text:
Q: Instaciate a generic type Consider the following generic class:
class MyClass<T>{
    T field;//ok
    public void method (T t){...}//ok
    public <E> MyClass(E[] e){
        E ee= new E();// compile error
        T t= new T();// compile error
    }
}

Why we cant instanciate of T and E? We know all about of types T,E at run time. I think that the type parameters T,E can be considered as a some reference type.


text:
Q: Implementing material design icons for iOS and mobile Safari I'm using some material icons in a web project.
Now the Google documentation states that the icon font for the web works specifically on retina displays (which by my understanding refers to Apple devices):
https://google.github.io/material-design-icons/#icon-font-for-the-web

Supported by all modern web browsers.
Vector-based: Looks great at any scale, retina displays, low-dpi
  display screens.

However it goes on to state:

The icon font contains 750+ icons and weighs in at only 40KB (woff2
  format). In comparison, a ZIP file of these in SVGs will be more than
  50% larger.

I am currently using the self hosted version of the icon font which only refers to the woff2 format and declares the font like so:
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v8/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}

I then call the icons with ligatures:
<i class="material-icons">face</i>

Now when the documentation and my web project are viewed using mobile Safari on iOS devices such as iPhone and iPad they do not display at all (the icons that do display are a different icon font):
Is there a way to resolve this issue? Does the .svg format need including for example?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Terraform Cloud - Local file not created in specificed location Code
resource "local_file" "sample" {
    content = "some text"
    filename = "${path.module}/sample.txt"
 }

File path details

*

*module

*

*local

*

*test.tf --- here I pasted the above code

*main.tf

*var.tf

After terraform apply I couldn't see the sample.txt in any of the folder.
Everything looks good. I can see the log as local_file creation but in the specified location new file not created. I'm trying this from windows 10. Also tried from gitlab pipeline cant see the file. Terraform version 14.9 and local provider version is ~2.1.
Please provide a solution for this


text:
Q: How to make an alias and work in sh for all users (not in bash)? My question maybe is silly, but how can I make an alias so as to work
in sh for all users?
I know that I can put an alias, let say this one:
alias ls='ls -l'

in /etc/bash.bashrc so as to work in bash but what is the equivalent
for the sh?
I tried to put is in /etc/profile but doesn't work.

A: After put your alias in /etc/profile exec follow command:

source /etc/profile

Try this solution and feedback here.

A: tl;dr
In general you can't.

Wikipedia says that for the POSIX shell (sh) startup/shutdown scripts are

Unspecified (.profile given as an example)

And I haven't found even this example in POSIX.1-2017.
In practice /etc/profile and ~/.profile are sourced (at least in Linux, by few sh implementations I worked with). In the context of your question the problem is they are sourced only by login shells. Not every shell is a login shell. Not every interactive shell is a login shell.
Additionally the sole concept of login shell seems not to be defined by POSIX (somebody correct me if I'm wrong). This document doesn't specify -l as a required option of sh, although in practice many implementations use it to force the login shell behavior.
Even if /etc/profile was parsed by a (((…-)grand-)grand)parent process of your current non-login shell, there's no way you inherited aliases defined there because aliases cannot be exported; they don't propagate within the environment like exported variables do. A function instead of an alias won't help you either.
My conclusion is: in general you cannot expect sh to source any file automatically. To make every sh source a specific file where your alias is defined, you need to find (or write) an implementation that does this.
A user can source a file by hand with . /path/to/file.

There is, however, an approach that allows you to make ls work like ls -l. You can do this by a wrapper script that replaces /bin/ls and exec-s to /bin/real_ls -l "$@" (where real_ls is the real ls renamed). Such approach is not uncommon, compare this answer. There are disadvantages and pitfalls though.

*

*If the real ls is a symlink to a swiss-army-knife binary like busybox, the binary will get confused if it's called by the name real_ls.

This is easily avoided by using /another/dir/ls instead of real_ls. But even then

*

*a future system update may overwrite your custom /bin/ls.

Now this can be avoided by leaving the real ls as /bin/ls, placing your custom ls in /another/dir and adding the /another/dir to PATH as the first entry for all users (this you can usually do via /etc/profile). But then

*

*every script that uses ls and the modified PATH variable (as opposed to /bin/ls, full path) will find your custom ls.

This may backfire easily. If you had an alias, a script (running in a subshell, not sourced) wouldn't inherit it. A script can define an independent alias for itself, anyway ls inside the script doesn't depend on any "external" alias; but it may easily depend on whatever executable ls resolves to. Changing the behavior of ls for every user may upset them a little, they will hopefully adjust in their interactive shells though. But changing the behavior of ls for every existing script is wrong, especially because ls is defined by POSIX and the definition explicitly states its behavior should depend on the presence of -l option. Replacing ls with your custom ls where ls and ls -l are equivalent will break its POSIX compliance.
OK, ls is not the best example here, because one shouldn't parse its output anyway. On the other hand you never know in what ways users (mis)use any tool.
Also note it's possible to have an implementation of sh where ls is a builtin. In this case mangling with /bin/ls or/and PATH cannot override what plain ls means; an alias or a function can.

If you'd like to have a "global" alias with another name, e.g.
alias ll='ls -l'

then switching to a /bin/ll script looks perfectly safe to me. ls stays intact, nothing is broken. The script may look like this:
#!/bin/sh
exec ls -l "$@"


text:
Q: My dialog is not being correctly displayed I have created a custom dialog layout and I am trying to display the dialog as a Activity instead of inflating the view inside the alert dialog. But the dialog is not being displayed as desired. Please have a look.
Custom Dialog Layout

The dialog activity is being shown like below

You can take a look at the code below
MainActivity
public class MainActivity extends AppCompatActivity {

    private static final int PROFILE_PHOTO = 1;

    private ImageView mImageView;

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

        mImageView = findViewById(R.id.image);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageOptionsDialog();
            }
        });
    }

    private void showImageOptionsDialog() {
        Intent imageDialogIntent = new Intent(this, ImageDialogActivity.class);
        startActivityForResult(imageDialogIntent, PROFILE_PHOTO);
    }
}

ImageDialogActivity
public class ImageDialogActivity extends AppCompatActivity {

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

activity_image_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/sixteen"
    android:clipToPadding="false"
    tools:context=".ImageDialogActivity">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="@dimen/eight"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/label_profile_pic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="24dp"
                android:layout_marginEnd="8dp"
                android:layout_marginRight="8dp"
                android:text="@string/label_profile_photo"
                android:textColor="@color/primary_text"
                android:textSize="@dimen/dialog_label"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <View
                android:id="@+id/divider"
                android:layout_width="match_parent"
                android:layout_height="@dimen/divider_height"
                android:layout_marginTop="40dp"
                android:background="@color/secondary_text"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/option_gallery" />

            <Button
                android:id="@+id/btn_cancel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="@drawable/cancel_button_bg"
                android:text="@string/action_cancel"
                android:textAllCaps="false"
                android:textAppearance="@style/TextAppearance.AppCompat.Small"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/divider" />

            <TextView
                android:id="@+id/option_gallery"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="32dp"
                android:drawableTop="@mipmap/ic_pick_img"
                android:drawablePadding="@dimen/eight"
                android:gravity="center"
                android:text="@string/option_gallery"
                android:textColor="@color/primary_text"
                app:layout_constraintEnd_toStartOf="@+id/option_remove_pic"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/label_profile_pic" />

            <TextView
                android:id="@+id/option_remove_pic"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:drawableTop="@mipmap/ic_remove_pic"
                android:drawablePadding="@dimen/eight"
                android:gravity="center"
                android:text="@string/option_remove_photo"
                android:textColor="@color/primary_text"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toEndOf="@+id/option_gallery"
                app:layout_constraintTop_toTopOf="@+id/option_gallery"
                app:layout_constraintVertical_bias="0.0" />

        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</android.support.constraint.ConstraintLayout>

Manifest
<activity
    android:name=".ImageDialogActivity"
    android:theme="@style/Theme.AppCompat.Light.Dialog" />

I'm not able to figure out the issue. Please help. Regards!

A: It is worked for me
DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        dialog.getWindow().setLayout((6 * width) / 7, LinearLayout.LayoutParams.WRAP_CONTENT);


text:
Q: Как нажать на JS кнопку через консольное приложение C# .NetCore? Пишу консольное приложение на .Net Core, мне нужно открыть веб-страницу и нажать на ней JS кнопку по ID, как это сделать?

A: Selenium Web Driver
http://www.seleniumhq.org/projects/webdriver/
Подойдет для этих целей


text:
Q: Can I get the referrer with JavaScript? I am creating a badge for my website.
UPDATE and CHANGE the question body
I'm trying to send the URL of the page that contain my badge back to my site when someone clicks the badge.

A: You can get the referrer with document.referrer, but bear in mind this may not be set. Proxies often send a different one or strip it, and I don't think you can check X_FORWARDED_FOR in JavaScript.

A: Try this:
<script>
alert(document.URL);
</script>

Mozilla Dev Center is really good and complete -- a great resource. You can find it  here.


text:
Q: Time functions in C? I have to find the date 4,000,000 seconds from now. I can get the correct answer if I add 4,000,000 to secondsSince1970, but I was wondering why it doesn't work if I add 4,000,000 to now.tm_sec?
int main(int argc, const char * argv[])
{
    long secondsSince1970 = time(NULL) + 4000000;

    struct tm now;

    localtime_r(&secondsSince1970, &now);

    printf("The date from 4,000,000 seconds from now is %i-%i-%i\n", now.tm_mon + 1, now.tm_wday, now.tm_year + 1900);
}

Output:
The date is 10-1-2012

int main(int argc, const char * argv[])
{
    long secondsSince1970 = time(NULL);

    struct tm now;

    localtime_r(&secondsSince1970, &now);
    now.tm_sec += 4000000;

    printf("The date from 4,000,000 seconds from now is %i-%i-%i\n", now.tm_mon + 1, now.tm_wday, now.tm_year + 1900);
}

Output: The date is 8-4-2012

A: Your struct tm is just a bunch of variables that get filled in by localtime_r. After the call to localtime_r, assigning to one of these variables will not magically make the other ones change their values.

A: Adding a value to tm_sec is simply changing the integer member of now.  The easiest way to do what you are trying to do is to pass the struct tm into mktime to convert it back into a time_t.  Then call localtime_r on the resulting value.
void
add_seconds(struct tm* broken, int num_seconds) {
   time_t then;
   broken->tm_sec += num_seconds;
   then = mktime(broken);
   localtime_r(&then, broken);
}

int
main(int argc, char const* argv[]) {
    time_t secondsSince1970 = time(NULL);
    struct tm now;
    localtime_r(&secondsSince1970, &now);
    add_seconds(&now, 4000000);
    printf("The date at 4,000,000 seconds from now is %i-%i-%i\n",
           now.tm_mon + 1, now.tm_mday, now.tm_year + 1900);
    return EXIT_SUCCESS;
}

A: It is incorrect to do this:
now.tm_sec += 4000000;

You tm_sec needs to be between 0 and 59 (60 for leap second).
You would need to do something like:
now.tm_sec += 4000000;
now.tm_min += now.tm_sec / 60; now.tm_sec %= 60;
now.tm_hour += now.tm_min / 60; now.tm_min %= 60;
etc.


text:
Q: __shared__ variable behaving oddly CUDA Consider the Below code Which runs under 9us on K20 :
__global__ void histogram( unsigned char *inputPointer, int *outputPointer)
{

    __shared__ unsigned char localDispersedHistogram[ 256  ] [ 32 ];
    __shared__ unsigned int partHist[ 256 ] ;

    int i ;
    int tx = threadIdx.x;
    int pixelOffset = (blockIdx.x * blockDim.x) +  threadIdx.x;
    uint8_t val = inputPointer[ pixelOffset ];

    uint8_t  data = val/ 8 ;
    uint8_t  position = val % 8 ;

    /**Trying to avoid loops thats why this code */
    localDispersedHistogram [  tx ] [  tx % 32 ] = 0 ;

    __syncthreads();

    TURN_ON( localDispersedHistogram [  tx ] [  data ] , position );

     __syncthreads();

    partHist[ tx ] = 0;

    int k = 0 ;
    for ( int i = 0 ; i < 256 ; i ++ ) {
        k++;
    }

}

Now the below code take 72us on access of shared Variable:
__global__ void histogram( unsigned char *inputPointer, int *outputPointer)
{

    __shared__ unsigned char localDispersedHistogram[ 256  ] [ 32 ];
    __shared__ unsigned int partHist[ 256 ] ;

    int i ;
    int tx = threadIdx.x;
    int pixelOffset = (blockIdx.x * blockDim.x) +  threadIdx.x;
    uint8_t val = inputPointer[ pixelOffset ];

    uint8_t  data = val/ 8 ;
    uint8_t  position = val % 8 ;

    /**Trying to avoid loops thats why this code */
    localDispersedHistogram [  tx ] [  tx % 32 ] = 0 ;

    __syncthreads();

    TURN_ON( localDispersedHistogram [  tx ] [  data ] , position );

     __syncthreads();

    partHist[ tx ] = 0;

    for ( int i = 0 ; i < 256 ; i ++ ) {
        partHist[ tx ]++;
    }

}

Why should the shared access make such a huge difference?
I understand shared access is expensive than register access but if you look in the above code, the line
TURN_ON( localDispersedHistogram [  tx ] [  data ] , position );

is also using shared variable, how come the manipulation of localDispersedHistogram takes less time , only the partHist access is taking crazy time ?
Help.
Update:
My Apologies:
My kernel configuration is <<< 256 , 256 >>>
FULL Code:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <conio.h>

#define SIZE_OF_OUTPUT_ARRAY 256 * 256 * 256
#define SIZE_OF_INPUT_ARRAY 256 * 256

#define TURN_ON(DATA,POSITION) (DATA|=(1<<(POSITION)))

__global__ void histogram( unsigned char *inputPointer, int *outputPointer)
{
    #if 1
    __shared__ unsigned char localDispersedHistogram[ 256  ] [ 32 ];
    __shared__ long long partHist[ 256 ] ;

    int i ;
    int tx = threadIdx.x;
    int pixelOffset = (blockIdx.x * blockDim.x) +  threadIdx.x;
    uint8_t val = inputPointer[ pixelOffset ];

    uint8_t  data = val/ 8 ;
    uint8_t  position = val % 8 ;

    for ( int j =  0 ; j < 32 ; j++) {
        localDispersedHistogram[ tx ] [ j ] = 0;
    }

    __syncthreads();

    TURN_ON( localDispersedHistogram [  tx ] [  data ] , position );

     __syncthreads();

    //partHist[ tx ] = 0;

    int sum = 0 ;

    for ( int i = 0 ; i < 256 ; i ++ ) {
        sum += (localDispersedHistogram [  i ] [  tx/ 8 ] & ( 1 << (tx % 8 ))) >> (tx % 8 ) ;
    }
    partHist[ tx ] = sum;

    atomicAdd( &outputPointer[ tx ] , partHist[ tx ]  );

    #endif

}

int main()
{

    #if 1
    printf(" Code Name, Sad buddy 17 ");

    unsigned char *inputPointer = (unsigned char * ) malloc (SIZE_OF_INPUT_ARRAY);

    for ( int i = 0 ; i < SIZE_OF_INPUT_ARRAY ; i ++ ) {

        int t = rand() % 256 ;
        //int t = 0;
        inputPointer [ i ]   = t;

    }

    unsigned char *device_inputPointer;
    int  *device_outputPointer;

    cudaMalloc((void**)&device_inputPointer, SIZE_OF_INPUT_ARRAY);
    cudaMemcpy( device_inputPointer,  inputPointer , SIZE_OF_INPUT_ARRAY, cudaMemcpyHostToDevice );
    cudaMalloc((void**)&device_outputPointer, 256 * sizeof ( int ) );
    cudaMemset(device_outputPointer,0,256 * sizeof ( int ) );

    histogram <<< 256 , 256 >>>  ( device_inputPointer , device_outputPointer  );

    unsigned int *output = ( unsigned int * )malloc ( 256 * sizeof( int ));

    cudaMemcpy( output,  device_outputPointer , 256 * sizeof( int ), cudaMemcpyDeviceToHost );

    unsigned int CPUHist [ 256 ]  ;
    unsigned int GPUHist [ 256 ]  ;

    for ( int i = 0 ; i < 256 ;i ++ ) {
        CPUHist[ i ] = 0;
        GPUHist [ i ] = 0;

        //printf( " %d " ,  inputPointer[ i ]);
    }

    for ( int i = 0 ; i < SIZE_OF_INPUT_ARRAY ; i++ ) {
        CPUHist[ inputPointer [ i ] ] ++;
    }

    int flag = 0 ;
    for ( int i = 0 ; i < 256 ;i ++ ) {
        printf(" %d  GPUHist  %d CPUHist\n" , output[ i ] , CPUHist[i]);

        if (output[ i ] != CPUHist[i]  ) {
            flag = 1 ;
        }
    }

    printf("\n\n======================\n\n");

    if ( flag ) {
        printf("TEST CASE FAIL ");
    }
    else {
        printf("TEST CASE Pass");
    }

    printf("\n\n======================\n\n");

    cudaDeviceReset();

    #endif
    getch();
    return 0;
}

A: Since you haven't actually posted both complete cases for comparison, I'm inferring your two cases based on your first posting and your update.
When you have code like this:
int sum = 0 ;

int k = 0 ;
for ( int i = 0 ; i < 256 ; i ++ ) {
    k++;
}

partHist[ tx ] = sum;

atomicAdd( &outputPointer[ tx ] , partHist[ tx ]  );

(or even if your k variable is replaced by sum, it does not matter) the compiler can figure out what will always end up in partHist[tx] without actually running any of the previous code.  Therefore it can optimize the previous code out (i.e. delete it) and still get the same result, and it will do so.  The code execution is therefore very much shorter, and you are getting the ~9us timing result.
On the other hand, when your code is as posted:
int sum = 0 ;

for ( int i = 0 ; i < 256 ; i ++ ) {
    sum += (localDispersedHistogram [  i ] [  tx/ 8 ] & ( 1 << (tx % 8 ))) >> (tx % 8 ) ;
}
partHist[ tx ] = sum;

atomicAdd( &outputPointer[ tx ] , partHist[ tx ]  );

Then this code depends on the preceding code to determine the result, and the compiler cannot optimize it out.
You can get additional confirmation of this perhaps by compiling with no optimization (nvcc -G ...) or else using cuobjdump -sass mycode to dump out the generated assembly code in each case, and you will discover a major difference in the kernel code at the assembly level, due to compiler optimization.
Whenever relative small changes are made to a code, and huge changes in execution timing occur, we should always suspect a compiler optimization side-effect.


text:
Q: How to upgrade to 10.5.1 using Azure Cloud Builder I installed ArcGIS Enterprise 10.5 in Azure using the Azure Cloud Builder, now I need to upgrade my portal to 10.5.1. How can I upgrade to 10.5.1 using Cloud Builder or do I have to manually upgrade?

A: At the time of writing, deployments built with the Azure Cloud Builder can be manually upgraded just as you do on-premises installations.
For 10.5 to 10.5.1, this should not cause any issues on Azure.  However, depending on your IT recovery strategy, you may want to do this on a staging environment first or make use of Azure Cloud Backup so you can roll back if you encounter any issues.
Run the upgrade in the following order:
Perform the upgrade steps for each ArcGIS Enterprise software component in the following order:

*

*Portal for ArcGIS

*ArcGIS Web Adaptor (for Portal)

*ArcGIS Server (upgrade hosting server first, then any other servers)

*ArcGIS Web Adaptor (for Server)

*ArcGIS Data Store (upgrade primary first, then stand-by)

Further Reading:

*

*ArcGIS Updates & Azure

*Upgrade ArcGIS Enterprise
// EDIT
As of 10.6, the builder now supports upgrades. Check this video.

A: In addition to the manual upgrade procedure - you can make use of Azure Cloud builder to upgrade dot-versions. IE. From 10.6 to 10.6.1
If you've deployed 10.6, you'd need to get the 10.6.1 version of Cloud Builder. Running against your instance you'd have the option to upgrade.
This has been explained in the upgrade deployment help topic. Note - this topic is only available for 10.6/10.6.1, inferring that the 10.5 to 10.5.1 must be done manually.


text:
Q: How to change Bool value within a function in javascript? Based on this tutorial: link
Here is my example code:
function modifyVar(obj, val) {
  obj.valueOf = obj.toSource = obj.toString = function(){ return val; };
}

function setToFalse(boolVar) {
  modifyVar(boolVar, 'false');
}

var isOpen = true;
setToFalse(isOpen);
console.log('isOpen ' + isOpen);

How can I change the bool variable value within a function?
Is it possible to pass the bool value by reference?
thanks in advance

A: We can use that.
var myBoolean = { value: false }

//get
myBoolean.value;

//set
myBoolean.value = true;

A: Several problems there:

*

*'false' is not false.

*Variables are passed by value in JavaScript. Always. So there is no connection whatsoever between the boolVar in setToFalse and the isOpen you're passing into it. setToFalse(isOpen) is processed like this:

*

*The value of isOpen is determined

*That value (completely disconnected from isOpen) is passed into setToFalse

*JavaScript has some interesting handling around primitive types: If you try to use them like object types (var a = 42; a.toFixed(2); for instance), the value gets promoted to a temporary object, that object is used, and then the object is discarded. So if obj is false, obj.anything = "whatever" ends up being a no-op, because the object that temporarily exists ends up getting released as soon as the line finishes.
You could do something like what you're doing by promoting isOpen to an object via new Boolean, but beware that it will then act like an object, not a boolean:

function modifyVar(obj, val) {
  obj.valueOf = obj.toSource = obj.toString = function(){ return val; };
}

function setToFalse(boolVar) {
  modifyVar(boolVar, false);
}

var isOpen = new Boolean(true); // An object
setToFalse(isOpen);
snippet.log('isOpen ' + isOpen);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

That works because the value in isOpen is a reference to an object. So when that value is passed into setToFalse as boolVar, boolVar's value is a copy of that reference, and so refers to the same object. So that sorts out issue #2 above. Issue #3 is solved by creating an object explicitly, rather than relying on the implicit behavior.
But, remember my warning above about how it will act like an object (because it is one), not like a boolean? Here's an example:

function modifyVar(obj, val) {
  obj.valueOf = obj.toSource = obj.toString = function(){ return val; };
}

function setToFalse(boolVar) {
  modifyVar(boolVar, false);
}

var isOpen = new Boolean(true); // An object
setToFalse(isOpen);
snippet.log('isOpen ' + isOpen);
if (isOpen) {
  snippet.log("isOpen is truthy, what the...?!");
} else {
  snippet.log("isOpen is falsey");
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

We see:

isOpen false
isOpen is truthy, what the...?!

...because isOpen contains a non-null object reference, and non-null object references are always truthy.

A: You are passing boolean primitive variable isObject. For primitive types it doesn't make sense to try to set toString method, because it's not needed (and used), since in ECMAScript spec there are already defined rules for to String conversion.
If you really want to use modifyVar function like you are trying, you can work with Boolean object instead of primitive:
function modifyVar(obj, val) {
  obj.valueOf = obj.toSource = obj.toString = function(){ return val; };
}

function setToFalse(boolVar) {
  modifyVar(boolVar, 'false');
}

var isOpen = new Boolean(true);
setToFalse(isOpen);
console.log('isOpen ' + isOpen);

So the answer: use new Boolean(true) or Object(true).

A: I am not sure but you are assigning false in single quote, value withing single/double quotes will be considered as string. Just use modifyVar(boolVar, false); and try.


text:
Q: Excel, copy data in same column (Same worksheet), replacing blank lines, but not replacing next line with data This seems like it is very easy, but I have not written VBA in a few years.
The file I'm working with has set formats when I receive it.  I have to UnMerge columns (which works okay).
Then I need to Select range to be copied, Select copy range and then move the range up one line so I can paste data.
Can someone help with this last part?  I can't seem to get the move up, to select the correct range to select.
The paste is okay.
Sub unMerge()

    Range("A9:B5000").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.unMerge

End Sub

Sub CopyRange()

Dim R As Range

    Range("A10").Select
    Selection.copy
    Range(Selection, Selection.End(xlDown)).Select
    ActiveCells = "R"
    ActiveCells = "R" - 1 'This is the line I really need help with.
    ActiveSheet.Paste
    Selection.End(xlDown).Select


text:
Q: How tall is the monster at the end of The Cloverfield Paradox? Assuming the thing's feet were at sea level, how tall would the monster we saw roaring above the cloud deck at the end of The Cloverfield Paradox have to be for us to see what we saw?

A: We have two pieces of evidence to work with in determining the creature's height, the clouds and the capsule.
The cloud layer appears to be altostratus clouds, which form no lower than 2000 meters up.  We can see different types of cirrus clouds above this layer, and nothing that would indicate we were looking at a layer of lower level stratus clouds instead of altostratus.
The capsule didn't match any known reentry vehicle, though it did have the usual conical shape and rounded stony-looking heat shield.  If we assume the return vehicle had a reentry profile like the Apollo command module then the drogue chutes should have been deployed at around 7300 meters.  We saw no chutes as the capsule plunged into the cloud bank.
So using this guesswork we have the creature two kilometers tall at the low end and seven or more kilometers tall at the upper end.

A: I haven't seen The Cloverfield Paradox, but since I think they were landing by the Atlantic Ocean, I calculated to see his height differently. What if he were actually standing on the sea floor? So my math should yield the creature at a maximum height of over 32,000 feet.


text:
Q: foreach data on bootstrap slider showing data in rows This is code for image slider with little bit text on image. This code showing images in a rows.
But I want to make it slider. So, please help me.
                  <?php $isFirst = true; ?>
                  <?php foreach ($summaries as $key => $Summary){  ?>

                        <?php
                            if($Image){
                          ?>
                            <?= $this->Html->image('../img/'.$Image[0]['Image']['name'],array('class' =>"img-responsive imgslider"));  ?>
                        <?php } else{ ?>
                            <?= $this->Html->image('new_dummy.png',array('class'=>'img-responsive imgslider')); ?>
                        <?php }; ?>

<?= $Summary['Summary']['dhalao_id']?  $Summary['Dhalao']['name'] : 'Root'; ?>

Quantity Report: <?= $Summary['Summary']['time_created'] ;?> && Time: <?= $Summary['Summary']['date_created']; ?>

                  <?php $isFirst = false; ?>
                  <?php }; ?>

Here, I created $isFirst variable, what stays true until first slide has been printed. This way we can add active class for first slide and not for others.

A: please use default format of php. start with  tag in line

and apply condition like following:
<div class="item <?php echo ($isFirst) ? ' active' : '' ; ?>">

A: if you are using bootstrap the html of carousal is like this :

     <?php $isFirst = true; ?>
                      <?php foreach ($summaries as $key => $Summary){  ?>

                            <?php
                                if($Image){
                              ?>
                                <?= $this->Html->image('../img/'.$Image[0]['Image']['name'],array('class' =>"img-responsive imgslider"));  ?>
                            <?php } else{ ?>
                                <?= $this->Html->image('new_dummy.png',array('class'=>'img-responsive imgslider')); ?>
                            <?php }; ?>

<?= $Summary['Summary']['dhalao_id']?  $Summary['Dhalao']['name'] : 'Root'; ?>

Quantity Report: <?= $Summary['Summary']['time_created'] ;?> && Time: <?= $Summary['Summary']['date_created']; ?>

                      <?php $isFirst = false; ?>
                      <?php }; ?>

        Previous

        Next


text:
Q: Append a column of NA values: lit() and withColumn() giving error I am trying to append a column of null values to a SparkR DataFrame with the following code:
w <- rbind(3, 0, 2, 3, NA, 1)
z <- rbind("a", "b", "c", "d", "e", "f")
x <- rbind(3, 3, 3, 3, 3, 3)

d <- cbind.data.frame(w, z, x)
B <- as.DataFrame(sqlContext, d)

B1 <- sample(B, withReplacement = FALSE, fraction = 0.5)
B2 <- except(B, B1)

col_sub <- c("z", "x")
B2 <- select(B2, col_sub)

B2 <- withColumn(B2, "w", lit(NA))

But, the last expression returns the error: Error in FUN(X[[i]], ...) : Unsupported data type:  null. I have used the lit operation to produce a column of null values before, but I'm not sure why it won't work this time.
Also, this has been discussed on SE before, see this question. I'm completely clueless as to why my expression yields that error. For reference, I'm using SparkR 1.6.1.

A: No matter if it works or not adding column this way is not a good practice. Since the only practical reason to add column which contains only undefined values is  enforcing specific schema for unions or external writes you should always use columns of specific type.
For example:
withColumn(B2, "w", cast(lit(NULL), "double"))

A: Spark columns can have types numeric, character.  My understanding is that it is intended that columns of other data types are illegal.
NA is not recognized by SparkR in the same way that R recognizes it as being an indicator of a missing value.  SparkR sees NA as being a value of type logical.  For example:
dtypes(NA)

unable to find an inherited method for function 'dtypes' for signature '"logical"'
If you try to add a column of NA's, Spark tries to create a column of type logical, which is not a valid data type for a column.  Hence the error.
There are a couple of places where SparkR (1.6.2) is inconsistent in trapping errors around creating illegal column types.  As you found, SparkR throws an error if you use lit(NA), but SparkR will let you convert an R data.frame with a column of NAs and it successfully creates an illegal column of type "logical"
x <- c(NA,NA,NA, NA, NA)
dfX <- data.frame(x)
colnames(dfX) <- c("Empty")
sdfX <- createDataFrame(sqlContext, dfX)
str(sdfX)

'DataFrame': 1 variables:
 $ Empty: logi NA NA NA NA NA


text:
Q: How can a static variable from other file accessed here on the C program below? #include <stdio.h>
#include <stdlib.h>
int function(int);

int main()
{
    int a=1;
    extern b;//can be only declared
    printf("a=%d\n",function(a));
    printf("b=%d\n",value());
    return 0;
}
int function(int v)
{
    return v+1;
}

In file1.c :
static int b=20;

int value() //can't be used on a static function
{
    return b;
}

In the code above though I've made variable b as static, it's accessible from other files. How can it be accessed, as the static keyword shouldn't allow the variable to be accessed from other files right? I'm bit confused.

A: This statement
static int b=20;

means the variable b will only be visible in its translation unit i.e. in file1.c, in which you have defined it.
In the main(), which is supposed to be in a different file, you have only declared b but not used it. Try to use it and you will find that linker will fail because it will not find the definition of b.
int main()
{
    int a=1;
    extern int b;    // note the type int in declaration. You have missed it.
    printf("access b = %d\n", b);   // <==== this won't work
    return 0;
}

Try to compile your program with above changes and you will see that the linker will throw error.
With above mentioned changes in main(), just remove the static keyword from variable b definition in file1.c file and above program will link successfully because then b will be a global variable which has external linkage.
From the value() you are returning the value that variable b hold which has nothing to do with whether b is static or non-static.
The lifetime of a static variable is the entire run of the program. You can access the static variable outside of it's scope/translation unit if you have the address of that static variable. Check this:
File file1.c :
#include <stdio.h>

static int b = 20;

int * retaddr_b (void) {
    return &b;
}

void print_b (void) {
    printf ("b = %d\n", b);
}

File main.c:
int * retaddr_b (void);
void print_b (void);

int main(void)
{
    print_b();                 // print static variable b value
    int * ptr_b = retaddr_b(); // ptr_b pointing to b
    *ptr_b = 99;               // dereference ptr_b and assign different value
    print_b();                 // print static variable b value
    return 0;
}

Output:
b = 20
b = 99

A: Its not really accessed there, dint you see below warning when compiled:
warning: type defaults to 'int' in declaration of 'b' [-Wimplicit-int]
All you are doing is printing the return value from function value.
if you really wanted to see whether it is accessed or not check as below:
comment your printf("b = %d\n",value()); and use printf("b = %d\n",b);
in its place then compile and check.


text:
Q: Remove the Report a map error from google map I have a v3 google map and in the bottom-right corner of the map, there is a "Report a map error" link overlaid onto the map.  Does anyone know if it is possible to remove this from the map?
Edit:
Here is an example of what I mean: http://jsfiddle.net/ahfA5/

A: An issue with the custom style map is that when switching back from map/satellite or street view it does not return to the custom style instance.
// remove the wrapping container
.gm-style-cc:last-child {
    display: none !important;
}
// remove the link only
a[title="Report errors in the road map or imagery to Google"] {
    display: none !important;
}

A: There isn't a way to disable this feature properly via the API.
Keep in mind, if you hide it without using the API it will violate the Google Maps API Terms of Service which, as of the date of this post, doesn't allow developers to manipulate this link. Refer to 10.1.1.f.x:

delete, obscure, or in any manner alter any brand features, logos, warnings, notices... or links that appear in the Service or the Content;

A: The example presented here does works:
var styleOptions = {
        name: "Dummy Style"
    };

 var MAP_STYLE = [
    {
        featureType: "road",
        elementType: "all",
        stylers: [
            { visibility: "on" }
        ]
    }
];
var mapType = new google.maps.StyledMapType(MAP_STYLE, styleOptions);
map.mapTypes.set("Dummy Style", mapType);
map.setMapTypeId("Dummy Style");

Initially the map get displayed WITHOUT the link on the Default map!
BUT
upon selecting either:
the MAP/Terrain or the SATELLITE/Label from the menu the Report map error link RETURNS on the map refresh.
If you choose as an alternative to create a StyledMapType MAP.
The Report a map error link can be disabled permanently on the StyledMap.
But you now have two MAPS (Default and the StyledMap).
I couldn't find a way to hide the default map.
Bottom line I couldn't remove the link Report a map error from the Default map permanently.

A: You could style the map to get rid of this. Check this out.
Notice that if you compare the first two screenshots, the "Report a map error" link is present in the first, but not in the second.
The simplest way to apply a dummy style to the map so that it still looks like google maps but without the error link would be to do the following:
const styleOptions = {
  name: `Dummy Style`,
}

const MAP_STYLE = [
  {
    featureType: `road`,
    elementType: `all`,
    stylers: [{ visibility: `on` }],
  },
]
const mapType = new google.maps.StyledMapType(MAP_STYLE, styleOptions)
map.mapTypes.set(`Dummy Style`, mapType)
map.setMapTypeId(`Dummy Style`)

Here's the updated JSFiddle.

A: You can not do this - Google's attempt at providing accurate data via crowd-sourcing will cause this on occasion. Live with it and accept that limitation. you can layer a custom element on top of the canvas if you position it absolute or fixed. But that kind of violates their TOS as it also covers the copyright notice.

A: You can hide it using CSS trick. It's dirty but working:
/* remove ugly google report-a-bug button from maps */
.gmnoprint:last-child {
    display: none !important;
}


text:
Q: Subset a dataframe if its date is larger than a date of another dataframe I have 2 dataframes as follows:
C1
Date|Artist
01-11-1955|M
18-01-1956|M
19-04-1956|M
01-05-1956|M
21-11-1956|X

T1
Date|Artist|FeatArtist
06-11-1955|UNK|M
15-01-1956|M|UNK
15-04-1956|UNK|M
06-05-1956|UNK|M
25-11-1956|X|UNK
25-11-1956|M|UNK

I want to be able to subset T1 if the T1$Artist == C1$Artist| T1$FeatArtist == C1$Artist and T1 date happened after C1 Date
The result should be:
T1
Date|Artist|FeatArtist
06-11-1955|UNK|M
06-05-1956|UNK|M
25-11-1956|X|UNK

I tried:
t<- T1[which(T1$Artist%in% unique(C1$Artist) | T1$FeatArtist%in% unique(C1$Artist)& T1$Date > max(C1$Date)),]

but didn't work out - any idea how I can achieve this please?

A: T1$Date=as.Date(strptime(T1$Date,"%d-%m-%Y"))
C1$Date=as.Date(strptime(C1$Date,"%d-%m-%Y"))

e=quote(Date.x>Date.y&Date.x-Date.y<7)
a=subset(merge(T1,C1,by="Artist",all=TRUE),eval(e))
b=subset(merge(T1,C1,by.x="FeatArtist",by.y="Artist",all=TRUE),eval(e))
rbind(a,setNames(b,names(a)),row.names=NULL)[-4]

    Artist     Date.x FeatArtist
12       X 1956-11-25        UNK
1        M 1955-11-06        UNK
121      M 1956-05-06        UNK


text:
Q: CMake error when trying to add opencv libraries I am trying to work with a depth sensor and trying to get the grayscale image and display it with OpenCV. I can access the data from the depth sensor without any issues. But I get the following errors when I try to include the OpenCV part in the CMakeLists.txt:
    CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_PREFIXES
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_FIND_LIBRARY_SUFFIXES
CMake Error at /usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:148 (message):
  Could NOT find CUDA (missing: CUDA_CUDART_LIBRARY) (found suitable exact
  version "8.0")
Call Stack (most recent call first):
  /usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:388 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake/Modules/FindCUDA.cmake:958 (find_package_handle_standard_args)
  /usr/local/share/OpenCV/OpenCVConfig.cmake:67 (find_package)
  /usr/local/share/OpenCV/OpenCVConfig.cmake:86 (find_host_package)
  share/royale-config.cmake:38 (find_package)
  CMakeLists.txt:6 (find_package)

My CMakeLists.txt looks like the following:
cmake_minimum_required(VERSION 2.8)

set(CMAKE_PREFIX_PATH "share")

find_package(royale REQUIRED)

find_package(OpenCV REQUIRED)

link_directories(${royale_LIB_DIR})

project (depthDataCallBack)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/inc)

add_executable(depthDataCallBack depthDataCallBack.cpp)

target_link_libraries(depthDataCallBack "${royale_LIBS}")

target_link_libraries(depthDataCallBack ${OpenCV_LIBS})

I am new to CMake. So any and all help will be appreciated. Thanks!

A: project() call should precede most of other commands call.
Normally, only cmake_minimum_required() and variables assignments may come before the project().
Correct:
cmake_minimum_required(VERSION 2.8)

set(CMAKE_PREFIX_PATH "share")

project (depthDataCallBack)

find_package(royale REQUIRED)
find_package(OpenCV REQUIRED)
link_directories(${royale_LIB_DIR})

...


text:
Q: Can anyone explain to me what this query does? I need the riposte in layman's language.
SELECT
    t1.*
    , IF(isBranch='true','',IF(pointsweightage IS NULL,'Not Set',pointsweightage)) AS w
    , t2.id AS wid
FROM
    `skills_hierarchy` t1 LEFT JOIN
    weightage t2 ON t1.pointsweightage=t2.weightage
WHERE
    isBranch='false'
    AND t1.deptid=$deptid
    AND t2.deptid=$deptid

I want the Query to be changed such that it gets me the data of the department which it does login.

A: Well, I'm going to re-format this a bit to help you out, then I'll explain below.
SELECT
    t1.*,
    IF(isBranch='true',
        '',
        IF(pointsweightage IS NULL,
            'Not Set',
            pointsweightage)) AS w,
    t2.id AS wid
FROM `skills_hierarchy` t1
    LEFT JOIN weightage t2
        ON t1.pointsweightage=t2.weightage
WHERE isBranch='false'
    AND t1.deptid=$deptid
    AND t2.deptid=$deptid

The "Select" portion gets you all values from the "skills_hierarchy" table, then a value for a column called "w".  This value will be one of three things.

*

*An empty value if isBranch is equal to true

*A Value 'Not Set' if pointsweightage is null

*The value of pointsweightage if 1 and 2 do not apply

The query is already filtering out results based on a parameter value of $deptid


text:
Q: Cloud Functions for Firebase - GeoFire implementation Implementing GeoFire as follow:
const GeoFire = require('geofire');
const geoFire = new GeoFire(admin.database().ref().child('geolocation'));

In database onWrite:
const promises = [];
promises.push(geoFire.set(id, [37.79, -122.41]));
return Promise.all(promises);

In the code below I do a geoquery:
exports.nearbyjobs = functions.database.ref('/users/{userid}/account/l').onWrite(event => {
  const location = event.data;
  if (location.child("lat").val() === null || location.child("lng").val() === null) return;
  const key = event.data.key;
  const uid = event.params.userid;
  const results = geoFire.query({
    center: [location.child("lat").val(), location.child("lng").val()],
    radius: 3000
  });
});

My question and problem is how de I handle the results from geofire query? I need to have the query result in my DB updating in real time.

A: Try something like this...
var arr = [];
var onKeyEnteredRegistration = results.on("key_entered", function(key, location, distance) {
      console.log(key + " entered query at " + location + " (" + distance + " km from center)");
//each location is added to the array
      arr.push[{'key':key, 'location':location, 'distance':distance}];
    });

Good luck.


text:
Q: Fedora 32 terminal alert volume too loud I recently upgraded my laptop to Fedora 32. After the upgrade the system alert in the terminal is unbearably loud. Other system alerts are fine and follow the overall volume settings. The issue is only in the terminal.
I have tried alsa mixer and PulseAudio Volume control.
How do I set the gain on terminal alerts?


text:
Q: Processing multiple Symfony bundle configs with one bundle I have lots of bundles which have similar config files called rules.yml held in BundleName/Resources/config/rules.yml
Each config file follows the same structure:
bundle_name:
    rules:
      name:
      items: []
      requirements: []

I have one bundle called RulerBundle. This bundle needs to automatically load, validate and combine all the rules.yml found within the other bundles. I would like RulerBundle to produce something like:
bundle_a:
    rules:
      name: Rule 1
      items: ['First Item']
      requirements: ['Second Item', 'Third Item']
bundle_b:
    rules:
      name: Rule 2
      items: ['Second Item']
      requirements: ['Third Item']

This should be automatically updated when a new bundle is added with a rules.yml
Questions

*

*Should I validate and process the config within every bundle? This will lead to code duplication as the validation rules will just be same.

*How would I go about finding and merging each of the bundle configs with the RulerBundle

A: So to that you can write a DependencyInjection extension in your top level bundle that will do all of the validation. Not sure what should happen if something is invalid but you could something like this:
// src/BundleName/DependencyInjection/BundleExtension.php
namespace Acme\HelloBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class BundleName extends Extension implements PrependExtensionInterface
{
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        foreach ($bundles as $name => $extension) {
            $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.$name.'/../../Resources/config'));
            // load the configuration file, returned as an array
            $config = $loader->loadFile('rules.yml');

            // validate the contents of your file
            $this->validateConfig($config);

            // append the config with the specified bundle name "bundle_a", "bundle_a"
            $container->prependExtensionConfig($name, $config);
        }
    }
}

haven't tested any of that but generally that is the base idea. You'll need to implement your config validation method.


text:
Q: Extract specific text from PDF - iText I am currently reading a page from PDF file. I would always like to extract specific text from the page. Can I do this easily if I know the internal structure of the PDF? If yes, how? Below is what I have:
public  void read(PdfReader reader) throws IOException{
    StringBuilder sb = new StringBuilder();
    sb.append(PdfTextExtractor.getTextFromPage(reader, 1));
    System.out.println(sb.toString());
    System.out.println("Text Line: " + sb.toString().substring(43,47));

}

The line
System.out.println("Text Line: " + sb.toString().substring(43,47));

is what I am concerned about. Is there a better way to do things other than using substring?
Text Extract from PDF:
SUPPLEMENT # :
1
RC :
2
D  :
0
R :
2
W: TOTAL :
0 0


text:
Q: PyQt5 Convert 2d np array to QImage from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImage
import numpy as np
import sys

def print_np():
    app = QApplication(sys.argv)

    win = QWidget()
    label = QLabel()

    img = np.ones((500, 500))
    qImg = QPixmap(QImage(img.data, img.shape[0], img.shape[1], QImage.Format_Indexed8))
    label.setPixmap(qImg)

    vbox = QVBoxLayout()
    vbox.addWidget(label)
    win.setLayout(vbox)
    win.show()

    sys.exit(app.exec_())

In this code, I am trying to display 2d np array on QtWindow.
I am expecting to see a white square, but I keep getting a weird display as below.
I believe its because wrong QImage.Format (data type), so I tried every option but didn't help.
https://srinikom.github.io/pyside-docs/PySide/QtGui/QImage.html#PySide.QtGui.QImage
Should I change np array to jpg or png first, as examples in documentation?

A: There are a couple of issues:

*

*Your dtype needs to be np.uint8 when you create your Numpy image array

*Your format needs to be QImage.Format_RGB888

*Your pixels need to bigger than 0 or 1 to show up, the full range is 0..255

So, with that in mind:
#!/usr/bin/env python3

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImage
import numpy as np
import sys

def main():
    app = QApplication(sys.argv)

    win = QWidget()
    label = QLabel()

    img = np.zeros((500, 500, 3), dtype=np.uint8)
    # Turn up red channel to full scale
    img[...,0] = 255
    qImg = QPixmap(QImage(img.data, img.shape[0], img.shape[1], QImage.Format_RGB888))
    label.setPixmap(qImg)

    vbox = QVBoxLayout()
    vbox.addWidget(label)
    win.setLayout(vbox)
    win.show()

    sys.exit(app.exec_())

main()

++ (to convert 2D image as black vs white)
img = np.zeros((500, 500), dtype=np.uint8)
img[250:, :] = 255

qImg = QPixmap(QImage(img.data, img.shape[0], img.shape[1], QImage.Format_Grayscale8))

It will create a window

Keywords: Python, Qt, QImage, QPixmap, image processing.


text:
Q: Ruby on rails cocoon gem - unable to capture callback events Hi I am currently using the cocoon gem for my rails app and it seems to be working fine since I was able to add and remove the nested associations in my form. However, when I try to console log the callbacks (e.g. "cocoon:after-insert"), there is no console log fired on the console. What could be the reason for this and how can i capture the callback event in my console? I have the gem remotipart bundled in my app too, if this would offer any clue as to why I have been unable to capture the callbacks on my console. Her are my codes:-
#new.html.erb

  <%= form_for [@strategy,@goal], :html => {:class => 'ui form'}, :remote => true do |f| %>

      <%= f.label :title %>
      <%= f.text_field :name %>

      <%= f.fields_for :tactics do |tactic| %>
        <%= render 'tactic_fields', f: tactic %>
      <% end %>

      <%= link_to_add_association "Add", f, :tactics %>

      <%= f.button :submit => "", class: "ui button" %>

  <% end %>

#_tactics_fields.html.erb

    <%= f.label :tactic %>
    <%= f.text_field :name %>

    <%= f.label :rating %>
    <%= f.text_field :rating %>

  <%= link_to_remove_association "delete", f %>

# application.js
$(document).on('turbolinks:load', function() {
  $('#tactical_field').bind('cocoon:before-insert', function() {
     console.log('helloworld');
    });
});

A: You have to make sure the event is captured on a surrounding div. Also you do not need the turbolinks code, you can simply do something like
$(document).on('cocoon:after-insert', '.content form', function(e) {
  console.log('Something');
});

So in short: listen to events on the complete document, if we capture a cocoon:after-insert event, from .content form we log something.


text:
Q: Aiming a 3D ray in space at a specific target by rotating a parent matrix I've got a weird problem I've been trying to solve for a few days and I'm wondering if someone can help me out.
I have the following pieces of information:

*

*A standard PSR (position, scale, and rotation) matrix

*An origin point in 3D space defining the starting point of a ray

*A normal vector in 3D space relative to #2 that defines the ray direction

*A target point in 3D space

The ray origin and normal can be located anywhere in 3D space, but they must be parented to the matrix described in #1 (which itself can have any initial rotation and/or position within 3D space).
What I need to do is to calculate the rotation of the parent matrix to ensure that the ray origin and ray direction are aligned in such a way that the ray is guaranteed to intersect with the target point, preferably using an up vector for alignment if there is more than one possible solution.
Is there any straightforward way to calculate this?
EDIT:
Here's some pictures that show exactly what I'm trying to do. Apologies for the confusion!
In this picture, the orange cube represents the parent matrix (with no rotation), the yellow sphere represents the ray origin, and the blue arrow represents the ray direction. There's also an up vector and target point.

I need to rotate the matrix the ray origin and direction are parented to so that the ray points directly at the target object, with the ray origin falling on a 2D plane defined by the parent matrix position, target point, and up vector.

Here's a third example showing how the ray direction now points directly at the target point.

And finally here's another picture that roughly shows how the entire thing needs to be aligned with the up vector.

The primary problem here is that nothing is constant- the parent matrix offset (read: position) could change, or the ray origin and direction could change. The target point will also move around, as can the up vector- meaning that I need to figure out how to realign everything as the objects shift around in 3D space.


text:
Q: Running multiple SQL statements using Boto3 and AWS Glue I would like to run multiple SQL statements in a single AWS Glue script using boto3.
The first query creates a table from S3 bucket (parquet files)
import boto3

client = boto3.client('athena')

config = {'OutputLocation': 's3://LOGS'}

client.start_query_execution(QueryString =
        """CREATE EXTERNAL TABLE IF NOT EXISTS my_database_name.my_table (
          'apples' string,
          'oranges' string,
          'price' int

        ) PARTITIONED BY (
          update_date string
        )
        STORED AS PARQUET
        LOCATION 's3://LOCATION'
        TBLPROPERTIES ('parquet.compression' = 'SNAPPY');""",
        QueryExecutionContext = {'Database': 'my_database_name'},
        ResultConfiguration = config)

This only creates the table. Then I have to run the following query in order to update the partitions and insert the data.
client.start_query_execution(QueryString =
        """MSCK REPAIR TABLE my_database_name.my_table;""",
        QueryExecutionContext = {'Database': 'my_database_name'},
ResultConfiguration = config)

Unfortunately, when I run the above statements in a single GLUE script, the partitions are not updated (only the table is created). I have to separate them in two jobs.
Is it possible to have a single scripts that can execute multiple queries in a sequence?
Using Glue Crawlers is not an option

A: You should explore the alternative of using partition projection which removes the need of loading partition via repair table or crawlers. See the docs: https://docs.aws.amazon.com/athena/latest/ug/partition-projection.html


text:
Q: Hunt for Sylvanas: Where is Tobias Mistmantle? I am a level 12 worgen hunter. I have only one quest available in Gilneas City (The Hunt for Sylvanas). It tells me to follow Tobias Mistmantle, but I cannot find him on the map anywhere. I don't have any other quests to do, and I cannot find a flight master to go somewhere else.

A: Go to where you picked to quest, restart the quest and when you take the quest, walk out of the back door and follow the canal to the left. Tobias will appear there. And he doesn't wait you must stay close to him for completing the quest.
For seeing and not missing him make sure you open your nameplates from UI settings


text:
Q: Radius of Convergence ratio test using the ratio test for the following
sum from n = 0 to infinity of
$$
\sum_{m=0}^{+\infty}\frac{(-1)^m}{(m!)^2} x^{2m +10}
$$
I need to find the radius of convergence. I managed to get up to $|x|^2$ $\lim$ as n approaches $∞$ of $\frac{-1(m!)}{m+1}$ but then what is the limit of that?

A: The series is dominated (in absolute values) by
$$
x^{10}\sum_{m=0}^\infty \frac{(x^2)^m}{m!}=x^{10}e^{x^2}
$$
so absolute convergence is ensured for all $x\in\Bbb R$.


text:
Q: R - Why does sapply return lists within this dataframe when searching for values in another dataframe? I have the following two 2 data.frames:
df1
structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1,
1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305,
4455134, 4398594), post_id_unique = c("1-NA", "1-post-1", "2-NA",
"2-post-2", "2-post-2", "2-post-2"), to = list(NULL, 1L, NULL,
    2L, 2L, 2L)), .Names = c("thread_id", "course_week", "user_id",
"post_id_unique", "to"), row.names = c(NA, 6L), class = "data.frame")

df2
structure(list(thread_id = c(1L, 1L, 2L, 2L, 2L, 2L), course_week = c(1,
1, 1, 1, 1, 1), user_id = c(1237305, 3001241, 1237305, 1237305,
4455134, 4398594), post_id_unique = c("1-post-1", "1-post-1125",
"2-post-2", "2-post-3", "2-post-43", "2-post-54")), .Names = c("thread_id",
"course_week", "user_id", "post_id_unique"), row.names = c(NA,
6L), class = "data.frame")

I am trying to replace df1$to with the value in df2$user_id that matches the $post_id_unique column in both files.
I've made the following code for it:
from <- as.list(df1$post_id_unique)
replace <- function(i){if(grepl("NA",i)!=TRUE) {df2[df2$post_id_unique==i,1]}}
df1$to <- sapply(from, replace)

Which works almost perfectly... except that every value within df1$to is a list rather than a numeric or character vector:
'data.frame':   6 obs. of  5 variables:
 $ thread_id     : int  1 1 2 2 2 2
 $ course_week   : num  1 1 1 1 1 1
 $ user_id       : num  1237305 3001241 1237305 1237305 4455134 ...
 $ post_id_unique: chr  "1-NA" "1-post-1" "2-NA" "2-post-2" ...
 $ to            :List of 6
  ..$ : NULL
  ..$ : int 1
  ..$ : NULL
  ..$ : int 2
  ..$ : int 2
  ..$ : int 2

Why is my original code creating lists within the dataframe? How can I unlist them? Or avoid them to start with.
I know this is similar to a merge(), but I am interested in doing it this way for learning and other reasons.

A: The "problem" is that sometimes your replace() function doesn't return a value (when the i value contains "NA"). Since sapply always returns an object with the same length as the input, NULL values are returned for the function. NULLs cannot be placed in a simple vector, so the result of sapply is cast to a list. you can fix this by returning a NA instead of nothing
replace <- function(i){if(grepl("NA",i)!=TRUE) {df2[df2$post_id_unique==i,1]} else {NA}}

But really it looks like you are doing a basic left merge operation. The basic syntax would be
merge(df1, df2, by="post_id_unique", all.x=T)


text:
Q: 'ResultSet' object has no attribute 'to_csv' I need to present the result of the query from database in csv format using python.
from influxdb import InfluxDBClient
client = InfluxDBClient(host='192.168.0.110', port=8086)
client.get_list_database()
client.switch_database('Mlogi_ALL')
res= client.query('SELECT * FROM n')
print(res)

The above line of codes retrieves the query result as:

Out[5]: ResultSet({'(u'n', None)': [{u'sid': 3, u'time': u'2018-07-04T04:58:22Z', u'M': u'01081093', u'N': u'01081093', u'iid': u'0', u'V': 4, u'sd': u'0', u'ides': u'0'}, {u'sid': 3, u'time': u'2018-07-04T04:58:22Z', u'M': u'01081093', u'N': u'01081093', u'iid': None, u'V': 4, u'sd': None, u'ides': None}

Now I need these results in form of csv, so the next line of code is :
res.to_csv("/home/rahul", sep=",", encoding="utf-8")
But here I get the following error:

Traceback (most recent call last):
File "", line 1, in
      res.to_csv("/home/surya", sep=",", encoding="utf-8")
AttributeError: 'ResultSet' object has no attribute 'to_csv'

How to rectify this, I have seen few ResultSet errors on stackoverflow but I'm unable to retrieve my results to csv format.


text:
Q: Return data from PHP back to a javascript file? I have a comments section on my websites that uses jQuery to animate comments in without reloading the page, as well as deleting comments.
Right now, I have it so when you write a comment, it sends it to a external JS, then to a php file where it processes. If it was successful, it will append the comment into the comment section. My delete action: jQuery deletes my the comment ID in the mysql database.
So my issue is I want to add a delete button via jQuery and somehow call back to the javascript file and tell it the id so the delete button knows the ID to put in the form so the delete file knows what to delete?
Here's my add_comment script:
$(function() {

$(".commentbutton").click(function() {

$.ajax({
  type: "POST",
  url: "http://myflashpics.com/process_addcomment.php",
  data: $("#commentform").serialize(),
  success: function() {

    var theComment = $("#commentsss").val();
    var theUserId = $("#user_id_two").val();
    var thePhotoId = $("#photo_id").val();
    var theProfilePicture = $("#user_profile_picture").val();
    var theUsername = $("#user_username").val();

    // Get new HTML data
    var html = "

" + theUsername + "

" + theComment + "

";

    // Append, then fade in
    $(html).hide().appendTo(thecommentsdisplay).fadeIn(500);

  }
 });
return false;
});
});

Thanks in advance!Coulton
EDIT 1:
Here's my comments form (just to clarify):
user_id_two (the user's ID)
commentsss (comments field)
photo_id (the id of the photo being commented on)
user_profile_picture (profile to display on the user's profile picture in the banner)
user_username (username of the user commenting)

Here's also my delete button form:
<form method='post' action='' name='deleteform' id='deleteform'>
<input type='hidden' name='userid' value='<?php echo "$userid_session"; ?>' />
<input type='hidden' name='userpass' value='<?php echo "$password_session"; ?>' />
<input type='hidden' name='pictureid' id='pictureid' value='<?php echo "$picture_id"; ?>' />
<input type='hidden' name='profilepictureid' id='profilepictureid' value='<?php echo "$user_profile_picture_id"; ?>' />
</form>

And lastly my DELETE COMMENT jQuery:
$(function() {

$(".commentdeletebutton").click(function() {

 var className = $(this).attr('class');
 var theID = className.replace(/delete_button commentdeletebutton delete_(\d+)/, "$1");
 commentDone = "#comment_" + theID;
 formDone = "#commentdeleteform_" + theID;

 $.ajax({
  type: "POST",
  url: "http://myflashpics.com/process_deletecomment.php",
  data: $(formDone).serialize(),
  success: function() {

    $(commentDone).hide();

  }
 });
return false;
});
});

A: If you add an  link for deleting, you can insert the complete url for deleting in the href, i.e. http://myflashpics.com/process_removecomment.php?id=xx.
So, you can bind a click event to that link and get the right url using $(this).attr('href') and doing the delete using ajax.
Edited for a more complete sample:
<? [[Loop your recordset]] { ?>

    <a href="http://myflashpics.com/process_deletecomment.php?id=<?=$id?>">Delete

        [[Comment content...]]

<? } ?>


text:
Q: detect two files in a folder in a batch file I need a code that detects if there is two files with the same extension and i need it to execute a different code.

*

*Detect if the folder is two *.txt files i need it to

*Echo there is two text files in this folder please remove one and continue
But if there is only one text file keep the code running
Im currently using this code to detect whether there isn't any files in the folder
If not exist Files\*.txt echo there is no lyrics

Maybe if we could combine this as well something like
  if text file equal to 0 echo no lyrics

  if text file equal to 1 echo.

  if text file Gtr 1 ech there is more than on text file in the folder

The code will be used twice one for text file and the other for .ogg audio files
Thanks

A: DIR /B lists files, one per line, without header or footer info
FIND /C counts the number of matching lines, /V "" matches any line
FOR /F processes the results of a command
for /f %%N in ('dir /b "Files\*.txt" ^| find /c /v ""') do (
  if %%N equ 0 echo No lyrics
  if %%N equ 1 echo(
  if %%N gtr 1 echo There is more than one text file in the folder
)


text:
Q: How to transform the column values to another pattern in DataFrame, Python? The values in 2nd-8th columns in DataFrame named df has a pattern like {'close': 'time1', 'open': 'time2'}, for example, {'close': '21:00', 'open': '11:00'}.
How can I change all the values that have this pattern to time2-time1, such as 11:00-21:00?

A: use the `apply function to call a custom algorithm to manipulate your dictionaries:
df.Monday.apply(lambda d: '-'.join([d['open'], d['close']])
                          if isinstance(d, dict) else d)


text:
Q: Remove some of the background noise to get clear microscopic image I have a microscopic image (img1).

I need to analyse it to be like the following image (img2):

But how do I do it in Mathematica (I am using Mathematica 9)? I am not much familiar with the processing of images.
I have tried using TotalVariationFilter. After using this the image looks like the following (img3):

Now the problem is that the particles look blur (hezzy).
The code I have used:
filtered = TotalVariationFilter[imj, 0.4]

So is there any option to bring the particle bright and clear remaining all other things unchanged?

A: Try ComponentMeasurements
pic=[![enter image description here][1]][1]

cells = ComponentMeasurements[pic // Binarize, {"Centroid",
"EquivalentDiskRadius" },  #AdjacentBorderCount == 0 &&100 < #Area &];
HighlightImage[pic, Circle @@@ cells[[All, 2]]]

Graphics[Circle @@@ cells[[All, 2]]]

shows the plot with the selected circles only.

A: I do not know what your aim is. For the present, I assume that you want to count points of a given size. We proceed as follows:
First we copy the picture and make it black and white picture:
im1 = ImageAdjust[im0]
im2 = Binarize [im1]

Then we pick dots that have an area in a given range. E.g. big dots:
 ComponentMeasurements[im2, "Area", (100 < #Area < 300) &]

(*{1 -> 290.25, 138 -> 114.625, 166 -> 168.25, 285 -> 265.875,
 318 -> 146., 500 -> 247.875, 503 -> 173.75, 655 -> 111.5,
 736 -> 114.875, 778 -> 125.25, 869 -> 186., 888 -> 122.875,
 891 -> 147.5, 1027 -> 125.5, 1056 -> 171.75, 1147 -> 143.625,
 1158 -> 146.375, 1198 -> 224.25}*)

Finally we count them:
ComponentMeasurements[im2, "Area", (100 < #Area < 300) &]  // Length

(* 18 *)

A: Here's my trial, which is v9 compatible:
img = (* Copy and paste the image here *);

comp = SelectComponents[Binarize[img, 0.6], "Area", # > 80 &]

mask = Dilation[comp, 5];
HighlightImage[img, mask, Method -> "Boundary"]

ImageFilter[Mean@Flatten@# &, img, 7, Masking -> ColorNegate@mask]

Parameters like 0.6, 80, etc. are all determined by trial and error.


text:
Q: How to access last upgrade date and version in postgres Is there any way i can get information about upgrades, downgrades performed on a postgres 12.3 database  : such as the last upgrade date and version ?
I'm thinking of something that mimicks DBA_REGISTRY_HISTORYin oracle

A: In general there are no "patch set" or "service pack" for PostgreSQL but only full releases: every quarter a new release that includes bug fixes is released (see https://www.postgresql.org/docs/release/).
To install these new releases  executables are just replaced as a whole: no patching of current executables is done and this change for related instances and databases is not registered in any system catalog.


text:
Q: Detecting pixel colour from "dynamic" image scraped online I'm new to python and opencv. I'm trying to learn both at the same time to make things more interesting.
I was trying to detect if certain pixels in an image online are of a certain colour (green). The image online would always be updated so the pixels in question wouldn't always have the same colour, hence the urllib.
I used a loop to go through all the specific pixels I wanted to check.
import urllib.request
import cv2
# import numpy as np

def download_status(url):
    urllib.request.urlretrieve(url, "boxes.jpg")

# List with representative pixels of each box, total 8 boxes
box_cords = [[62, 42], [144, 42], [234, 42], [312, 42], [62, 133], [144, 133], [234, 133], [312, 133]]

# List describind box status/colour; 0-gray 1-green
box_status = [[0], [0], [0], [0], [0], [0], [0], [0]]

download_status("https://image.ibb.co/chtUW6/boxes.png")

box_scheme = cv2.imread("boxes.jpg")
for box in box_cords:
    box_colour = box_scheme[box]
    #  print(box_colour)
    if box_colour == "[51 204 52]":
        box_status[box] = 1

#  print(box_status)

Unfortunatly I'm getting a warning: "FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison"
Also while debugging by printing variables that express colour, I always get the same values (255 255 255). And I'm not sure If I'm comparing the colours in the loop correctly in terms of syntax, which is quite probably the reason for the warning.
I treid searching for the warning and of ways to do what I'm trying to achieve but failed to find anything useful..
Thanks in advance!


text:
Q: AS2 textField hyperlink I have to add something to an existing as2 project. I know as3 pretty well, but as2 doesn't make sense to me at all. Basically what I have to do is add a link to the bottom of every "page". The link changes depending on what "page" you are on. I have variables passing, so all I need to do is create the link.
//Url gets passed here
var urlString;

createTextField("urls", 1, 300, 499, 150, 30);
urls.setNewTextFormat(my_fmt);

urls.text = urlString;

Now I have to turn "urls" into a link. What would be the best way to do this?

A: This would be one possible solution: Create a movieclip to hold the textfield and then use it as a button...
//Url gets passed here
var urlString = "the URL";
this.createEmptyMovieClip("urlHolder", 1);
urlHolder._x = 300;
urlHolder._y = 499;
urlHolder.createTextField("urls", 1, 0, 0, 150, 30);
//urlHolder.urls.setNewTextFormat(my_fmt);

urlHolder.urls.text = urlString;

urlHolder.onRelease = function(){
    getURL("www.google.com");
}


text:
Q: Chrome doesn't play mp4 after I install quicktime I'm designing a web page for old browsers that don't support <video>. Here is my code:

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>

    <embed src="http://www.w3school.com.cn/i/movie.mp4" />

    <object data="http://www.w3school.com.cn/i/movie.mp4"></object>

    <object data="http://www.w3school.com.cn/i/movie.mp4">
        <embed src="http://www.w3school.com.cn/i/movie.mp4">
    </object>

It works perfectly in Chrome. But when I test with Firefox, it asks me to install QuickTime 7. After I install QuickTime 7, Chrome suddenly can't play any video in the three tags. See the following pic.

A: I would recommend using a Flash fallback rather than a QuickTime fallback (Flash has a better adoption rate on old browsers).
You can find an example here or here. You need to include the flash fallback within the video tag (older browsers that do not know about the video tag will skip to the flash object tag)
If you need an open source flash player have a look at Strobe from OSMF.
For your issue with QuickTime it is probably some settings in Chrome, either try to troubleshoot your plugin settings or simply uninstall QuickTime 7 from your PC.
Tell us if it works for you.


text:
Q: Why can't I set the Resolution field in JIRA? I'm new to JIRA as an admin, and I'm wondering why my issues' Resolution field only seems to ever be either "Unresolved" or "Done"?
I suspect this has something to do with the simplified workflow that I chose for my projects? Is the best/right way to fix this adding extra transitions into the workflow?
Ultimately, all I'd really like is a way to mark as issue as cancelled (without actually deleting them). I don't really need to distinguish between invalid or won't fix, or any of that-- comments are fine for those purposes.
If it matters, these projects are all Kanban, and I'm using an agile board with a filter that pulls in multiple projects as my primary interface in JIRA.

A: I appreciate the suggested answers from other folks, but ended up going a slightly different route. Here's what I did:

*

*Edited all of my workflows to include an additional "Cancelled" status. This was done as statuses seem to work better with the Kanban boards than other options. (I'd initially tried just adding a new "Any --> Done" transition, but wasn't able to, since I already had one.)

*I set the status' "category" to "Done".

*In that status, I added a post function to set the issue's Resolution field to "Won't Do" (which was already there, apparently).

*I added the status to my board's "Done" column.

Now, when dragging issues over to the Done column, I'm offered a choice of two drop targets in that column: Done or Cancelled. Very slick!

A: I wouldnt add any other transition if it is not necessary, jsut for resolution field.
Go to your admin panel>issues>
almost at the end of the left menu, shows "Issues' attributes". There you can find "Resolutions" option. You can configure there your different values to resolution field.
** Maybe names of menu, are not exactly as i said you, cause my jira instance is in spanish.
Regards

A: I suspect that you are moving the JIRA's that are Unresolved to a kanban column other than done? If so, then you setup that transition to have a post function to put the resolution status as canceled when you drag it to the column. See this for how to do this:
https://confluence.atlassian.com/adminjiraserver070/advanced-workflow-configuration-749383189.html#Advancedworkflowconfiguration-postfunctions
Also, if you would like to change the resolution types for your system, you can do that as well (note: resolution types effect all projects; the entire JIRA system):
https://confluence.atlassian.com/jira/defining-resolution-field-values-185729576.html
Hope this helps!


text:
Q: Function to find minimum number of survivors Given are different types of cells, which can swallow their direct neighbors:

*

*Type X can swallow Type Y

*Type Y can swallow Type Z

*Type Z does nothing

Count the minimum number of survivors.

*

*Cells are represented by a 1-dimensional array.

*A cell can swallow only specified types, according to the above rules

*If there are multiple ways, choose the most optimal, minimising the number of survivors

## Example:

    C=[X,Y,Z,X,Z,Z,Y]

Answer is: 3.

* C0 swallows C1, [X,Z,X,Z,Z,Y]
* C5 swallows C4, then C3 [X,Z,X,Y]
* C2 swallows C3 [X,Z,X]

How can such a function be implemented?

A: We can make the following observations:

*

*If the list has no Y, then nothing can be swallowed

*If the list has only Y, then nothing can be swallowed

*In all other cases there is a possibility to swallow something, as that means there is an Y that has a neighbor that is not Y. If that neighbor is an X, then this Y can be swallowed by that neighbor, or if that neighbor is Z, then this Y can swallow that neighbor.

*An X cannot be swallowed, so all X remain.

We should therefore prioritise moves where an Y swallows a Z. This will not take away any possibility for an X to swallow an Y, ... so we can postpone those without risking to take a less optimal path.
When no more such moves are possible, perform the only remaining type of move, where an X swallows an Y.
If also that move is no longer possible we have arrived at a minimum.
To make sure the algorithm is efficient, the input could be stored in a linked list. The first step (where Y swallows Z) can be performed in one sweep through the linked list. If the current node is an Y and the previous node is a Z, then remove Z from the list, and keep the same node as current for the next iteration. If the previous node is not a Z, but the next node is, then remove the next node and keep the same node as current for the next iteration. If neither is true, make the next node the current node and repeat.
This has linear time complexity.
The next phase (where X swallows Y) follows the same principle.
Implementation
I will give here an implementation in Python. First follows the code for a generic doubly linked list, using a sentinel node:
class Node:
    def __init__(self, val, prev=None):
        self.val = val
        self.prev = prev or self
        self.next = prev.next if prev else self
        self.next.prev = self.prev.next = self

    def remove(self):
        self.prev.next = self.next
        self.next.prev = self.prev

class LinkedList(Node):
    def __init__(self, lst=None):
        super().__init__(None)  # A sentinel node
        if lst:
            node = self
            for val in lst:
                node = Node(val, node)

    def values(self):
        for node in self.nodes():
            yield node.val

    def nodes(self):
        node = self.next
        while node != self:
            yield node
            node = node.next

The actual algorithm would then look like this:
def swallow(c):
    ll = LinkedList(c)  # create doubly linked list for input

    for eater, food in ("YZ", "XY"):  # two phases
        for node in ll.nodes():
            if node.val == eater:
                while node.prev.val == food:
                    node.prev.remove()
                while node.next.val == food:
                    node.next.remove()

    return list(ll.values())  # return result as a standard list

You could call it as follows:
c = ["X","Y","Z","X","Z","Z","Y"]
print(swallow(c))  # ['X', 'X']

Alternative implementation
Instead of a linked list, you could also use a string and a regular expression to remove:

*

*any sequence of Y that occurs right before a Z

*any sequence of Y that occurs right after a Z

*any sequence of X that occurs right before an Y

*any sequence of X that occurs right after an Y

... in that order.
import re

def swallow(c):
    s = "".join(c)  # convert to string
    s = re.sub(r"Z+Y", "Y", s)
    s = re.sub(r"YZ+", "Y", s)
    s = re.sub(r"X+Y", "X", s)
    s = re.sub(r"YX+", "X", s)
    return list(s)  # convert back to list

A: You can see it as a typical branch and bound problem, like tic tac toe or other similar games, where you maximize a target function while you recursively search for the "best" move in a given position (C).
The following code demonstrates the principle.

*

*can-swallow-p checks if a neighbor can be swallowed and returns T or NIL.

*generate-moves generates a list of possible moves from a position.

*eval-position generates an integer value which denotes how "good" a position is.

*do-move takes a position and a move and returns the resulting position.

*maximize is the search function which looks for the best resulting position and its value.

With those functions in place, which in one form or another occur in any similar problem (often games), you can build a solution, which is basically a depth first recursive search.
Many algorithms are publicly known, to optimize the efficiency of the brute force version I wrote in my demo code below.
(defun can-swallow-p (position eater eatee)
  (if (< -1 eatee (length position))
      (let ((eater-value (aref position eater))
        (eatee-value (aref position eatee)))
    (cond
      ((and (eql eater-value :x) (eql eatee-value :y)) t)
      ((and (eql eater-value :y) (eql eatee-value :z)) t)
      (t nil)))
      nil))

(defun generate-moves (position)
  (let ((result nil))
    (if (= 0 (length position))
    nil
    (loop
      for i below (length position) do
        (let ((left (- i 1))
          (right (+ i 1)))
          (when (can-swallow-p position i left)
        (push (cons i left) result))
          (when (can-swallow-p position i right)
        (push (cons i right) result)))))
    result))

(defun eval-position (position)
  "From the question it is not clear, what is optimal.
So for the purpose of demonstration we choose, that
shorter positions are 'more optimal' than longer ones."
  (- (length position)))

(defun remove-at (sequence index)
  "Does not modify sequence.
Returns a copy instead, with item at index removed."
  (concatenate 'vector
           (subseq sequence 0 index)
           (subseq sequence (+ index 1))))

(defun do-move (position move)
  "Returns a new position, which results from the move.
move is a dotted pair of eater index and eatee index.
"
  (let ((eatee-index (rest move)))
    (remove-at position eatee-index)))

(defun maximize (position depth best)
  (let ((moves (generate-moves position)))
    (if moves
    (let ((value
        (loop
          for m in moves
          for child-position = (do-move position m)
          maximizing (maximize child-position (+ depth 1) best))))
        value)
    (let ((value (eval-position position)))
      (when (>= value best)
        (format t "~D ~A~%" value position))
      value))))

(defun analyze (position)
  (maximize position 0 (eval-position position)))

(defun test()
  (analyze #(:X :Y :Z :X :Z :Z :Y)))


text:
Q: Salesforce Describe Call on Sharing object Anyone has any idea on how to fetch sharing objects or sharing rules from describe call? I think its not feasible!
Thanks for you help,
Best,
Manju

A: The describe information is at the object and field level, whereas sharing rules are at the record level. So describe info won't tell you who can access a particular record.
The UserRecordAccess object can be queried to determine if a user has access to a single record or a group of records. (Note that you can query many records at the same time by using an IN clause with a list of recordids.)
http://www.salesforce.com/us/developer/docs/object_reference/Content/sforce_api_objects_userrecordaccess.htm

A: You can describe sObjects that hold sharing associated to particular records, but why would you need to? It's not like we can add any fields to them. To query them maybe? Works in REST API (/services/data/v26.0/sobjects/AccountShare) as well as in Metadata API.
You can describe sharing rules (I think it's a feature introduced in 2012). To do that check which metadata your Eclipse is retrieving, package.xml should contain entries similar to
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <name>AccountCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>AccountOwnerSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>CampaignCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>CampaignOwnerSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>CaseCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>CaseOwnerSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>ContactCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>ContactOwnerSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>LeadCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>LeadOwnerSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>OpportunityCriteriaBasedSharingRule</name>
    </types>
    <types>
        <members>*</members>
        <name>OpportunityOwnerSharingRule</name>
    </types>
    <version>26.0</version>
</Package>

And finally you can query the objects from (1) or - as mentioned by Bob - the UserRecordAccess table if you want to know about access to particular records.


text:
Q: Encrypt and decrypt a String in java I am new to cryptography. I wish to learn how to encrypt and decrypt the text in a file... when I refer the related articles in net. I had a doubt that whether the encrypted text will be same for single text when encryption is done multiple times on the same text? Can anyone please clear my doubt?

A:     public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Here's an example that uses the class:
try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

A:
I had a doubt that whether the
  encrypted text will be same for single
  text when encryption done by multiple
  times on a same text??

This depends strongly on the crypto algorithm you use:

*

*One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.

*Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

A: Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.


text:
Q: Can I block a PayPal contact from purchasing on my merchant account using the API? There are multiple malicious users attempting to pay using a single compromised PayPal account. Since this is detected later, I would like to block these PayPal accounts from purchasing from me again. Of course, I block them on the application level but they create new accounts using VPN and valid but compromised email addresses. I cannot block a PayPal account on my application since I receive an IPN after the payment is processed.
According to this I can block a contact from making purchases/sending messages etc. Is there a way to do this using the API for a merchant account?
As an alternative, I could probably issue a refund after checking the buyer information on the IPN but I would rather find a more "official" solution to this.


text:
Q: RewriteRule Slash Single Redirect I'm trying to create a new redirect for my v2.2 api.php file. The desired link is: website.com/api/v2.2/ but rewrite just works if I use _ instead of /:
website.com/api_v2.2/ (WORKS):
RewriteRule ^api_v2.2/?$ /api.php [NC,QSA,L]

website.com/api/v2.2/ (DON'T WORKS):
RewriteRule ^api/v2.2/?$ /api.php [NC,QSA,L]

Any idea?
I've tried these lines too, but nothing works:
RewriteRule ^api\/v2.2/?$ /api.php [NC,QSA,L]

RewriteRule ^(api)/v2.2$ api.php [QSA,NC,L]

A: Have you tried escaping the dot and slashes ?
RewriteRule ^api\/v2\.2\/?$ /api.php [NC,L]

The dot may cause problem here since it means "Any character" in the regex (source). Moreover, I don't think you need the QSA flag here.

A: I've moved the website.com/api.php file to website.com/api/api.php
and the new .htaccess url rewrite rule is:
RewriteRule ^api/v2.2/?$ /api/api.php [NC,L]