text:
Q: What is the probability that the distance between x and y is less than d?
Let $w$ and $d$ be positive real numbers. A point $x$ and a point $y$ are selected at random from the closed interval $[0,w]$ of the real number line. What is the probability that the distance between $x$ and $y$ is less than $d$? (Your answer should be a formula in terms of $w$ and $d$.)

My solution :
The distance between $x$ and $y$ is less than $d$ if and only if $|x - y| < d$. Geometrically, this means that we are looking for the probability that the points $x$ and $y$ lie within a strip of width $2d$ centered on the diagonal of the square $[0,w] \times [0,w]$.
The diagonal has length $\sqrt(w^2 + w^2) = \sqrt(2)w$, so the area of the square is $w^2$, and the area of the strip is $2dw$.
Thus, the probability that $|x - y| < d$ is the ratio of the area of the strip to the area of the square:
$P(|x - y| < d)$ = (area of strip) / (area of square) = $\frac{2dw}{w^2} = \frac{2d}{w}$.
Therefore, the probability that the distance between $x$ and $y$ is less than $d$ is $2d/w$
Is my solution correct?.
Thank you.


text:
Q: Should you use runnable even if the threads are not sharing data? I have been working on writing a multi threaded java program. Before I progress I was thinking how best I can write the program.
I read the differences between runnable and thread and what we should use and what we should not. However I have a question. Is it good to follow the runnable implementation to thread even if the threads are not sharing data i.e the same runnable class object?
I would end up creating different runnable objects thus occupying memory.
Also another idea I have is to pool runnable objects and change the value they hold and assign it to a thread. Thereby having only a set of runnable objects and thus utilizing memory better.
Sample Code:
public class MrRunnable implements Runnable {
    private String toFireUrl;

    MrRunnable(String url){
    }

    @Override
    public void run() {
        // do some function here
    }
}

public class Main {

    public static void main(String[] args) {
        // We will create 500 threads
        for (int i = 0; i < 500; i++) {
            Runnable task = new MrRunnable("some new url");
            Thread worker = new Thread(task);
            //start the thread
            worker.start();
        }
    }
}

Here I am creating a new instance of runnable objects and my threads don't share data.
So is this way justified? Or is it better to create a pool of runnable objects and I let my threads manipulate their content and use it?

A: Each thread you start allocates a call stack, sized by default at 1 Megabyte. Each MrRunnable you create allocates... 24 bytes. Keeping things in perspective helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to group the elements in an array based on status property in react? I have am array of object i.e. JSON like this in my react state and before rendering it I want it to sort based on status property example-
Actual Value
{
"list": [
{
   "id": "aac",
   "name": "James",
   "status": "active"
},
{
   "id": "gds",
   "name": "Alice",
   "status": "left"
},
{
   "id": "cvs",
   "name": "Kristy",
   "status": "active"
},
{
   "id": "cgt",
   "name": "Samaira",
   "status": "left"
},
]
}

Expecting Value after sorting based on status element
{
"list": [
{
   "id": "aac",
   "name": "James",
   "status": "active"
},
{
   "id": "cvs",
   "name": "Kristy",
   "status": "active"
},

{
   "id": "gds",
   "name": "Alice",
   "status": "left"
},

{
   "id": "cgt",
   "name": "Samaira",
   "status": "left"
},
]
}

A: This will sort alphabetically by status
arrayName.sort((objA, objB) => objA.status > objB.status ? 1 : -1)


text:
Q: When do I exactly need a pointer with structs I really do not understand if and when do I need to declare a pointer to my data struct.
I have two programs and both works the same, but I cant figure out where should I need a pointer or not.
Here are the programs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct data
{
    char *ptr;
};

void printStruct( struct data pers );

int main (void)
{
    struct data pers;   // Here pers is not a POINTER

    pers.ptr = malloc(sizeof (char) * 256);
    strcpy(pers.ptr, "Hello World");

    printStruct(pers);
    free(pers.ptr);
}

void printStruct( struct data pers ){
    printf("PTR = %s\n", pers.ptr);
}

When do I exactly need a pointer?
As you can see, here struct data pers; I declared a variable and in the next example I am using a pointer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct data
{
    char *ptr;
};

void printStruct( struct data *pers );

void printStruct( struct data *pers ){
    printf("PTR = %s\n", pers->ptr);
}

int main (void)
{
    struct data *pers;   // Here pers is a POINTER
    pers = malloc(sizeof(*pers));
    pers->ptr = malloc(sizeof (char) * 256);
    strcpy(pers->ptr, "Hello World");

    printStruct(pers);

    free(pers->ptr);
    free(pers);
}

A: There are four cases where you have to use a pointer to a struct:

*

*You want a function to write to a parameter of struct type:
struct foo { int member; }

void updateFoo( struct foo *bar )
{
  bar->member = some_new_value();
}

int main( void )
{
  struct foo f = {0};
  ...
  updateFoo( &f );
}

*You want to allocate one or more instances of a struct type dynamically:
struct foo *farr = malloc( sizeof *farr * NUM_ELEMENTS );

*You're using a struct type with a flexible array member:
struct foo { int x; char y[]; }

struct foo *instance = malloc( sizeof *instance + LENGTH_FOR_Y_MEMBER );

*You want to define a self-referential type (i.e., each instance of struct foo points to a different instance of struct foo:
struct list_node { int data; struct list_node *next; }

This is a common implementation of a singly-linked list - each element of the list explicitly points to the next element in the list (or NULL if at the last element).

You may also choose to pass a pointer to a struct to a function, even if the function doesn't modify the parameter, just to save the overhead of creating a copy in the called function, especially if the struct type is large:
struct ginormous { /* define many large members here */ };

void blah( const struct ginormous *g )
{
  // do stuff with g
}


text:
Q: Nested function for SLC-filling using Google Earth Engine JavaScript API I wrote a function to fill in a bitmasked and filtered SLC from Landsat 7. I want multiple inputs because I need to fill in the SLC with different values each time like the median reflectance, the mean reflectance etc. There is a similar question at GEE ImageCollection.map() with multiple-input function and I think I did the exact same thing but it doesn't work.
//Step 3 SLC-filling

var ReplaceFunction = function(replacement) {

  var Replace = function(Im) {
    var replaced = ee.Im.unmask(replacement)
    return replaced;
  }
  return Replace
}

var MedianReflectance = a2_lessthan50.median() //this is just calculating the median reflectance value
var ReplMedian = CollectionMapNoShadow.map(ReplaceFunction(MedianRefl)) //this is the collection that is masked and I want to fill in with the median values

The error I get is:

cannot read property "unmask" of undefined.

A: I believe my mistake was that I used ee.Im.unmask. Removing the ee. will make it work.
With ee you access server side functions and classes, but the moment you create an object by using that functionality it is already on server side.


text:
Q: Using Search Engine APIs to replace my own crawling (for non search engine purposes)? At the moment I am crawling a large number of predefined sites, looking for a very small number of particular documents of interest. Importantly, I am not crawling these sites to create my own search engine: it is specifically for retrieving the documents.
All of the major search engines have an API that I don't mind paying for, but they seem to be focused on using their API to make your own search engine.
For example: Yahoo BOSS TOS at http://info.yahoo.com/legal/us/yahoo/boss/tou/ . B.1(a) says "You are permitted to use the Services only for the purpose of incorporating and displaying Results from the Services as part of a Search Product deployed on Your Offering". So I can only use it for my own search engine.
Google only has the Custom Search Engine stuff, which again is not what I need.
Bing's API seems to be closer to what I need but then it's TOS require not removing certain pieces of information etc. But then again, it doesn't require me to only use it for implementing my own search engine (from what I can see).
Am I reading too much into this or is there a search engine that allows me to essentially use the results of their crawl of certain sites instead of my own for my product? Again, the search results themselves are not my product: it's what I do with the data in the documents that is.
Thanks for any tips.

A: You will not want to use a search engine to do this.
Search engines will not index all content on a site. If a site has lots of similar pages, for example, they will be thrown out. Sites with large number of pages will not be completely indexed.
You could potentially miss lots of pages this way.
Keep it crawling!
P.S.
Crawling individual websites often violates their TOS. If you care about that, also take care to adhere to robots.txt.


text:
Q: Diffing the bits of an integer I have a 32 bit integer which I fill with data by mapping the individual bits to various types of data.
For instance one section is used for oxygen level. It's a value from 0 to 128, so I use 7 bits for that.
Another section is used for the rotation of the object. Rotation is always either 0, 90, 180 or 270 degrees around the three axis x, y and z. Each angle is indexed with the values 0, 1, 2 and 3, so I only need 6 bits. Rotation is stored as 010101 for a rotation of 90 deg around x, y and z, or 100000 for a rotation of 180 deg around x.
Some of the sections are stored as integer values, like with oxygen level, but cast to enums when I need to use them.
Each of the sections are laid out next to each other in the data integer, filling the bits from right to left.
Type :    ... | Oxygen  | Rotation |
          --------------------------
Bits:     ... | 0000000 | 000000   |
          --------------------------
Position: ... | 19-25   | 26-31    |
          --------------------------

The problem
I would like to compare two integers and see what's changed.
When the oxygen level of one int is 16, and the other is 20, the difference is an increase of 4 units. When one rotation is 0 on all axis, and an other is 90 around x, the difference is a rotation around x of 90 deg.
I have extension methods on the data object that allows me to get the oxygen level as an int value, and the rotation as a quaternion. When using these on the delta data object, I would like to get the value 4 for oxygen level, and a quaternion for the rotation 90 deg around x.
Question
What's the most efficient way to get the difference in value of two integers?
Possible approaches
I've thought about a couple of different ways to approach this.
Integer comparing
Since the data is an integer, I tried to simply subtract one from the other. I started with an int with a value of 0 and set the bits for oxygen level to 16. I created a new int, set its oxygen level to 20, and subtracted the first from the last, and the oxygen level of the delta was 4. But as I added rotation and other data to the integers, the result after the subtraction changed the resulting oxygen level and rotation.
I need to verify that all my extension methods are working as intended. All unit tests succeeds, but the tests might not be good enough.
Bitwise comparing
Another approach was to compare each bit separately throughout the entire integer, using the various bitwise operators. I used an int with the rotation bits set to 90 deg around x (bits 01). Another int had the x rotation set to 180 deg (bits 10). The delta value I was looking for is 90 deg (bits 01), but I couldn't find any suitable operators to produce that result.
This test led me to believe that I can't compare bits separately. In the case of the rotation indexes, I need to look at a pair of bits as a single value.
BitArray
I read the documentation for .net's BitArray, but couldn't immediately see using that would make any difference.
Compare each section
Comparing each bit section would produce the result I'm looking for. The rotation bits would be converted to a quaternion before calculating the difference, and then converted back to bits before setting them in the data integer.
This is the approach I was hoping to find an alternative to. I didn't want the comparer to know the structure of the data, and I was hoping to find a more efficient solution.
Edit
I see now, after reading the comments and doing more testing, that it would be more beneficial for my case to get only the new value of a bit section, and not how much they changed. Any section that remains unchanged should be zeroed out. As far as I can see, my only option is to compare the data sectionwise.
Edit again
I'm not sure which answer to pick as the correct one. I don't think my question was specific enough, and am sorry for that.
The method given by @harold works when comparing bit by bit, and is independent of the data structure.
The answer by @Pikoh compares section by section, and can be made dynamic so that the method won't need to know about the data structure.

A: I am not exactly sure what you wanted, but it is certainly possible to compute the modular difference for all fields, using typical SWAR techniques:
z = ((x | H) - (y &~H)) ^ ((x ^~y) & H)

This is the general formula for SWAP subtraction. For 2-bit fields, H = 0xAAAAAAAA.
Since there are only two bits and SWAR usually treats the top bit differently (to prevent leaking into the next field), the bits are effectively totally separate.

With the new requirements it is also not necessary to do ugly splitting of the fields, for example: (not tested)
m = x ^ y;
m = (m | (m >> 1)) & 0x55555555;
m *= 3;
z = y & m; // maybe

The idea here is that a xor will produce a 1 somewhere in a field iff it has changed, then OR all bits of the field and put it in the lowest bit of the field, the multiplication by 3 broadcasts it to all bits of the field. & with the new value to get changed fields and zeroes elsewhere, but that means you cannot distinguish between "changed to 0" and "unchanged". Using m you can still distinguish them.

A: Let's see if something like this helps you:
int data1 = Convert.ToInt32("00000000000000000000000000011100", 2); //sample data
int data2 = Convert.ToInt32("00000000000000000000000000101000", 2);
int xrotationposition = 26; //start positions of data
int yrotationposition = 28;

string xrotationmask = new string('0', xrotationposition) + "11" +
                   new string('0',30 - xrotationposition); //mask to extract the data
string yrotationmask = new string('0', yrotationposition) + "11" +
                   new string('0', 30 - yrotationposition);

int xrotation1 = data1 & Convert.ToInt32(xrotationmask, 2); //bit AND
int xrotation2 = data2 & Convert.ToInt32(xrotationmask, 2);

int yrotation1 = data1 & Convert.ToInt32(yrotationmask, 2);
int yrotation2 = data2 & Convert.ToInt32(yrotationmask, 2);

xrotation1 = (xrotation1 >> 30 - xrotationposition); //shift the bits
                                                     to the lowest part of byte
xrotation2 = (xrotation2 >> 30 - xrotationposition);

yrotation1 = (yrotation1 >> 30 - yrotationposition);
yrotation2 = (yrotation2 >> 30 - yrotationposition);

At the end of this execution, you'll get xrotation1=1, xrotation2=2,yrotation1=3 and yrotation2=2, that seems easy values to compare.
Hope this helps


text:
Q: PyInstaller: cannot exclude a module I have compiled the exe of a .py file but the problem is that it is 200mb+
I would like to remove useless packages (for instance scipy that I am not using).
Still I have not clear the proper syntax of PyInstaller.
Let's start from the beginning...usually I do on cmd:
cd myFolder
C:\Python27\Scripts\Pyinstaller.exe MyFile.py

and it gives me the exe file in the dist folder.
If I want to set some configuration which is the proper way?
C:\Python27\Scripts\Pyinstaller.exe MyFile.py Config.py

or
C:\Python27\Scripts\Pyinstaller.exe Config.py

because online I found both of them but I could not distinguish.
If it is the last one I tried to run:
lock_cipher = None
a = Analysis(['Main.py'],
     pathex=['C:\Users\myname\Desktop\myFolder'],
     binaries=None,
     datas=None,
     hiddenimports=[],
     hookspath=None,
     runtime_hooks=None,
     excludes=None,
     cipher=block_cipher)
a.binaries = [x for x in a.binaries if not x[0].startswith("scipy")]
pyz = PYZ(a.pure, a.zipped_data,
     cipher=block_cipher)
exe = EXE(pyz)
coll = COLLECT(exe)

But it does not work. Where am I wrong?

A: My suggestion is that you use a virtual env containing only the required modules. It is a better development practice.
Also, you can use --exclude-module flag to list all the modules you want to exclude. (Pyinstaller automatically includes unneeded modules)


text:
Q: ContentPresenter in Templated Control not working I have created a templated control. All I did to the default style was add a content presenter. I also referenced the Generic.xaml in the App.xaml file.
<Style TargetType="local2:TestingControl" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local2:TestingControl">
                <Border
                    Height="200px"
                    Background="Green">

                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

public sealed class TestingControl : Control
{
    public TestingControl()
    {
        this.DefaultStyleKey = typeof(TestingControl);
    }

}

I haven't made any changes to the .cs code of the control.
I tried setting the content, but was told that the control does not allow direct content.
 <StackPanel>
        <local1:TestingControl >
            Testing
        </local1:TestingControl>

    </StackPanel>

What should i be doing to make use of the content presenter?
The same approach works perfectly if i try to use a user control.

A: To handle XAML content in a custom Templated Control you have to either derive your control from the ContentControl or stay inherited from a Control, implement a custom ContentProperty and bind a ContentPresenter to it.
Going with the ContentControl is a bit easier, and here's the code you'd probably end up with.
Style definition in Themes/Generic.xaml
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="using:SmallTests2018">

    <Style TargetType="local:TemplatedControlWithContent" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:TemplatedControlWithContent">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                        <Viewbox>
                            <Grid>
                                <Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                                    <Ellipse Width="10" Height="10" Fill="#80808080" />
                                </Viewbox>
                                <ContentPresenter />
                            </Grid>
                        </Viewbox>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

*

*I prefer to keep Border bound to the templated control properties, so a developer using it has more control over the looks.

*An ellipse here is an example of some extra custom content.

TemplatedControlWithContent.cs
using System;
using Windows.UI.Xaml.Controls;

namespace SmallTests2018
{
    public sealed class TemplatedControlWithContent : ContentControl
    {
        public TemplatedControlWithContent()
        {
            DefaultStyleKey = typeof(TemplatedControlWithContent);
        }
    }
}

*

*note that the only change here is that control is derived from ContentControl.

A test page TemplatedControlWithContentPage.xaml
<Page
    x:Class="SmallTests2018.TemplatedControlWithContentPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SmallTests2018"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <local:TemplatedControlWithContent>
        <TextBlock>Hello World!</TextBlock>
    </local:TemplatedControlWithContent>
</Page>

How it looks in the page XAML designer

A: While the answer posted by @DK. was perfect, I was trying to use a Control instead of a ContentControl. The reason why is because i'm simply messing around trying to familiarize myself with UWP.
His answer was extremely helpful in getting me to solve the issue for a control inheriting from Control.
TestingControl.cs
[ContentProperty(Name = "Content")]
public sealed class TestingControl : Control
{
    public TestingControl()
    {
        this.DefaultStyleKey = typeof(TestingControl);
    }

    public object Content
    {
        get { return (string)GetValue(ContentProperty); }
        set { SetValue(ContentProperty, value); }
    }

    public static readonly DependencyProperty ContentProperty =
        DependencyProperty.Register("Content", typeof(string), typeof(TestingControl), new PropertyMetadata(string.Empty));

}

Style
<Style TargetType="local2:TestingControl" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local2:TestingControl">
                <Border
                    Height="200px"
                    Background="Green"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">

                    <ContentPresenter Content="{TemplateBinding Content}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Usage
    <StackPanel>
        <local1:TestingControl >
                Testing
        </local1:TestingControl>
    </StackPanel>


text:
Q: vector replication in c how can i define an array in c which works like vector? This array should take any amount of values. It can take 0 values or 10 values or 100 values.
The code below works but gives me a runtime error that stack was corrupted.
int i = 0;
    int* aPtr = &i;
    int* head = aPtr;
    for(i=0;i<6;i++){
        (*aPtr)=i;
        aPtr++;
    }

Similarly how can i use char* str to take any amount of characters followed by null character in end to make a string?
Practice for interviews :)

A: There are many ways to do this in C, depending on your requirements, but you said "any number of values" (which usually means as many as will fit in memory).  That's commonly done using realloc to grow the size of an array dynamically.  You'll need to keep some bookkeeping information too on the size of the array as it grows.
void
store (vector_t * v, int idx, int value)
{
  if (v->size < idx) {
     v->size = idx * 2;
     v->data = realloc(v->data, v->size);
  }
  v->data[idx] = value;
}

This being tagged "homework", I've left some details to fill in such as the definition of vector_t.

A: In Your for loop , after the first iteration, you are trying to access aPtr which points to a memory location which was not declared or reserved before. In the first iteration, the int i did the memory allocation for you.
What you could do though would be to initally allocate the memory required using malloc .
Once this memory is allocated , and if you walk through only the allocated stack space, you wont come across a run time error.
PS:Your code does not work if it just compiles. Any program may contain run time as well as compile time errors. Your code sample is a very common example of run-time error.

A: This isn't too difficult.  The important thing to remember is that you will need to initially allocate memory for your array using malloc(...) or calloc(...).  After that you can easily allocate (or deallocate) memory as items are added or removed.  The method for dynamically adding or removing memory (which is used to store the items in the array) is realloc(...).  The wiki page for C Dynamic Memory Allocation is actually pretty informative.  I've provided an example below showing how to initially allocate a char* array, then increase the size and decrease the size.
#include "stdio.h"
#include "stdlib.h"

int main()
{
  char *myDynamicString;

  /* allocate initial memory */
  myDynamicString = (char *)malloc(sizeof(char) * 2);
  myDynamicString[1] = '\0';

  /* set values */
  myDynamicString[0] = 'A';

  /* prints: A */
  printf("String: %s\n", myDynamicString);

  /* make string bigger */
  myDynamicString = (char *)realloc(myDynamicString, sizeof(char) * 6);
  myDynamicString[5] = '\0';

  /* set values */
  myDynamicString[1] = 'P';
  myDynamicString[2] = 'P';
  myDynamicString[3] = 'L';
  myDynamicString[4] = 'E';

  /* prints: APPLE */
  printf("Bigger String: %s\n", myDynamicString);

  /* make string smaller */
  myDynamicString = (char *)realloc(myDynamicString, sizeof(char) * 3);
  myDynamicString[2] = '\0';

  /* set values */
  myDynamicString[1] = 'Z';

  /* prints: AZ */
  printf("Smaller String: %s\n", myDynamicString);

  /* don't forget to release the memory */
  free(myDynamicString);

  return 0;
}


text:
Q: How to add buttons in each row of data table? I am using theme DataTable. I want to add edit or delete button in each row with clickable event to get customer id for future operations. I didn't get any solution of adding buttons. I want buttons in actions column. I tried to make custom object of customers with buttons in html but it shows html in actions column not making buttons.

Html:

All Customers

                                        Show
                                        entries

                                        Search:

                            <b-table
                                    :items="customers"
                                    :fields="fields"
                                    responsive="sm"
                                    :per-page="perPage"
                                    :current-page="currentPage"
                                    :sort-by.sync="sortBy"
                                    :sort-desc.sync="sortDesc"
                                    :filter="filter"
                                    :filter-included-fields="filterOn"
                                    @filtered="onFiltered"
                            >

```

Script:
 data() {
            return {
                customers: [],
                totalRows: 1,
                currentPage: 1,
                perPage: 10,
                pageOptions: [10, 25, 50, 100],
                filter: null,
                filterOn: [],
                sortBy: "master_number",
                sortDesc: true,
                fields: [
                    { key: "master_number", sortable: true },
                    { key: "name", sortable: true },
                    { key: "co_applicant", sortable: true },
                    { key: "country", sortable: true },
                    { key: "phone", sortable: true },
                    { key: "email", sortable: true },
                    { key: "actions", sortable: true },
                ]
            };
        },
computed: {
            rows() {
                return this.customers.length;
            }
        },
methods: {
            onFiltered(filteredItems) {
                this.totalRows = filteredItems.length;
                this.currentPage = 1;
            },
            getAllCustomers(){
                axios.get(this.$path + 'all_customers').then((response) => {
                    this.customers = response.data.data
                }).catch((error)=>{
                    console.log('error', error);
                });
            }
        },
 mounted() {
            this.getAllCustomers();
            this.totalRows = this.customers.length;
        }

This is what i tried till now.

     getAllCustomers(){
                axios.get(this.$path + 'all_customers').then((response) => {
                    var i;
                    var cusArr = [];
                    for(i = 0; i < response.data.data.length; i++){
                        var customerArr = {
                            'master_number': response.data.data[i].master_number,
                            'name': response.data.data[i].name,
                            'co_applicant': response.data.data[i].co_applicant,
                            'country': response.data.data[i].country,
                            'phone': response.data.data[i].phone,
                            'email': response.data.data[i].email,
                            'actions': `<button>Edit</button>`,
                        }
                        cusArr.push(customerArr);
                    }

                    this.customers = cusArr
                }).catch((error)=>{
                    console.log('error', error);
                });
            },

A: you might be able to use the scoped slot in the component try this:

    <template v-slot:cell(actions)="data">
        <button @click="myAction">Click</button>
    </template>


text:
Q: How to attach text to an object?
Sooo I am making a card game for a jam and I am making a system where the card level and cost go up each time you deploy it. For that i cant use the card as a single sprite, instead i will use one sprite (with the name and description on it) and the level and cost go separate.
The problem I'm facing is if I move the card on game the cost and level of that card will remain on the same spot, how can I make it move along?

A: set Canvas Render Mode to World Space:


text:
Q: Is it possible for a child domain and a OU in the parent domain to share the same name?
I'm adding this Q/A because I just stumbled upon this limitation
  today, and I was not able to find any documentation about it; there
  is an old KB article about this issue, but it's currently not
  indexed by Google (probably because it was published years ago and
  never updated), and the issue is never mentioned elsewhere.

Is it possible to create a OU in the parent domain with the same name as a child domain?
Is it possible to create a child domain with the same name as a OU in the parent domain?

A: No, this is not possible if the OU is located at the root level in the parent domain (there is instead no issue if the OU is located in a subtree).
Reference: http://support.microsoft.com/en-us/kb/240147.
The KB article is very old and only mentions Windows 2000, but the limitation still applies as of Windows Server 2012 R2.
Oddly, the official guide about Active Directory naming conventions doesn't explicitly mention this issue: it only says that you can run into it even after you delete the conflicting item, due to lingering tombstoned objects.


text:
Q: sqlite creating new rows based on column conditions I receive a database like this:
Product   Condition1   Condition2   Condition 3
Computer  1            2
Car       1            2            3

What they want from me is to export a database in this form:
Product   Condition
Computer  1
Computer  2
Car       1
Car       2
Car       3

It's a lot of data, would not make any sense to fix stuff manually. Do you have any idea how would i get dynamic solution for this. I would highly appreciate your help.

A: This should work:
SELECT product, condition1 FROM table_name
UNION SELECT product, condition2 FROM table_name
UNION SELECT product, condition3 FROM table_name
UNION ORDER BY product


text:
Q: Is "uncomplete" a word? Or would I just use incomplete?  Would there be any instance that one would uncomplete?

A: The word which means not complete is incomplete.
Although http://www.thefreedictionary.com/ defines uncomplete (adj) as not yet finished:
Ex: an uncompleted play .
the use of uncomplete as an adjective is very rare. I would suggest you to use incomplete or unfinished.

A: The correct adjective is incomplete. The verb "uncomplete" does not exist. If you want to express that someone took something that had been complete and made it incomplete, you would have to say:

He removed the cog wheel from the engine, rendering it incomplete.

or

She erased her last answer (and now her application form is incomplete).

A: Yes, it is a word, but it is uncommon. Less rare is the adjective "Uncompleted".


text:
Q: mongo in() clause sort by most matches Problem shows as follows:
my query:
db.goods.find({tags:{$in:["white","black","gray"]}}).pretty();

and data returned:
{
    "id":1,
    "tags": [
        "black",
        "blue"
    ]
}
{
    "id":2,
    "tags": [
        "white",
        "gray"
    ]
}
{
    "id":3,
    "tags": [
        "gray",
        "black",
        "white"
    ]
}

Now I want the query ordered by revelence of tags,that is,_id:3 is the most matches record of the tags field,_id:2 followed.
Can anybody help me with the problem?

A: You can use the following aggregation query to get the desired results.
db.goods.aggregate([
    {$match: {tags: {$in: ["white","gray","black"]}}},
    {$project: {"tags":1, "tagsCopy":"$tags"}},
    {$unwind: "$tagsCopy"},
    {$match: {tagsCopy: {$in: ["white","gray","black"]}}},
    {$group: {
        _id:"$_id",
        counter:{$sum:1},
        tags:{"$first":"$tags"}
    }},
    {$sort:{counter:-1}},
    {$project: {"tags":1}}
]);

A: can solved by using aggregate
db.goods.aggregate([
    {$match: {tags: {$in: ["white","gray","black"]}}},
    {$unwind: "$tags"},
    {$match: {tags: {$in: ["white","gray","black"]}}},
    {$group: {
        _id:"$_id",
        matches:{$sum:1},
        tags: {$push:"$tags"}
    }},
    {$sort:{matches:-1}}
]);


text:
Q: How to make LUA script read my config file I want make lua script read custom config file
personal.txt

[user4]
id=1234
code=9876

[user3]
id=765
code=fh723

so i can read or write data

A: To do this, you should make the config file a Lua compatible format:
--personal.txt

user4 = {
  id=1234,
  code=9876,
}

user3 = {
  id=765,
  code=fh723,
}

Then you can load the file using loadfile and pass in a custom environment to place the contents into:
local configEnv = {} -- to keep it separate from the global env
local f,err = loadfile("personal.txt", "t", configEnv)
if f then
   f() -- run the chunk
   -- now configEnv should contain your data
   print(configEnv.user4) -- table
else
   print(err)
end

Of course, there are multiple ways to do this, this is just a simple, and relatively safe way.

A: You can use lua module to make your config:
-- config.lua

local _M = {}

_M.user3 = {
    id = 765,
    code = "fh723",
}

_M.user4 = {
    id = 1234,
    code = "9876",
}

return _M

Then you can require the module, and use the field in module table as you like:
-- main.lua

local config = require "config"

print (config.user3.id)
print (config.user3.code)

print (config.user4.id)
print (config.user4.code)

-- Also you can edit the module table
config.user4.id = 12345
print (config.user4.id)

Output:

765
  fh723
  1234
  9876
  12345

A: Here's one possibility. (WARNING: Not tested 100% but seems to work.)
You can read/write any such file and add, update, or delete entries depending on which parameters are left nil.
--==============================================================================

local
function file_exists(path)
  local f = io.open(path)
  if f == nil then return end
  f:close()
  return path
end

--------------------------------------------------------------------------------
-- Read the whole configuration in a table such that each section is a key to
-- key/value pair table containing the corresponding pairs from the file.

function read_config(filename)
  filename = filename or ''
  assert(type(filename) == 'string')
  local ans,u,k,v,temp = {}
  if not file_exists(filename) then return ans end
  for line in io.lines(filename) do
    temp = line:match('^%[(.+)%]$')
    if temp ~= nil and u ~= temp then u = temp end
    k,v = line:match('^([^=]+)=(.+)$')
    if u ~= nil then
      ans[u] = ans[u] or {}
      if k ~= nil then
        ans[u][k] = v
      end
    end
  end
  return ans
end

--------------------------------------------------------------------------------
-- When all three parametes are nil, no action at all.
-- When both key and value are nil but section is not, delete section.
-- When only value is nil, delete key value pair for given section.

function write_config(filename,section,key,value)
  filename = filename or ''
  assert(type(filename) == 'string')
  if section == nil and key == nil and value == nil then return end
  local t = read_config(filename)       -- read existing configuration, if any

  if section ~= nil and value == nil then
    if key == nil then
      t[section] = nil                  --eliminate whole section
    else
      t[section][key] = nil             --eliminate key/value pair
    end
    goto WriteFile
  end

  if key:match '=' then
    error('An equals sign is not expected inside key')
  end

  t[section] = t[section] or {}         --create section if not present
  t[section][key] = value               --update key value

::WriteFile::                           -- write to file
  local fo = io.open(filename,'w')
  for k,v in pairs(t) do
    fo:write('['..k..']\n')
    for k,v in pairs(v) do
      fo:write(k..'='..v..'\n')
    end
    fo:write('\n')
  end
  fo:close()

  return t                              --return updated configuration table
end

--==============================================================================

--------------------------------------------------------------------------------
-- Example use
--------------------------------------------------------------------------------

f = 'personal.txt'                                --file to use

write_config(f,'user2','id','my_id')              --update key value pair
write_config(f,'user2','name','noone')            --add key value pair
write_config(f,'user3','id','818')                --update key value pair
write_config(f,'user3','xxx','whatever')          --add key value pair
write_config(f,'newuser','id','54321')            --create new user
write_config(f,'newuser','xxx','54321')           --create new key/value pair
write_config(f,'newuser','xxx')                   --remove key/value pair
write_config(f,'newuser')                         --remove section


text:
Q: Custom Y tick text in R I have a dataset
structure(list(ValueName = c("Value 11", "Value 14", "Value 13",  "Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4",  "Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6",  "Value 11", "Value 14", "Value 13", "Value 12", "Value 10", "Value 1",  "Value 5", "Value 9", "Value 4", "Value 7", "Value 8", "Value 3",  "Value 15", "Value 2", "Value 6", "Value 11", "Value 14", "Value 13",  "Value 12", "Value 10", "Value 1", "Value 5", "Value 9", "Value 4",  "Value 7", "Value 8", "Value 3", "Value 15", "Value 2", "Value 6" ), plotOrder = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,  12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,  11L, 12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,  10L, 11L, 12L, 13L, 14L, 15L), Response = c("A1", "A1", "A1",  "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",  "A1", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2", "A2",  "A2", "A2", "A2", "A2", "A2", "A3", "A3", "A3", "A3", "A3", "A3",  "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3", "A3"), Percent = c(86.5,  85.3, 84.5, 83.2, 81, 79.5, 77, 76.7, 71, 66.2, 64.5, 60.5, 59.6,  57.2, 53.2, 9.9, 9.4, 10.2, 9.9, 11.8, 14.7, 13.9, 13.5, 15.1,  16.1, 21.3, 21.3, 26.6, 19.8, 18.5, 3.6, 5.3, 5.3, 6.9, 7.2,  5.8, 9, 9.8, 13.9, 17.7, 14.1, 18.2, 13.8, 22.9, 28.2)), .Names = c("ValueName",  "plotOrder", "Response", "Percent"), row.names = c(NA, -45L), class = c("tbl_df",  "tbl", "data.frame"))
which produces the following:

But I want to change the X and Y tick text according to a custom value.
for example like the following

Is there any ggplot function to do that? I have looked everywhere but couldn't find anything.

A: You may try(I filtered and used four Values)
install.packages("ggh4x")
df %>%
  filter(ValueName %in% c("Value 9", "Value 8", "Value 7", "Value 6")) %>%
  ggplot(aes(Percent, ValueName, fill = Response)) +
  geom_col() + scale_y_discrete(labels = c("So On", "Comprehensive", "Clear", "Good")) +
  guides(
    y.sec = ggh4x::guide_axis_manual(
      labels = ~ c("So On", "Incomprehensive", "Unclear", "Bad")
    )
  )

A: Similar to the approach by @Park but using "just" ggplot2 you could achieve your desired result via a secondary or duplicated axis where I use named vectors of labels. However, this requires to switch to a continuous y scale and to map your plotOrder column directly on y.
library(ggplot2)

labels <- unique(df$ValueName)
names(labels) <- unique(df$plotOrder)
labels2 <- labels

labels[1:2] <- c("Good", "Clear")
labels2[1:2] <- c("Bad", "Unclear")

ggplot(df, aes(Percent, plotOrder, fill = Response)) +
  geom_col(orientation = "y") +
  scale_y_continuous(breaks = unique(df$plotOrder), labels = labels, sec.axis = dup_axis(labels = labels2))


text:
Q: swift: support iOS8 with POD which is only for iOS9 I have app which works from iOS9.
Now, I want to add support for iOS8 but 1 of my PODS works only from iOS9.
I want that this POD will work for iOS9+ but do not work for iOS8 and I can compile the app.But now I can not compite the app if I set iOS8 in Project settings.
The goal is basically do not compile(?) define POD for iOS8 but compile it for iOS9+
How can I solve that?


text:
Q: Can distinct be used as a verb? I have been using distinct in a verb form for many years, and I'm not sure how I picked it up. I use it in the form like this, "I distincted myself".
To my ears, it sounds right - distinct-ing, so to speak, is an action and should fall under normal rules for grammar, but all dictionary definitions seem to only have it in adjective form.
Is distinct ever used as a verb, or is this just a quirk of my individual language/possibly my region?

A: Technically yes, Distinct was a verb but even by Noah Webster's time in 1828 it had fallen into disuse. I would suggest using the words Discern, Distinguish or Discriminate instead.
Which word you use is mostly a matter of preference but Discern implies the use of sight and Discriminate has picked up some negative connotations regarding stubbornly elitist attitudes. Discriminate has the benefit of a noun form (discrimination) without the visionary implications of discernment. It also sounds closer to distinct than distinguish.
In more recent times Differentiate has also become acceptable, probably to replace discriminate since English speakers often dislike repetitive use of words.
Do not use Determine for this exact purpose. Its closest definitions mean to give form to something or to Ascertain (make certain) which is a somewhat different concept. Proper discrimination may determine the distinctness of one thing from another but determination can not distinguish between the two.
Noah Webster's American Dictionary of The English Language (1828)
Webster's Revised Unabridged Dictionary (1913) [Cited just For differentiate.]

A: Distinguish should fit the bill here as a verb.
For example (from the above link):

1.
  to mark off as different (often followed by from or by):
He was distinguished from the other boys by his height.

A: To my knowledge distinct should not be used as a verb. Perhaps "distinguish" is a better substitute.

A: I have not heard or seen distinct be used as a verb, but the quote below might be of interest to you:
 'there is no noun in English that can't be verbed'. (Tom McArthur)


text:
Q: QGIS OTB Machine Learning algorithms do not create output I am attempting to calculate and save an image statistics file on a landsat 8 scene. When attempting the virtual raster and separate band files no output is created:
2016-04-01T16:26:13 0   OTB execution command
            C:\OSGeo4W64\bin\otbcli_ComputeImagesStatistics
            -il
            "C:\Users\Rion Lerm\Desktop\Bulk Order 628994\L8 OLI_TIRS\2015-07-16\reprojectedToWgs84\PAN_LC81680772015197LGN00_B5.TIF " "C:\Users\Rion Lerm\Desktop\Bulk Order 628994\L8 OLI_TIRS\2015-07-16\reprojectedToWgs84\PAN_LC81680772015197LGN00_B4.TIF " "C:\Users\Rion Lerm\Desktop\Bulk Order 628994\L8 OLI_TIRS\2015-07-16\reprojectedToWgs84\PAN_LC81680772015197LGN00_B3.TIF " "C:\Users\Rion Lerm\Desktop\Bulk Order 628994\L8 OLI_TIRS\2015-07-16\reprojectedToWgs84\PAN_LC81680772015197LGN00_B2.TIF "
            -bv
            0
            -out
            "C:/Users/Rion Lerm/Desktop/olifantsRiver_scp_classifies/otb_trainingClassifier/image_stats_bands2to5"
2016-04-01T16:26:13 0   OTB execution console output

...and then no output?

Attempted kmeans unsupervised via OTB (orfeo) and the following error appeared (QGIS 2.14). I performed it on a virtual raster composed of various landsat 8 bands:
2016-04-08T10:23:01    0   OTB execution command
            C:\OSGeo4W64\bin\otbcli_KMeansClassification
            -in
            "C:\Users\Rion Lerm\Desktop\Bulk_Order628994\L8_OLI_TIRS\2015-07-16\reprojectedToWgs84\landsat_projectedToWgs84.vrt"
            -ram
            7000
            -ts
            100
            -nc
            7
            -maxit
            1000
            -ct
            0.0001
            -out
            "C:/Users/Rion Lerm/Desktop/olifantsRiver_scp_classifies/2015_landCover_classify_olifantsRiver_kmeans.tif"
            -outmeans
            "C:\Users\RIONLE~1\AppData\Local\Temp\processing9b135f51bd084ee9a73e3f9100b6ae29\77bd7262ce7948e8bc780c22999c2dcf\outmeans.file"
2016-04-08T10:23:01 0   Adapter for adaptKMeansClassification not found
2016-04-08T10:23:01 0   OTB execution console output
2016-04-08T10:23:01 2   Error loading result layer:
            Traceback (most recent call last):
              File "C:/Users/Rion Lerm/.qgis2/python/plugins\processing\gui\Postprocessing.py", line 76, in handleAlgorithmResults
                out.name))
              File "C:/Users/Rion Lerm/.qgis2/python/plugins\processing\tools\dataobjects.py", line 194, in load
                + '\nCheck the procesing framework log to look for errors')
            RuntimeError: Could not load layer: C:/Users/Rion Lerm/Desktop/olifantsRiver_scp_classifies/2015_landCover_classify_olifantsRiver_kmeans.tif
            Check the procesing framework log to look for errors

Please assist!

A: Could you please copy paste the log content ?
I am not sure but I see space in the path of your file.
Generaly it could generateberror message just for that.
So you can try to move your input file in a folder where the full path don't have space.


text:
Q: Trying to make an anchor open with javascript and python First of all, sorry for any mistakes, I'm an extreme novice coder.
What I'm trying to do is open a link on a page (which is html generated by python), have it open in another window to an anchor. This anchor is a reversedisplay javascript, which means that I want to open the contents of where the anchor is.
The initial python/html link is as follows:
print "/>TEXT HERE(?)"

which you would click to lead to this:
mg-auto

TEXT HERE

The javascript function to open the reverse display is this:
function Open(d) {
document.getElementById(d).style.display = "block";
}

I have implemented this function in both the html and the python.
However, for some reason the anchor won't work at all. I fiddled around and discovered that a header + id like so:

will make a valid anchor, but the div + id like I have will not.However, I can't combine a header and the javascript function without breaking the html.
Does anyone know of a way to make an anchor work? I guess my biggest problem is no matter how I try to implement the id, when I try to link to the anchor it will not recognize the '#IDNAME'

A: From what I can understand, you want someone clicking on the '(?)' to get a new window where the div that is display="none" to start with gets display="block".
Putting '#mg-auto' after the link (a fragment or hash) will take you to the element with that id attribute when the page loads (it will jump-scroll to it if it is off screen). But the problem is that the onClick="Open('mg-auto')" will get run before you follow the link, not after the new page loads in a new window. So in the new window the div still has display="none".
To run something when a page loads you can use the window.onload event, so all you then need is the hash. Check the code below.
window.onload = function() {
  // Check if hash exists
  if(window.location.hash) {
    // Remove the "#" from the hash
    hash = window.location.hash.substr(1);
    // Display element with id == hash
    document.getElementById(hash).style.display = "block";
  }
}

That code will run when everything on the page has been loaded.
PS: You can essentially put an id on any element (including div and headings) and have the hash of you url take you to it.


text:
Q: Ubuntu with Rodecaster Pro (USB Soundcard) I switched from MacOS to Ubuntu 20.04 and I really like it but I cannot get a USB Soundcard running. It's the Rodecaster Pro and they don't offer a Linux driver but I read about ALSA drivers.
When I run
lssub

I see the Rodecaster Pro in the list which is good. But I cannot see it in my audio devices.
Rodecaster Pro USB device
I modified the USB audio config file with
sudo nano /etc/modprobe.d/snd-usb-audio

snd-usb-audio entry
I already tried:
pulseaudio, alsa-utils, alsomixer

Do you have any ideas or recommendations?
Thank you.


text:
Q: Invoke server with PowerShell to run python script: can't open file [Errno 13] Permission denied I understand this is a permission's issue but I can't tell where.
Basically I have a PowerShell script that gets some info from a user locally, then sends it to an API via python. The API I am posting to for some reason can't take JSON from PowerShell properly (thinks it's malformed no matter what you do) so I am using python to do the last bit.
The call has to come from our server ip so I have to pass the info to the server & python file and invoke the server to call the API. I do so with:
Invoke-Command -ComputerName $servername -ScriptBlock {python.exe "PATH TO .PY" -id $using:CaseID -tag $using:serviceTag -m $using:message}

I get:
C:\PATH-TO\python.exe: can't open file 'PATH TO .PY': [Errno 13] Permission denied

The python file is on a network share. I've tried giving the "everyone" group read/write to the folder to see the outcome but it is still the same.
My only thought comes down to what user is the scriptblock running under when the server executes, and if I need to provide credentials.

A: As comments stated, it was infamous PowerShell double hop issue.
Server A (me) invoking Server B to run the script on "Server C" (The network share).
The reason I say "Server C" is because the network share was attached to Server B itself. I used the direct path instead of the network share path in the script block and everything worked. Basically Server A to B at that point.
Before, I was going to go the route of passing credentials (not a fan of Credssp), but even this did not work when I passed them.
Best doc for this was here:
https://learn.microsoft.com/en-us/archive/blogs/ashleymcglone/powershell-remoting-kerberos-double-hop-solved-securely


text:
Q: How can i update a field / post a form without redirecting or reloading a page? I have the following code to update just one field in my database which a field called Flag which is a Boolean field. How can I update flag field  without reloading the page and redirecting. I tired ajax/Jquery but it works for the first time then stopped when updating the next item in the <li> list, on the next list click it shows ID and Flag value in address bar but not updating record only works when updating the first item in the list.
 <form id="updateflag">
         @if (item.Flag == "Off")
           {
            <input name="ID" type="hidden" value="@item.ID" />  //value changes based on the selected list item
            <input name="Flag" type="hidden" value="true" />//value changes based on the selected list item
            <button type="submit" class="btn btn-primary">  @(Localizer["Turn Flag On"]) // value changes based on the selected list item</button>
            }
           @if (item.Flag == "On")
             {
              <input name="ID" type="hidden" value="@item.ID" />//value changes based on the selected list item
              <input name="Flag" type="hidden" value="false" />//value changes based on the selected list item
              <button type="submit" class="btn btn-primary">  @(Localizer["Turn Flag Off"])</button>//value changes based on the selected list item
             }
  </form>

//the above form ID field changes
I used the following Ajax/Jquery which works once then on the next try it shown me the posted data in the url but not updating the field
$('#updateflag').submit(function (e) {
    e.preventDefault();
    let Data = $(this).serialize();

    $.post({
        type: 'POST',
        url: "/Customer/updateFlag",
        data: Data,
        success: window.location.reload()
    })
})

what is the best way to update a field value on button click without redirecting and show the updated result instantly?

A: According to your jquery codes, I found you just bind the click event for the updateflag.
If you have multiple form that the Jquery click binding will just work for the first one.
You could try to set a class for all the forms and use class selector in the jquery like this: <form id="updateflag" class="update">, jquery: $('.update').submit.


text:
Q: Ternary expression to execute before null checking How can I shoprten the following block by using ternary expression?
if(paginator) {
    paginator.pageIndex = 1;
}

I try to use this:
paginator.pageIndex = paginator ? 1 : undefined

But I am not sure if it is a good idea or if there is an elegant way. Because when paginator is undefined it seems to be not a good idea to set its property as undefined. So, can I use ternary operator for this scenario?

A: I would stick with your original suggestion.
Why? If paginator is undefined, then "paginator.pageIndex" will cause your code to throw an exception.
In this case I would stick with your original code which will not throw exceptions.


text:
Q: Php command on Crontab and in PHP-Cli, same? (Codeigniter) I'm with a trouble in my webhost. I have a CodeIgniter php-cli Script that is running on the SSH Terminal but when I put it in Crontab does not run, gives me several errors. The most weird thing is that this php-cli Script have been running by months.
What could be the problem and how can I start to solve it?
Restart the php-cli deamon should be a start?
Best Regards,

A: If you are using v2.0.0 then you will need to make sure you set the current working directory of the crontab to the level of your index.php.
Or, upgrade to v2.0.1 which will do this for you.
Remember that when you get error messages you should post them in your question, otherwise answers end up just being guesswork.


text:
Q: Error on using git mergetool with opendiff after Mavericks and Xcode 5.0.1 I just install OS X Maverics and Xcode 5.0.1 but now when I'm trying to use git mergetool with opendiff I'm getting this error:
Normal merge conflict for 'Assets/Scripts/Characters/MobAI.cs':
{local}: modified file
{remote}: modified file
Hit return to start merge resolution tool (opendiff):
2013-11-01 11:51:11.980 opendiff[1706:1007] too few arguments
2013-11-01 11:51:11.985 opendiff[1706:1007] usage: opendiff file1 file2 [-ancestor ancestorFile] [-merge mergeFile]

The xcode-select path is /Applications/Xcode.app/Contents/Developer/
Any idea?

A: This was my situation:
git config -l

(abbreviated output)
merge.tool=opendiff
mergetool.opendiff.cmd=/usr/bin/opendiff $2 $5 -merge $1

How I fixed it:
git config --global --unset mergetool.opendiff.cmd


text:
Q: What is proper order of pull requests and testing? We want to setup proper development workflow.
We have two main branches: master(release branch) and develop(working branch).
We want to use pull requests properly.
We see two ways how to do this:
The first one:

*

*Create new branch for feature.

*Implement feature.

*Merge to develop branch.

*Test develop branch.

*Confirm that everything works.

*Create pull request onto master branch.

*Merge pull request.

  Steps 4 and 7 can return to step 1.

The second one:

*

*Create new branch for feature.

*Implement feature.

*Create pull request onto develop branch.

*Merge pull request.

*Test develop branch.

*Confirm that everything works.

*Merge develop into master.

  Steps 4 and 6 can return to step 1.

Which one is better? Or there is better way that I described?
We have 3 team members: developer, tester and reviewer.

A: I would say that whether you use the first approach ('you verify') vs. the second approach ('we verify') depends on the setup and organization of your team.
A small group of team members that work closely together (often in the same physical place but not always) often prefers the first approach.
A widely distributed team of folks who don't know each other well and that may work different hours and number of hours may prefer the second approach which gives more control to a central authority.

A: The problem with the first approach is that features have to go through the developer's develop branch before they reach the shared repository. This means that if a developer has posted a pull request for a big and important feature that takes lots of discussing, reviews, approvals and changes, it'll clung their's develop branch and they won't be able to post smaller pull requests while waiting on other people actions/decisions related to that big PR.
Essentially - the local develop branch becomes a blocking bottleneck for each developer.
The problem with the second approach is that features are tested after they are merged into the shared repo's develop branch. This means you can have bad code in there that'll ruin the project for everyone until fixed. Also, if you decide to postpone or to abandon a feature because it's too hard to fix or because you can't fix it without ruining the overall design you need to change the shared repo's develop branch's history - which is not a very fun thing to do...
Essentially - the shared(!) develop branch becomes a blocking bottleneck for the entire team(!!).
So - I suggest a third approach, that avoids these problems:

*

*Create new branch for feature.

*Implement feature.

*Test feature branch.

*Create pull request onto develop branch.

*Merge pull request.

*Confirm that everything works.

*Merge develop into master.

That way, the blocking pipe is the feature branch - and since you can have as many as you want it's not a bottleneck.


text:
Q: How can I use duplicate row names in R? I wanted to convert the first column in a data frame, but I got the following error.
Maindata1 <- data.frame(Maindata[,-1], row.names = Maindata[,1])

Error in data.frame(Maindata[, -1], row.names = Maindata[, 1]) :
duplicate row.names: SICON, si Chk1, nothing, PRKDC, FEN1, SMC3, HMGB1, RPA3, DLGAP5, TP53, CHEK1, POLD1, PCNA, TADA3, RAD51, DUT, H2AFX, UNG, APEX2, RRM2, RBBP8, TP73, RAD17, RAD9A, FLJ20516, RAD1, RBL1, XPC, RAD52, MNAT1, MAD2L2, RB1, CHEK2, e12, e14, e13, e24, e3, e23, e15, e5, e11, e10, e26, e27, e33, e17, e20, e16, e22, e4, e18, e34, e6, e25, e19, e30, e8, e29, e32, e9, e7, e28, e2, e1, e21, e31, HUS1, CDC6, CDKN2D, FANCG, BLM, CDC25A, CKS2, ABL1, ATR, ERCC3, GADD45A, E2F3, CCNH, CDK7, CENPE, ATM, BRCA1, JUN, CKS1B
I know that I have duplicate row names in my data set and I want to use duplicate row names. I wanted to solve using the following code.
rownames(df) = make.names(Maindata, unique=TRUE)

Error in rownames<-(*tmp*, value = c("c.932..520..653..377..729..706..972..147..504..764..500..508..638..517..906..510..636..1168..237..35..359..88
How can I use them in my analysis? I want to make a 3D graph using a big data set to see their position in XYZ's direction. Thanks in advance!

A: You can make use of make.unique which will create unique rownames and then remove the first column from the data.
rownames(Maindata) <- make.unique(Maindata[[1]])
Maindata <- Maindata[-1]


text:
Q: How to label a barplot bar with positive and negative bars with ggplot2 I'm trying to plot a labeled barplot with ggplot2 with positive and negative bars.
That works so far, but I would like to set the label outside of the bar, so that it is above or under the bar. I tried to set an adjustment in vjust = c(x1,...,xn) where x is a positive or negative value according to the value of the bar in geom_text(). This doesn't work. I just got the Error message Error: "When setting aesthetics, they may only take one value. Problems: vjust"
With the normal plot command that works. I want to replicate this command in ggplot2:
xpos <- barplot(d, col=mycols, main='Verteilung in Dresden 2004',
         ylab='Anteil in %', xlab='Milieu', names.arg=l,
         cex.axis=0.7, cex.names=0.7, ylim=c(0,max(d)+0.05))
boxed.labels(xpos,d+0.02,sprintf('%d%s', d*100, '%'),
          bg='transparent', border=FALSE, cex=0.7)

So that it looks like this just in nice... ;-)

Does someone have any suggestions?
Thank's for y'all help.

A: This does the trick
library(plyr)
library(ggplot2)
library(scales)
dtf <- data.frame(x = c("ETB", "PMA", "PER", "KON", "TRA",
                  "DDR", "BUM", "MAT", "HED", "EXP"),
                  y = c(.02, .11, -.01, -.03, -.03, .02, .1, -.01, -.02, 0.06))
ggplot(dtf, aes(x, y)) +
  geom_bar(stat = "identity", aes(fill = x), legend = FALSE) +
  geom_text(aes(label = paste(y * 100, "%"),
               vjust = ifelse(y >= 0, 0, 1))) +
  scale_y_continuous("Anteil in Prozent", labels = percent_format()) +
  opts(axis.title.x = theme_blank())


text:
Q: Angularjs checkbox in ng-repeat does not have a value I have the following problem: I have a parent checkbox and other children. If I use the ng-model parent, in the ng-check they are checked, until there it works ok.
When wanting to know if the ng-change attribute has changed, I do not get results until I click on the child checkbox.
View

send
            <input type="checkbox"
                   class="filled-in"
                   id="{{fleet.nameFleet}}"
                   ng-model="fleetObject[fleet.nameFleet]" />
            {{fleet.nameFleet}}

                <input type="checkbox"
                       class="filled-in"
                       id="{{item.nameVehicle}}"
                       ng-checked="fleetObject[fleet.nameFleet]"
                       ng-model="vehicleObject[item.nameVehicle]"
                       ng-change="viewVehicle()"/>
                {{item.nameVehicle}}

{{fleetObject | json}}

{{vehicleObject | json}}

controller
myApp.controller('fleets', function ($scope, $http, sharedProperties) {
var idFleet = sharedProperties.getProperty();
$scope.fleetObject = {};
$scope.vehicleObject = {};
//
$http.get(myUrl + 'AppVehicle/' + idFleet).then(function (response) {
    if (response.data.length != 0) {
        $scope.fleets = response.data;
        Materialize.toast('Flotas obtenidas', 2000);
    }
    else {
        Materialize.toast('No se encontraron Flotas', 2000);
    }
})
//
$scope.viewVehicle = function(){
    console.log('obj');
}});

please, could you help me with just checking the parent checkbox get the names of the children.
Already very grateful


text:
Q: How to page multiple plots in R in separate jpeg files? I'd like to plot multiple plots in separate bitmap files using the file name pattern (for example, for JPEG) file.%03d.jpg in R. I tried using something like:
somevar <- 1
jpg(paste(sep='',filename,'.%03d.jpg'))
while(somevar <= n)
{
  plot(data[somevar])
  dev.new()
  somevar <- somevar + 1
}
dev.off()

but it creates one .jpg file and several Rplotnnn.pdf files. How can I change the default device to jpg, and use the custom file name pattern?

A: I think this should work
somevar <- 1
while(somevar <= n) {
  jpg(sprintf("%s%03.jpg", filename, somevar))
  plot(data[somevar])
  dev.off()
  somevar <- somevar + 1
}

Plotting goes from device opening (here jpeg(...)) to dev.off(). You control the filename (where I corrected your use of paste() to sprintf()) and the loop.

A: What happens if you remove the dev.new() from your code?  The jpg function/device should generate the multiple files following your pattern as long as you keep writing to the jpg device (the device.new call starts a new device each time, hence the pdf files).


text:
Q: Running for loop to read xlsv I have a excel on US airports, I need to get their zip codes in the adjacent column.
Using Google geocoding, I could read their zip codes individually. But now I need to run the FOR loop to read all the entries. My excel file has only 1600 rows with names of Airports in a single column.
This is my code:
data = get_data("/Users/shreyaagarwal/Desktop/Airport and zipcodes.xlsx")
import json
print(json.dumps(data))

for element in row:
    g= geocoder.google(element)
    print (g.postal)

This code reads until 5 rows and then stops
This is result:
None
None
None
None
54015
None

Which is not correct!
Please help.
I need to get the zip codes adjacent to the airports in the excel. Is it possible?

A: You are looping over the elements in 1 row. You need to wrap that in a for loop for each row  i.e.
for row in rows:
   for element in row:


text:
Q: How do I access elements in this dataset using objc? I'm struggling with this dataset:

stopsArray: (
        (
                {
            DistanceFromStart = 0;
            Ordinal = 1;
            Stop =             {
                Lat = "38.90282440185547";
                Lon = "-77.03208160400391";
                OrgAbbr = "<null>";
                OrgId = DcCi;
                StopCode = 1001259;
                StopId = "DcCi_1445_7727";
                StopName = "NW 14TH ST & NW K ST";
            };
        },
                {
            DistanceFromStart = "0.443314063224555";
            Ordinal = 2;
            Stop =             {
                Lat = "38.90834426879883";
                Lon = "-77.03208923339844";
                OrgAbbr = "<null>";
                OrgId = DcCi;
                StopCode = 1001393;
                StopId = "DcCi_1445_7808";
                StopName = "NW 14TH ST & NW RHODE ISLAND AV";
            };
        },
                {
            DistanceFromStart = "1.050716048463951";
            Ordinal = 3;
            Stop =             {
                Lat = "38.91703033447266";
                Lon = "-77.03196716308594";
                OrgAbbr = "<null>";
                OrgId = DcCi;
                StopCode = 17348;
                StopId = "DcCi_1445_6674";
                StopName = "NW 14TH ST & NW U ST";
            };
        },

*

*I'm not sure if this is an array, a dictionary, or a combination. How do I tell the difference?

*How would I pull out the "Ordinal" field, as well as elements in the "Stop" dataset?
To get the stopsArray data, I used this line:
stopsArray = [variantArray valueForKey:@"Stops"];
I've tried to pull the first Ordinal field (i.e. 1) with this:

NSMutableArray *array = stopsArray[0];
    NSString *string = [array valueForKey:@"Ordinal"];
    NSLog(@"string: %@", string);

But that results in:
string: (
    1,
    2,
    3,
    4,
    5,
    6,
    7
)

Any ideas to stop my hair coming out would be most welcome.
I'll keep at it meanwhile.

A: Firstly, its an array of objects of type dictionary.
Secondly, the data doesn't seem to be properly formatted.
Its like an array with a single object of type dictionary, but that single object contains all the different dictionary values.
hence your result of
string: (
    1,
    2,
    3,
    4,
    5,
    6,
    7
)

What seems to me the problem is the second open bracket
stopsArray: (
        (
             {

Try doing this...
NSMutableArray *array = stopsArray[0];
NSMutableArray *actualDataArray = array[0];

and then
NSString *string = [actualDataArray[INDEX_OF_DIC_OBJECT] valueForKey:@"Ordinal"];
    NSLog(@"string: %@", string);

Lemme know if it works.
Updated Solution
What eventually worked for  David DelMonte.
NSString *string = [[[stopsArray objectAtIndex:0] objectAtIndex:0] objectForKey:@"Ordinal"];


text:
Q: Call PHP inbuilt function dynamically using function name string I need to format a given value as an integer of float. For that I am using intval() & intfloat() functions in PHP.
For both operations I need to use one function.
function formatValue($value, $functionString){
  return $functionString === 'intval' ? intval($value) : floatval($value);
}

Is there a way to shorter this function? I need to call the function directly from the $functionString like,
function formatValue($value, $functionString){
  return {$functionString}($value);
}

Is there a way to do this?

A: You don't need the curly braces:
function formatValue($value, $functionString){
    return $functionString($value);
}

See Variable Functions for reference.
Please note that recent PHP versions will throw an Error throwable if something goes wrong.


text:
Q: Any way to edit video in iMovie after establishing multiple audio tracks? I've painstakingly edited audio from two separate tracks with my video in iMovie 2011. Now I want to trim the audio+video in certain areas. However, all I am able to do is select a portion of video, and delete it -- but the audio remains unchanged, so now audio is out of sync with video.
There seems to be no way to "merge" the audio back together with the video, or "link" them somehow, before trying to edit.
Next I thought maybe I can import into Final Cut Pro X and have more control. So I imported it, but it brings everything in EXCEPT all of the edits I made to the audio levels in iMovie.
Now the only thing I can figure to do is to export the iMovie project as a video (in Apple Intermediate Codec?) and then re-import that back into iMovie as a new project, where I will then perform my video edits. But this seems hacky and probably would result in a loss of quality, right?

A: The workaround I came up with was to go ahead and import the iMovie project into Final Cut Pro X, and then export the project from iMovie as a movie file with high quality audio.
Then I imported the exported movie into FCP, detached the audio, and then delete that video clip. That left me with the better sound track from the exported movie file, with the original video quality from the iMovie project.


text:
Q: Textbox value in MVC3 using ViewBag Consider a textbox field in a View made using an Html Helper.
@Html.TextBoxFor(m=>m.name, new {@value=ViewBag.x});

In this case, if in my model I pass some value(not null), then what will be the value of my textbox, the ViewBag.x, or the one I've passed in my model object??

A: You cannot override the value property of a strongly typed helper. Forget about strongly typed helpers if you use ViewBag. Once you go that route, you will have to follow it:
@Html.TextBox("x")

where x is something that you have stuffed into the ViewBag in your controller action:
ViewBag.x = "foo";

Strongly typed helpers work with the model and use the lambda expression passed as first argument to get the value.
So if you want to do things properly throw the ViewBag away and use view models and strongly typed helpers:
@Htlm.TextBoxFor(model => model.X)


text:
Q: Yarn node manager failed with 0xc0000bb8 I am getting this error in yarn nodemanager:
ERROR util.SysInfoWindows: ExitCodeException exitCode=1: PdhAddCounter \Network Interface(*)\Bytes Received/Sec failed with 0xc0000bb8.
Error in GetDiskAndNetwork. Err:1

        at org.apache.hadoop.util.Shell.runCommand(Shell.java:1008)
        at org.apache.hadoop.util.Shell.run(Shell.java:901)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:1213)
        at org.apache.hadoop.util.SysInfoWindows.getSystemInfoInfoFromShell(SysInfoWindows.java:86)
        at org.apache.hadoop.util.SysInfoWindows.refreshIfNeeded(SysInfoWindows.java:101)
        at org.apache.hadoop.util.SysInfoWindows.getPhysicalMemorySize(SysInfoWindows.java:153)
        at org.apache.hadoop.yarn.util.ResourceCalculatorPlugin.getPhysicalMemorySize(ResourceCalculatorPlugin.java:64)
        at org.apache.hadoop.yarn.server.nodemanager.NodeResourceMonitorImpl$MonitoringThread.run(NodeResourceMonitorImpl.java:143)

Using Hadoop 3.3.0 on Windows 10
I found a solution here: https://github.com/apache/hadoop/pull/458
But I do no know what to do exactly. I guess I have to edit the source code for winutils and recreate the .exe-file. But where can I find the source code and how do I generate the .exe?
Can anyone help?

A: The easiest solution is to change the language of your operation system into English. It helped me.


text: Q: How do you configure Files to display the star column? I use Files (3.36.3-stable) as a file manager in Ubuntu and it has a collection in the sidebar called "Starred." I can star files throughout the other collections and they are automatically listed in the starred collection. This works for all folders and files except those outside home and its path. This means it excludes project related files and code used in development with LAMP, which is in the var path.  Is there anyway to change this behavior so that any file can be starred?  Note that although Files allows you to set preferences for every collection, and that involves selecting to display the Star column, it simply doesn't show.


text:
Q: What does same 'value' mean for a std::set? In C++, the std::set::insert() only inserts a value if there is not already one with the same 'value'.  By the same, does this mean operator== or does it mean one for which operator< is false for either ordering, or does it mean something else?

A:
does it mean one for which operator< is false for either ordering?

Yes, if the set uses the default comparator and compares keys using <. More generally, in an ordered container with comparator Compare, two keys k1 and k2 are regarded as equivalent if !Compare(k1,k2) && !Compare(k2,k1).
Keys are not required to implement operator== or anything else; they are just required to be comparable using the container's comparator to give a strict weak ordering.

A: std::set has a template argument called `Compare' as in this signature:
template < class Key, class Compare = less<Key>,
       class Allocator = allocator<Key> > class set;

Compare is used to determine the ordering between elements. Here, the default less<Key> uses the < operator to compare two keys.
If it helps, you can think of a set as just a std::map with meaningless values, ie a std::set<int> can be thought of as a std::map<int, int> where the values are meaningless.

A: The only comparison that set is allowed to perform on T is via the functor type it was given to do comparisons as part of the template. Thus, that's how it defines equivalence.
For every value in the set, the comparison must evaluate to true for one of the two ordering between that value and the new one. If it's false both ways for any value, then it won't be stored.


text:
Q: get_object_or_404 with values views.py:
def car(request, car_id):
    car = get_object_or_404(Car, pk=car_id, active=1)
    return render(request, 'car.html', {'car': car,}
    )

in car.html:
...
{{ car.mark }}, {{ car.options.year }}, etc.
...

So, I have many requests to my db. In another view I use
all_cars = Cars.objects.all().filter(active=1).values(...)

And in this variant I have only 2 request to db.
Yes, I know, that I can use in car`s view:
car = Car.objects.filter(id=car_id, active=1).values(...)[0]

Is any other variants to do the same with get_object_or_404 or something, that not doing many requests to db?
Thanks!

A: You can pass a queryset as the first parameter, instead of a model class. Here you can use select_related (and prefetch_related, but it seems you need the first one) to reduce database queries:
def car(request, car_id):
    cars = Car.objects.select_related('options')
    car = get_object_or_404(cars, pk=car_id, active=1)
    return render(request, 'car.html', {'car': car})


text:
Q: Install urllib2 in Arch Linux I am trying to install the urllib2 module in Arch Linux as I need to run a Python code.
The error that the Python code outpus is:
File "PiMiner/PiMiner.py", line 3, in <module>
import sys, subprocess, time, urllib2, socket

Now, when I runt his code sudo pacman -S urllib2, I get error: target not found: urllib2
What can I do in this situation?

A: In ArchLinux, the command python defaults to python3.  If you neeed to use 2.x, you should run the script with python2 whatever.py.

A: As aelfric5578 said, python defaults to python3
But if you wish to run it with python3 then you can search the Arch repos with pacman -Ss urllib which will a return a list of packages you can pacman -S
As a naming scheme, Arch sticks to python-libname for python 3 or python2-libname for python2, so it's usually a safe bet to pacman -S python-missinglib


text:
Q: I cannot compile a C++ library using cmath on macOS 10.15.4 with premake5/gmake I've spent several hours attempting to find out as to why I cannot compile my application that uses spdlog due to several errors related to cmath having no member in its global namespace:
In file included from lib/spdlog/include/spdlog/fmt/bundled/format.h:38:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:325:9: error: no member named 'isless' in the global namespace
using ::isless;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:326:9: error: no member named 'islessequal' in the global namespace
using ::islessequal;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:327:9: error: no member named 'islessgreater' in the global namespace
using ::islessgreater;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:328:9: error: no member named 'isunordered' in the global namespace
using ::isunordered;
      ~~^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath:329:9: error: no member named 'isunordered' in the global namespace
using ::isunordered;

I had initially made the assumption that this was due to Premake not finding the MacOS SDK given that the path to the sysroot was not previously declared in my script. I made sure to add it to my link options before retrying:
    linkoptions
    {
        "-isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"
    }

However, this issue still persists and I've failed to find any other issues online related to this problem both on the official wikis of premake and spdlog. Any help would be very much appreciated.

A: Make sure you have downloaded the latest 'Command Line Tools for Xcode 11.4.1' package and run this from a terminal (command line):
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_11.4.1.pkg

Can't compile C program on a Mac after upgrade to Mojave

A: sudo vim /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/cmath
search <math.h>
change #include <math.h> to #include "math.h"
save and exit
try again to compile


text:
Q: Timedelta is not defined Below is the code I am working on. From what I can tell there is no issue, but when I attempt to run the piece of code I receive an error.
import os
import datetime

def parseOptions():

    import optparse
    parser = optparse.OptionParser(usage= '-h')
    parser.add_option('-t', '--type', \
                      choices= ('Warning', 'Error', 'Information', 'All'), \
                      help= 'The type of error',
                      default= 'Warning')
    parser.add_option('-g', '--goback', \
                      type= 'string')
    (options, args) = parser.parse_args()
    return options

options = parseOptions() now = datetime.datetime.now() subtract = timedelta(hours=options.goback) difference = now - subtract

if options.type=='All' and options.goback==24:
    os.startfile('logfile.htm')

else:
    print
    print 'Type =', options.type,
    print
    print 'Go Back =', options.goback,'hours'
    print difference.strftime("%H:%M:%S %a, %B %d %Y")
    print

Error is as followed:
Traceback (most recent call last):
  File "C:\Python27\Lib\SITE-P~1\PYTHON~2\pywin\framework\scriptutils.py", line 325, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Users\user\Desktop\Python\python.py", line 19, in <module>
    subtract = timedelta(hours=options.goback)
NameError: name 'timedelta' is not defined

Any help would be appreciated.

A: You've imported datetime, but not defined timedelta.  You want either:
from datetime import timedelta

or:
subtract = datetime.timedelta(hours=options.goback)

Also, your goback parameter is defined as a string, but then you pass it to timedelta as the number of hours.  You'll need to convert it to an integer, or better still set the type argument in your option to int instead.

A: It should be datetime.timedelta

A: Where you have timedelta, you need to put datetime. before it, so it's actually datetime.timedelta

A: I find this problem may occur in some of my sutpid action.
I create a file named datetime.py and even I rename the file, I still leave the datetime.pyc in the folder...
So every file that import dateime will use this file and timedelta cannot be found.
After I delete the file:datetime.pyc, It works.


text:
Q: WebSocket thru Amazon ELB or directly (remote IP issue) We use WebSockets to communicate with our EC2 instances.
Our script is served using nodejs and Express, and then initialize the WebSocket.
Right now ELB is used which makes life harder to identify the client IP.
Using x-forwarded-for header we can get the IP in the context of HTTP, but when it comes to WebSocket context in the server, it looks like it's not forwarded by Amazon.
We identified 2 options:

*

*Communicate the WebSocket directly with the instance (using its public DNS).

*Maintain some sort of sessionid, in which store the IP when in the context of HTTP and associate it with the sessionid. The client side will get its sessionid using the HTTP response, and will use it to on the WebSockets. The the server will be to identify the client and resolve its IP from the cache.

Both options are not great: 1 is not fault tolerant and 2 is complex.
Are there more solutions? Can Amazon somehow forward the IP? What is the best practice?
Thanks

A: I have worked with websockets and I have worked with ELB, but I've never worked with them together, so I didn't realize that an HTTP forwarder on an Elastic Load Balancer doesn't understand websocket requests...
So I take it you must be using a TCP forwarder, which explains why you're using a different port, and of course the TCP forwarder is protocol-unaware, so it won't be adding any headers at all.
An option that seems fairly generic and uncomplicated would be for the http side of your application to advise the websocket side by pushing the information across rather than storing it in a cache for retrieval.  It's scalable and lightweight, assuming there's not an obstacle in your environment that makes it difficult or impossible to implement.
While generating the web page that loads the websocket, take the string "ipv4:" and the client's IP ("192.168.1.1," for example), concatenate and encrypt them, and make the result url-friendly:
/* pseudo-code */
base64_encode(aes_encrypt('ipv4:192.168.1.1','super_secret_key'))

Using that example key with 128 bit aes and that example IP address, I get:
/* actual value returned by pseudo-code above */
1v5n2ybJBozw9Vz5HY5EDvXzEkcz2A4h1TTE2nKJMPk=

Then when rendering the html for the page containing the websocket, dynamically build the url:
ws = new WebSocket('ws://example.com/sock?client=1v5n2ybJBozw9Vz5HY5EDvXzEkcz2A4h1TTE2nKJMPk=');

Assuming the querystring from the websocket is accessible to your code, you could base64_decode and then aes_decrypt the string found in the query parameter "client" using the super-secret key, and then verify that it begins with "ipv4:" ... if it doesn't, then it's not a legitimate value.
Of course, "ipv4:" (at the beginning of the string) and "client" (for the query parameter) were arbitrary choices and do not have any actual significance.  My choice of 128 bit AES was also arbitrary.
The problem, of course, with this setup is that it is subject to a replay: a given client IP address will always generate the same value.  If you only using the client IP address for "informational purposes" (such as logging or debugging) then this may be sufficient.  If you are using it for anything more significant, you may want to expand this implementation -- for example, by adding a timestamp:
'ipv4:192.168.1.1;valid:1356885663;'

On the receiving end, decode the string and check the timestamp.  If it is not +/- whatever interval in seconds that you deem safe, then don't trust it.
These suggestions all hinge on your ability to dynamically generate the websocket url, the browser's ability to connect with it, and you being able to access the querystring portion of the URL in the websocket request... but if those pieces will fall into place, maybe this will help.

Additional thoughts (from comments):
The timestamp I suggested, above, is seconds from the epoch, which gives you an incrementing counter that requires no statefulness in your platform -- it only requires that all of your server clocks are correct -- so it doesn't add unnecessary complexity.  If the decrypted value contains a timestamp less than (for example) 5 seconds different (+/-) from the server's current time, then you know you're dealing with an authenticated client.  The time interval permitted only needs to be as long as the maximum reasonable time for a client to attempt its websocket connection after loading the original page, plus the maximum skew of all your server clocks.
It is true, of course, that with NAT, multiple different users could be behind the same source IP address.  It's also true, though far less less likely, that a user could actually make the websocket connection from a different source IP than the one where they originated the first http connection, and still be quite legitimate... and it sounds like the identity of the authenticate user may be a more important value for you than the actual source IP.
If you include the authenticated user's ID within the encrypted string as well, you have a value that is unique to origin IP, user account, and time, to a precision of 1 second.  I think this is what you're referring to by additional salt.  Adding the user account to the string should get you the information you're wanting.
'ipv4:192.168.1.1;valid:1356885663;memberid:32767;'

TLS should prevent discovery of the this encrypted string by an unauthorized party, but avoidance of replayability is also important because the generated URL is available in clear text in a user's browser's "view source" for the html page.  You don't want a user who is authorized today but unauthorized tomorrow to be able to spoof their way in with a signed string that should be recognized as no longer valid.  Keying to a timestamp and requiring it to fall in a very small valid window prevents this.

A: It depends on how serious the application is.
Basing any kind of decision on client IP address is a risky proposition. Basing security on it, even more so. While the suggestions offered so far work well within the given constraints, it would not be sufficient for a robust enterprise application.
Client IP addresses can be  obscured by NATs, as already pointed out. So people accessing the Web from their place of work will often appear to have the same IP address. People's routers at home act as a NAT, so every family member at home accessing the Web will appear to the have the same IP address. Or even the same person accessing the application from a PC and a tablet...
Whether behind a NAT or not, using the application from two browsers on the same machine will appear to the have the same address. Similarly, multiple tabs in the same browser will appear to have the same address.
Other junction points like proxies or load balancers may also hide the original client IP address such that the thing behind the proxy/load balancers thinks they are the client. (More sophisticated or lower level intermediaries can prevent this, which is what makes them more sophisticated or expensive.)
Given all of the above, a serious application should not rely on client IP address for any kind of important decision, especially around security.