text:
Q: How to solve a pattern? I need to make a pattern detection code,
with the following conditions:
Given an image (square matrix) A[N,N], if point P(X,Y) is the center of a star, the following condition will be satisfied:

(1) A[X][j]=255, for all 0<=j<N  (The values in the Xth row are all 255)

(2) A[i][Y]=255, for all 0<=i<N  (The values in the Yth column are all 255)

(3)
    A[X+i][Y+i]=255, for all -N<=i<N if 0<=(X+i)<N and 0<=(Y+i)<N

   A[X+i][Y-i]=255, for all -N<=i<N if 0<=(X+i)<N and 0<=(Y-i)<N

   (The values of two diagonals from the centers are all 255)

I would like to know a way to effectively solve this problem quickly.
What I have tried:
The way that my program works is as follows:

*

*receive the input matrix

*create an empty copy 2d matrix

*scan for full row values whilst scanning. -> add the value of a the detected row into the copy

*scan for full column values-> add the value of a the detected col into the copy

*scan for full diagonal values -> same as above

*scan for full anti-diagonal values. -> same as above

*iterate through the copy matrix, and the center of a star will be found with a point which has been intersected 4 times.

With simple testcases, my code works, but it fails in the online judge, and also have time limit issues.

Full code down here:
#include<stdio.h>
int constellation[2048][2048];
int copy[2048][2048]={};
int main()
{
    int a,size;
    int totalrow=0, totalcol=0;
    scanf("%d", &a);
    scanf("%d", &size);

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

        for(int row=0; row<size; row++){
            for(int col=0; col<size; col++){
                scanf("%d", &constellation[row][col]);
                constellation[row][col]=(constellation[row][col]== 255)?1:0;
                totalrow+=constellation[row][col];
            }
            if(totalrow==size)
            {
                for(int col = 0; col<size; col++)
                    copy[row][col]+=1;
            }
            totalrow=0;
        }

        for(int row=0; row<size; row++){
            for(int col=0; col<size; col++)
                totalcol+=constellation[col][row];
            if(totalcol==size)
                for(int x=0; x<size; x++)
                    copy[x][row]+=1;
            totalcol=0;
        }
        int totaldiagonal=0, i=0, j=0;
        for(int k=0; k<=size-1; k++)
        {
            i=k;
            j=0;
            while(i>=0)
            {
                totaldiagonal+=constellation[i][j];
                i-=1;
                j+=1;
            }
            //printf("j=%d\n", j);
            if(totaldiagonal==j && totaldiagonal!=0){
                i=k;
                j=0;
                while(i>=0){
                    copy[i][j]+=1;
                    i-=1;
                    j+=1;
            }
            }
            totaldiagonal=0;
        }
        totaldiagonal=0;
        //checking for the same diagonal, but the patterns changed, need new for loop.
        for(int k=1; k<=size-1; k++){
            i=size-1;
            j=k;
            while(j<=size-1)
            {
                totaldiagonal+=constellation[i][j];
                i-=1;
                j+=1;
            }
            //printf("i=%d\n", size-i);
            //printf("total diagonal=%d\n", totaldiagonal);
            if(totaldiagonal== size-i-1){
                i=size-1;
                j=k;
                //printf("masuk\n");
                while(j<=size-1){
                    copy[i][j]+=1;
                    i-=1;
                    j+=1;
                }
            }
            totaldiagonal=0;
        }
//-----------------------------------------------------------------------------------------------

        int max=0;
        for(int j=0; j<size ;j++)
        {
            max=0;
            int i=size-1;
            int y=j;
            while(y>=0)
            {
                max++;
                totaldiagonal+=constellation[i][y];
                i--;
                y--;
            }
            if(max==totaldiagonal){
                //printf("inside\n");
                int i=size-1;
                int y=j;
                while(y>=0)
                {
                    //printf("coordinates: x=%d, y=%d\n", i,y);
                    //printf("data: %d", constellation[i][y]);
                    copy[i][y]+=1;
                    i--;
                    y-=1;
                }
            }
            totaldiagonal=0;
            //printf("repeat\n");
        }

        for(int k=size-1; k>=0; k--)
        {
            max=0;
            i = k-1;
            j = size-1;
            while(i>=0)
            {
                max++;
                totaldiagonal+=constellation[i][j];
                i--;
                j--;
            }
            if(totaldiagonal==max)
            {
                i=k-1;
                j=size-1;
                while(i>=0)
                {
                    copy[i][j]+=1;
                    i--;
                    j--;
                }
            }
            totaldiagonal=0;
        }

        int counter=0;
        /*
        for(int i=0; i<size; i++){
            for(int j=0; j<size; j++){
                printf("%d ", constellation[i][j]);
            }
            printf("\n");
        }
        printf("\n");
        */
        for(int i=0; i<size; i++){
            for(int j=0; j<size; j++){
                if(copy[i][j]>=4  && i>0 && i<size-1 && j>0 && j<size-1) counter++;
                //i have checked whether the edges could be or not be a center of star, but still no difference
                //printf("%d ", copy[i][j]);
            }
            //printf("\n");
        }
        printf("%d\n", counter);
    }
    return 0;
}

A: I would first go for a simpler problem. Consider that stars only have horizontal and vertical lines going through them. To find out which horizontal and vertical lines are completely white, just count the number of white pixels in each of them, and at the end compare the count with the width and height of the image. This is very cheap if you do it while reading the input:
int rowsums[size] = {0};
int colsums[size] = {0};

for (int row=0; row<size; row++) {
    for (int col=0; col<size; col++) {
        int value;
        scanf("%d", &value);
        rowsums[row] += value;
        colsums[col] += value;
    }
}

Note that we no longer need the two-dimensional arrays, we just have two one-dimensional arrays to store information about the image.
Now you can get the positions of the stars by checking for each pixel if it's in a full row or full column:
for (int row=0; row<size; row++) {
    if (rowsums[row] != size * 255)
        continue;

    for (int col=0; col<size; col++) {
        if (colsums[col] != size * 255)
            continue;

        printf("Star at %d, %d\n", row, col);
    }
}

That second pass is still O(N²). However, if you first scan rowsums and colsums and create new arrays that only hold the row and column indices of those rows and columns that are fully white, you reduce the problem to O(N + number_of_stars). If you only need to count, then it's just O(N), since you just need to multiply the number of fully white rows with the number of fully white columns to get the number of stars.
Now try to expand this approach to build the sum of pixel values of all the possible diagonals.

A: My first thought:

*

*Create 8 arrays of bits (or a single array of 8-bit numbers), with the same size as the image.
Each array corresponds to one of the directions. A bit in the array should be true if there is a white line (in the specific direction) from the corresponding pixel to the edge of the image.
In other words, arr1[i][j] should be true if input[i][j] is white and
arr1[i-1][j] is true (offset is different for each array).
If all 8 arrays have true elements in the same location, this location is a star.

*To fill the arrays according to this rule, you do two passes over the input image. The second pass should be in reverse.
The first pass can fill 4 of the 8 arrays (which ones should be self-evident: it only makes sense to examine neighbors that were already traversed).
The second pass can fill the 4 remaining arrays.
The second pass can also check if thet current pixel is a star (if all 8 arrays have true elements in the same location), and increment a counter if it's the case.

In pseudocode, the first pass could look like this:
for y = 0..n-1
    for x = 0..n-1
        if input[x][y] == 255
            if arr1[x-1][y]
                arr1[x][y] = true
            if arr2[x-1][y-1]
                arr2[x][y] = true
            if arr3[x][y-1]
                arr3[x][y] = true
            if arr4[x+1][y-1]
                arr4[x][y] = true

You also need special handling for the image borders, to avoid accessing `arr??` out of bounds.

The second pass would be exactly the same, except you should be iterating in reverse, and should be filling the other 4 arrays.


text:
Q: Would the 2 way Chi Square test be appropriate for this scenario; If not, what test is? The test hypothesis is this:

Does a student's gender have a greater influence on their choice in
  whether they study data science as a core topic; than other
  demographic/variable factors?

The sample is of a population with 39 students in the class,and the other demographic/variable factors are:

*

*nationality (Australian or other)

*religion (non-affiliated or religious)

*how they were paying for university[payment] (government help or savings)

*if they had moved house to study[moved] (yes or no)

*if they had chosen data science as an elective or core topic

I was considering performing two chi square tests, one for gender and the core/elective topic, and one for core/elective topics and other demographic/variable factors; as shown below:

With

*

*H0: Gender/demographic factors does have a greater influence/relationship with picking a
core topic

*Ha: Gender/demographic factors does not have a greater influence/relationship with
picking a core topic

I am to test the hypothesis by viewing the difference between the two table's p-values and to see that if the first table has a smaller p-value than the second's, then we know that gender does have a greater influence.
I am sorry, I don't really understand these statistical tests, would really appreciate it if someone can help interpret analysis that can be performed to answer the test hypothesis.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django - values() for foreign key relations Django values() is very handy, is it possible to serialize nested object too?
class Book(model.Models):
   name = models.CharField(max_length=50)
   user = models.ForeignKey(settings.AUTH_USER_MODEL)

I would hope to do something like
d = Book.objects.all().values('name', 'user', deep={
    'user': ['username', 'first_name', 'last_name'] # related user fields
})

And to get a result
[
 {
  'name': 'book1',
  'user': {'username': 'user1', 'first_name': '...', 'last_name': '..'}
 }
]

So I'll get a nested dict for the foreign key object (user), instead of just the user id.
I don't need more than a depth of 1, so only one level of related objects.

A: I would suggest Django RestFrameWork for efficient use. Define your serializers.py as below,
from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name')

class BookSerializer(ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Book
        fields = ('name', 'user')

and try this in your view/shell
book = Book.objects.get(id=1)
result = BookSerializer(book).data

OR
all_book_objects = Book.objects.all()
result = BookSerializer(all_book_objects, many=True).data


text:
Q: How to write a A-star search algorithm to visit all the nodes without a specific end-point? I am trying to write an algorithm to collect as many as possible items from different stops. which every stop is a cell in a matrices. the goal is to find the shortest path to collect all the items. The start point is defined, but the end-point can be anywhere... I used the A-star search algorithm for it...
Here is code:
import numpy as np

class Node:
    """
        A node class for A* Pathfinding
        parent is parent of the current Node
        position is current position of the Node in the maze
        g is cost from start to current Node
        h is heuristic based estimated cost for current Node to end Node
        f is total cost of present node i.e. :  f = g + h
    """

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.g = 0
        self.h = 0
        self.f = 0
    def __eq__(self, other):
        return self.position == other.position

#This function return the path of the search
def return_path(current_node,maze):
    path = []
    no_rows, no_columns = np.shape(maze)
    # here we create the initialized result maze with -1 in every position
    result = [[-1 for i in range(no_columns)] for j in range(no_rows)]
    current = current_node
    while current is not None:
        path.append(current.position)
        current = current.parent
    # Return reversed path as we need to show from start to end path
    path = path[::-1]
    start_value = 0
    # we update the path of start to end found by A-star serch with every step incremented by 1
    for i in range(len(path)):
        result[path[i][0]][path[i][1]] = start_value
        start_value += 1
    return result

def search(maze, cost, start, end):
    """
        Returns a list of tuples as a path from the given start to the given end in the given maze
        :param maze:
        :param cost
        :param start:
        :param end:
        :return:
    """

    # Create start and end node with initized values for g, h and f
    start_node = Node(None, tuple(start))
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, tuple(end))
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both yet_to_visit and visited list
    # in this list we will put all node that are yet_to_visit for exploration.
    # From here we will find the lowest cost node to expand next
    yet_to_visit_list = []
    # in this list we will put all node those already explored so that we don't explore it again
    visited_list = []

    # Add the start node
    yet_to_visit_list.append(start_node)

    # Adding a stop condition. This is to avoid any infinite loop and stop
    # execution after some reasonable number of steps
    outer_iterations = 0
    max_iterations = (len(maze) // 2) ** 10

    # what squares do we search . serarch movement is left-right-top-bottom
    #(4 movements) from every positon

    move  =  [[-1, 0 ], # go up
              [ 0, -1], # go left
              [ 1, 0 ], # go down
              [ 0, 1 ]] # go right

    """
        1) We first get the current node by comparing all f cost and selecting the lowest cost node for further expansion
        2) Check max iteration reached or not . Set a message and stop execution
        3) Remove the selected node from yet_to_visit list and add this node to visited list
        4) Perofmr Goal test and return the path else perform below steps
        5) For selected node find out all children (use move to find children)
            a) get the current postion for the selected node (this becomes parent node for the children)
            b) check if a valid position exist (boundary will make few nodes invalid)
            c) if any node is a wall then ignore that
            d) add to valid children node list for the selected parent

            For all the children node
                a) if child in visited list then ignore it and try next node
                b) calculate child node g, h and f values
                c) if child in yet_to_visit list then ignore it
                d) else move the child to yet_to_visit list
    """
    #find maze has got how many rows and columns
    no_rows, no_columns = np.shape(maze)

    # Loop until you find the end

    while len(yet_to_visit_list) > 0:

        # Every time any node is referred from yet_to_visit list, counter of limit operation incremented
        outer_iterations += 1

        # Get the current node
        current_node = yet_to_visit_list[0]
        current_index = 0
        for index, item in enumerate(yet_to_visit_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index

        # if we hit this point return the path such as it may be no solution or
        # computation cost is too high
        if outer_iterations > max_iterations:
            print ("giving up on pathfinding too many iterations")
            return return_path(current_node,maze)

        # Pop current node out off yet_to_visit list, add to visited list
        yet_to_visit_list.pop(current_index)
        visited_list.append(current_node)

        # test if goal is reached or not, if yes then return the path
        if current_node == end_node:
            return return_path(current_node,maze)

        # Generate children from all adjacent squares
        children = []

        for new_position in move:

            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

            # Make sure within range (check if within maze boundary)
            if (node_position[0] > (no_rows - 1) or
                node_position[0] < 0 or
                node_position[1] > (no_columns -1) or
                node_position[1] < 0):
                continue

            # Make sure walkable terrain
            if maze[node_position[0]][node_position[1]] != 0:
                continue

            # Create new node
            new_node = Node(current_node, node_position)

            # Append
            children.append(new_node)

        # Loop through children
        for child in children:

            # Child is on the visited list (search entire visited list)
            if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:
                continue

            # Create the f, g, and h values
            child.g = current_node.g + cost
        ## Heuristic costs calculated here, this is using eucledian distance
        child.h = (((child.position[0] - end_node.position[0]) ** 2) +
                   ((child.position[1] - end_node.position[1]) ** 2))

        child.f = child.g + child.h

        # Child is already in the yet_to_visit list and g cost is already lower
        if len([i for i in yet_to_visit_list if child == i and child.g > i.g]) > 0:
            continue

        # Add the child to the yet_to_visit list
        yet_to_visit_list.append(child)

if name == 'main':
maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0]]

start =[10, 6] # starting position
end  = [14,20] # ending position
cost = 1 # cost per movement

path = search(maze,cost, start, end)
#   print(path)

print('\n'.join([''.join(["{:" ">3d}".format(item) for item in row])
   for row in path]))


text:
Q: A different way to version api output with laravel? I'm about to ...

*

*extend my App/Orm/MyModel.php with Http/Json/V1/MyModel.php so I can keep the $appends, $hides, toArray() neatly tucked away in a V1

*namespace and prefix some routing for V1

*probably do some custom resolvers for route model binding

And I'm thinking ... really?  They haven't built this in... what am I missing here?  There's gotta be a quick, turn-key for this.  I'm interested in knowing how other people are doing this, so please chime in.

A: Try Resources instead of Models
Have a look at resources:
https://laravel.com/docs/5.7/eloquent-resources
And add your logic to resources so that you display different versions of a model depending on the API version. You can still make use of $appends and $hidden.
With this approach we return a Resource of a model rather than the model itself.
Here is an example of a UserResource for different API versions:
class UserResource extends JsonResource
{
    private $apiVersion;

    public function __construct($resource, int $apiVersion = 2) {
        $this->apiVersion = $apiVersion; // OPTION 1: Pass API version in the constructor
        parent::__construct($resource);
    }

    public function toArray($request): array
    {
        // OPTION 2: Get API version in the request (ideally header)
        // $apiVersion = $request->header('x-api-version', 2);

        /** @var User $user */
        $user = $this->resource;

        return [
            'type' => 'user',
            'id' => $user->id,
            $this->mergeWhen($this->apiVersion < 2, [
                'name' => "{$user->first_name} {$user->last_name}",
            ], [
                'name' => [
                    'first' => $user->first_name,
                    'last' => $user->last_name
                ],
            ]),
            'score' => $user->score,
        ];
    }
}

The you can call:
$user = User::find(5);
return new UserResource($user);

If you need a different connection you can do:
$user = User::on('second_db_connection')->find(5);

So V1 API gets:
{
    id: 5,
    name: "John Smith",
    score: 5
}

and V2 API gets:
{
    id: 5,
    name: {
         first: "John",
         last: "Smith",
    },
    score: 5
}

Now if later you wanted to rename score to points in your DB, and in V3 of your API you also wanted to change your JSON output, but maintain backwards compatibility you can do:
   $this->mergeWhen($this->apiVersion < 3, [
       'score' => $user->points,
   ], [
       'points' => $user->points,
   ])

Prefix routes
You can easily prefix routes as mentioned here: https://laravel.com/docs/5.7/routing#route-group-prefixes
Route::prefix('v1')->group(function () {
    Route::get('users', function () {
        // ...
    });
});

Explicit Route Model Binding
To do custom route model bindings have a look at: https://laravel.com/docs/5.7/routing#route-model-binding
e.g.
Route::bind('user', function ($value) {
    return App\User::where('name', $value)->first() ?? abort(404); // your customer logic
});


text:
Q: React Function Component Form not setting state variables? I have a React Function Component that is a form where users enter in values. The user inputs are stored using Hooks. The issue that I am running into is that it does not seem to be setting the hook correctly. When I console log one value right before the axios call, it returns as undefined. Below is the code I have so far. I think I am pretty close but am unsure where I made mistakes. Any help is appreciated!
import React, { useState, useEffect } from "react";
import axios from "axios";

function ReportOutage(){
    //Use state hook to hold the values users input, passed into axios call
    //setting the default values
    const [formData, setFormData] = useState({
        userReport: '6',
        serviceType: "",
        serviceName: "",
        serviceStreet: "",
        serviceCity: "",
        serviceState: "",
        serviceDescription: ""
    })

    const handleChange = (event) => {
        event.preventDefault();
        setFormData({[event.target.name]: event.target.value})
    };

    const handleSubmitReport = async (event) =>{
        event.preventDefault();
        console.log(formData.serviceName); // This is returning undefined when I am expecting the service name entered by the user.
        const res = await axios.post("/outage-new", {
            user_id: `${formData.userReport}`,
            service_type: `${formData.serviceType}`,
            service_name: `${formData.serviceName}`,
            outage_street: `${formData.serviceStreet}`,
            outage_city: `${formData.serviceCity}`,
            outage_state: `${formData.serviceState}`,
            outage_description: `${formData.serviceDescription}`,
        })
    };

    return (
        <>

Test Dialog box

            <form onSubmit={handleSubmitReport}>
                <input type="text" placeholder="Service Type"
                onChange={handleChange}
                value={formData.serviceType}
                name="serviceType"/>

                <input type="text" placeholder="Service Name"
                onChange={handleChange}
                value={formData.serviceName}
                name="serviceName"/>

                <input type="text" placeholder="Street"
                onChange={handleChange}
                value={formData.serviceStreet}
                name="serviceStreet"/>

                <input type="text" placeholder="City"
                onChange={handleChange}
                value={formData.serviceCity}
                name="serviceCity"/>

                <input type="text" placeholder="State"
                onChange={handleChange}
                value={formData.serviceState}
                name="serviceState"/>

                <input type="text" placeholder="Description"
                onChange={handleChange}
                value={formData.serviceDescription}
                name="serviceDescription"/>

                <button type="submit">Report Outage</button>
            </form>
        </>
    );
}

export default ReportOutage;

A: When using the useState hook, updates are not shallowly merged like they are in the class component's this.setState. You are replacing the state with a new object with only the last field value updated.
const handleChange = (event) => {
  event.preventDefault();
  setFormData({ // <-- new object with only field name/value
    [event.target.name]: event.target.value
  });
};

You must manage this yourself, manually. Use a functional state update to access and shallow copy the previous state into the next state object.
const handleChange = (event) => {
  event.preventDefault();
  const { name, value } = event.target;
  setFormData(data => ({
    ...data,
    [name]: value,
  }));
};


text:
Q: I am using Angular 4 for my project, writing code for range slider After compilation in browser I am getting this issue:

moduleId should be a string in "Ng2SliderComponent

enter image description here
enter image description here
While compiling I am getting below error:

Argument of type '{ selector: string; templateUrl: string; directives:
  typeof SlideAbleDirective[]; changeDetection...' is not assignable to
  parameter of type 'Component'. Object literal may only specify known
  properties, and 'directives' does not exist in type 'Component'.

A: You are probably referring to an old angular version. Since a long time (NgModule) the @Component decorator no longer has the directives array. This has been moved to the NgModule declarations array. You should remove any directive you have in your @Component, and move it to your NgModule


text:
Q: python tkinter infinite loop freezes im currently making a tkinter app that auto backup files by watching the last mod
time of the file. code is as below.
from tkinter import *
from tkinter import filedialog
import shutil
import os
from datetime import datetime

app = Tk()
app.title("7dtd auto backup")
app.geometry("800x500")
stopsign = False

def stop():
    global stopsign
    stopsign = True

def getSrcFolderPath():
    folder_selected = filedialog.askopenfilename()
    src_text.set(folder_selected)

def getDstFolderPath():
    folder_selected = filedialog.askdirectory()
    dst_text.set(folder_selected)

def watchpath(file, folder):
    global stopsign
    file = file.get()
    folder = folder.get()
    backupnum = 1
    if file != "":
        lastmtime = os.path.getmtime(file)
        while stopsign == False:
            if os.path.getmtime(file) != lastmtime:
                lastmtime = os.path.getmtime(file)
                shutil.copytree(os.path.dirname(file), folder+"/backup"+str(backupnum))
                backupnum += 1

src_text = StringVar() #source file selector
src_label = Label(app, text="save file")
src_label.grid(row=0, column=0)
src_entry = Entry(app, textvariable=src_text)
src_entry.grid(row=0, column=1)
src_btn = Button(app, text="browse", width=12, command=lambda: getSrcFolderPath())
src_btn.grid(row=0, column=2)

dst_text = StringVar()
dst_label = Label(app, text="destination folder")
dst_label.grid(row=0, column=3)
dst_entry = Entry(app, textvariable=dst_text)
dst_entry.grid(row=0, column=4)
dst_btn = Button(app, text="browse", width=12, command=lambda: getDstFolderPath())
dst_btn.grid(row=0, column=5)

start_btn = Button(app, text="start", width=12, command=lambda: watchpath(src_text, dst_text))
start_btn.grid(row=2, column=0)
end_btn = Button(app, text="end", width=12, command=lambda: stop())
end_btn.grid(row=2, column=1)

app.mainloop()

the idea is that im setting an infinite loop for the function to keep fetching the last mod time of the file until it has changed, but doing so will make my app freeze during the loop, which means that the app can only be stopped by closing. Is there a way to make it not freeze while still maintaining the function of detecting the change in last mod time?
Much appreciated!

A: The tkinter package offers a widget.after() function that allows you to call a function of your choice after a delay of X milliseconds. It's signature is as follows: w.after(delay_ms, callback=None, *args_for_your_function)
To make your code work, you can declare lastmtime as a global variable at the start of your code and then change your watchpatch function to the following:
def watchpath(fileVar, folderVar):
    print("watchpatch firing...")
    global stopsign
    global lastmtime
    if stopsign:
        stopsign = False
        print("Stopping watchpath!")
        return
    file = fileVar.get()
    folder = folderVar.get()
    backupnum = 1
    if file != "" and os.path.getmtime(file) != lastmtime:
        lastmtime = os.path.getmtime(file)
        while os.path.exists(folder+"/backup"+str(backupnum)):
            backupnum += 1
        print("Copying folder contents to backup folder...")
        shutil.copytree(os.path.dirname(file), folder+"/backup"+str(backupnum))
        backupnum += 1
    app.after(1000, watchpath, fileVar, folderVar)

Points to note:

*

*Your program actually seems to copy the entire contents of the srcfile directory to the specified backup directory, not just the individual file. I've left this logic as-is, but you might want to change it if your goal is to backup just the one file.

*I added in some basic print statements to help you understand what's happening. Remove these once you're good to go.


text:
Q: recv() in C socket returns 0 for some requests I have an issue with recv() and read() methods as well, both return 0 byte for some of my requests. On the other hand, I made a java application to do the same, and it always get me the response from the server, I mean the issue only happens with my C application, but not happen on Java. So please revise my below main method for that.
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <limits.h>
#define PORT 7142

typedef unsigned char BYTE;

//function to convert string to byte array
void string2ByteArray(char* input, BYTE* output)
{

    int loop;
    int i;

    loop = 0;
    i = 0;

    while (input[loop] != '\0')
    {
        output[i++] = (unsigned char)input[loop++];

    }
}

int toDigit(char ch, int index) {
    int digit;
    if (ch >= '0' && ch <= '9')
        digit = ch - '0';
    if (ch >= 'A' && ch <= 'F')
        digit = ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f')
        digit = ch - 'a' + 10;

    if (digit == -1) {
        // throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
        return -1;
    }
    return digit;
}

void ToHex(BYTE data[], BYTE out[])
{
    int len = strlen(data);
    int i, j, f;
    if ((len & 0x01) != 0) {
        //throw new Exception("Odd number of characters.");
    }

    // two characters form the hex value.
    for (i = 0, j = 0; j < len; i++) {
        f = toDigit(data[j], j) << 4;
        j++;
        f = f | toDigit(data[j], j);
        j++;

        out[i] = (f & 0xFF);

    }

}

void encodeHex(int data[], char output[1024], int len) {
    int l = len, i = 0, j = 0;
    char out[l << 1];
    char DIGITS_LOWER[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    // two characters form the hex value.

    for (i = 0, j = 0; i < l; i++) {
        out[j++] =  DIGITS_LOWER[(unsigned int)((0xF0 & data[i]) >> 4)];
        out[j++] =  DIGITS_LOWER[(unsigned int)(0x0F & data[i])];

    }

    out[j] = '\0';
    strcpy(output, out);
}

int main(){
    char ascii_str[] = "Hello world!";
    int i;
    struct sockaddr_in address;
    int sock = 0, sRet, rdret = 0;
    struct sockaddr_in serv_addr;
    char sbuffer[] = "005a600003000001006038048020C090001663917561001880293100001701091820291201002100346391756100188029D2301521107398300f32323230303737373232323030303037202020202020203933385a4f1aceb81b09d7";
    int len = strlen(sbuffer);
    BYTE arr[len], arr1[len], bufferbyte[1024];
    char buffer[1024] ="";
    int tempBuffer[1024] = { 0 };
    char Recv[1024] = "";
    int* ptr;

    string2ByteArray(sbuffer, arr);

    ToHex(arr, arr1);

    if ((sock =  socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    if (inet_pton(AF_INET, "10.16.4.212", &serv_addr.sin_addr) <= 0)
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nConnection Failed \n");
        return -1;
    }

    sRet = send(sock, arr1, strlen(sbuffer), 0);
    printf("Hello message sent %d\n", sRet);

    rdret = recv(sock, buffer, 100,0);

    printf("Recieved Size1: %d\n", rdret);

    {

        int i = 0;
        int j = 0;

        for (i = 0; i <= rdret; i++)
        {
            if (buffer[i] == 0)
            {
                buffer[i] = buffer[i] + 256;

            }
            tempBuffer[j] = buffer[i];

            ++j;

        }
                encodeHex(tempBuffer, Recv, j - 1);

        printf("\nRecieved Data: %s\n", Recv);

    }

    return 0;
}

A: When recv or read returns 0 it means that the other end have nicely closed its connection, and you should do the same.
This is well-documented behavior and any socket book or tutorial should have mentioned it.


text:
Q: How write a CSV in R that is correctly read by Google Spreadsheets Problem
I am trying to write a dataframe to a CSV-file that will be read-in correctly by Google Spreadsheets however I am running into an error with a particular column format.
There is one column called 'details' that has values that look like this {\"campaign_id\":1,\"line_item_id\":1234}. This column format is correctly read by R from an original dataframe supplied from Google Spreadsheets but when written into a CSV, the column is separated along the , into two columns pushing overwriting the values of the following column (which is empty by default).
Data
The dataframe in R looks like this:
data <- structure(
  list(
    `Line Item Id` = c(1234, 4567),
    Details = c(
      "{\"campaign_id\":1,\"line_item_id\":1234}",
      "{\"campaign_id\":1,\"line_item_id\":4567}"
    ),
    `Bid Strategy Type` = c("",""),
    `TrueView Video Ad Formats` = c("In-stream / Video Discovery",
                                    "In-stream / Video Discovery"),
    `TrueView Bid Strategy Type` = c("Manual CPV",
                                     "Manual CPV")
  ),
  row.names = 1:2,
  class = "data.frame"
)

Current approach
I have tried writing the relevant column in a quote:
library(tidyverse)
data %>%
  mutate(Details = dQuote(Details,q = )) %>%
  write.csv("test.csv", fileEncoding = "UTF-8",na = "",row.names = FALSE,quote = FALSE)

But this does not seem to work and neither does omitting the dQuote.
My output csv is this:
test.csv generated by above code
More Details
The data being wrangled here is an SDF generated by DV360 a Google platform to manage YouTube ad campaigns. In my process I download an SDF from DV360 change some values in R and upload it back. However re-uploading does not work at the moment due to the described problem. I have tested it to confirm that the column problem described above is causing the issue and if manually corrected uploading works.
Expected output
I have added the expected output and the output I am getting.
What I have at the moment:
Line Item Id,Details,TrueView Video Ad Formats,TrueView Bid Strategy Type
14596716402,"{"campaign_id":283,"line_item_id":99588}",In-stream / Video Discovery,
14596725552,"{"campaign_id":283,"line_item_id":99585}",In-stream / Video Discovery,

What I need:
Line Item Id,Details,TrueView Video Ad Formats,TrueView Bid Strategy Type
1234,"{""campaign_id"":1,""line_item_id"":1234}",,In-stream / Video Discovery
4567,"{""campaign_id"":1,""line_item_id"":4567}",,In-stream / Video Discovery

And quite interestingly, what I get when I fiex the problem by hand in googlesheets and then download the file:
Line Item Id,Details,TrueView Video Ad Formats,TrueView Bid Strategy Type
1234,"""{""""campaign_id"""":1,""""line_item_id"""":1234}""",,In-stream / Video Discovery
4567,"""{""""campaign_id"""":1,""""line_item_id"""":4567}""",,In-stream / Video Discovery

A: After getting valuable input from @Greg and @MrFlick I was finally able to solve it.
For Google ecosystem (Spreadsheets and Dv360) to correctly read the column it needs to have this format:
"{""campaign_id"":1,""line_item_id"":1234}"

Using dQuote() will put the necessary quotes around the column but due to my system settings, the wrong quote type was supplied. So we need to put off useFancyQuotes.
Additionally the already occuring quotes around campaign_id and line_item_id need to be double-quoted.
Maybe there is a faster way but the following code will work:
library(dplyr) # only needed for pipe, not part of solution

options(useFancyQuotes = FALSE)

data %>%
  mutate(Details = dQuote(gsub('"','""',Details))) %>%
  write.csv("test3.csv", fileEncoding = "UTF-8",na = "",row.names = FALSE,quote = FALSE)

So we need to first convert all quotes to double Quotes, which I did with gsub() and then use dQuote() to put final quotes around the column making sure not to use fancy, directional quotes.


text:
Q: Meaning of "backwards" What's the meaning of backwards here? Does it mean it's going towards a worse state?

English is hands down the most comprehensive and efficient language. The language of an advanced civilization
lol I know you are goofing around but after learning Spanish and being able to speak it fluently for almost 15+ years now, English is such a backwards piece of s***.

A: If it does mean that, the commenter doesn't know as much about English as he imagines; backwards in that sense can only be applied to a verb. Backward would fit, as the opposite of advanced; whether that can properly be applied to a language (as opposed to a creole) is probably beyond the scope of this site.

A: I'm not so sure I buy the "backwards to a worse state" theory.  It is very common to hear people talk about a particular place or group of people as "backwards."  It is not, in my experience, typically used as a relational adjective.
The meaning is very similar to "provincial" though I'm not sure of the origin.  There are other variants that I expect are related, especially when discussing geographical locations.  For example:

One critic who gave the Manet show highest marks was the New York Times's John Canaday, who then went on to blast New York as a "cultural backwater" because the show would not be seen at any of its museums.

A: In this example "backwards" is used as an adjective, and therefore incorrectly. "Backwards" is an adverb (roughly, modifies anything but nouns), "backward" can be used both as an adverb (thus, safer bet, if less expressive), and as an adjective (modifier or qualifier of nouns and noun phrases).

A: Look at the second case under entry #3 here:

towards or into a worse state

It means that, after having learned Spanish, English looks like going back to a worse state. Exactly as you imagined.


text:
Q: why this left join returns only one record? Here is a sample input, SQL and output, and wondering why only one row is returned? I am using MySQL/MySQL Workbench.
+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

SELECT
  score_primary.score, COUNT(DISTINCT score_higher.score) + 1 AS rank
  FROM
    TestRank score_primary
  LEFT JOIN TestRank score_higher ON score_higher.score > score_primary.score

Output:
+-------+------+
| score | Rank |
+-------+------+
|   3.5 | 4    |
+-------+------+

BTW, if I add group by, for this new SQL statement, how do I know if (1) group by is first executed, then left join on group-by results, or (2) left join, then group-by on left join results?
SELECT
  score_primary.score, COUNT(DISTINCT score_higher.score) + 1 AS rank
  FROM
    TestRank score_primary
  LEFT JOIN TestRank score_higher ON score_higher.score > score_primary.score
  GROUP BY score_primary.score

A: Using aggregate function (e.g. COUNT()) without GROUP BY will cause implicit GROUP BY grouping all rows into a single row.

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.


text:
Q: Rails moving queries from view to controller Got this code for view and controller:
# matches/show.html.haml
%h3
  Players

-@clans.each do |clan|
  %h4=link_to clan.name, clan
  %ul
    -@players.find_all_by_clan_id(clan.id).each do |player|
      %li
        %strong=link_to player.name, player

%h3
-@rounds.each_with_index do |round,index|
  %h4
    Round
    =index+1

  -@clans.each do |clan|
    %h4=clan.name
    %ul
      -round.participations.includes(:player,:champion).find_all_by_clan_id(clan.id).each do |participation|
        %li
          =participation.player.name
          =participation.champion.name

# matches_controller.rb

class MatchesController < ApplicationController
  def index
    @matches = Match.played.includes(:clans).page(params[:page])

  end

  def show
    @match = Match.includes(:rounds,:clans).find(params[:id])
    @clans = @match.clans
    @rounds = @match.rounds

    @players = @match.players

  end
end

How do I move all unnecessary db queries, logic etc. from view to controller?
Maybe simplify this somehow?

A: Move it to the Match model, not the controller.  Your controller should usually only contain routing logic and setting an instance variable to use in the view.  The bulk of the code  should go in the model.  Skinny controllers, fat models.
Read up on scopes:
http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html
Also, this article is from 2006 (pre scopes), but most of it is still relevant to your question:
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
You really don't need to set instance variables for clans, rounds and players.  You can access these directly from @match in simple situations where you are iterating through an associated collection.  For example:
-@match.clans.each do |clan|

Otherwise, use a scope if its something more complicated than a simple has_many/belongs_to association.


text:
Q: Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: invalid literal for int() with base 10: 'DDoS' I was trying to run a deep learning model on the compressed dataset I retrieved from the bottleneck layer of an autoencoder. The dataset has 4 features and when I appended the target feature, the total features became 5. The target feature is made up of 2 classes which are: DDoS and Benign and I have fitted a random forest model on the dataset and the result was interesting. However, I intend to use a deep learning approach to fit on the dataset but I keep get the error Error in py_call_impl(callable, dots$args, dots$keywords): ValueError: invalid literal for int() with base 10: 'DDoS'. I decided to run my code line by line to enable me know where the error was coming from and it was coming the line where I tried to convert the target feature to one-hot using to_categorical(). Please is there a way I could go about it as I have installed keras library and the error has still not cleared?
Here's the code I used
 train <- DF2[sample(1:225711, 1*nrow(DF2)),]
>   Train2<- as.matrix(train) #convert datafarame to matrix and remove dimensions
>   dimnames(Train2) <-NULL
>   set.seed(222)
>   #data partition
>   part <- sample(1:225711, 0.8*nrow(Train2), replace = F)
>   training<- Train2[part,1:4]
>   testing <- Train2[-part,1:4]
>   trainingtarget <- Train2[part,5]
>   testingtarget <- Train2[-part,5]
>   trainLabels <- to_categorical(trainingtarget)
Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: invalid literal for int() with base 10: 'DDoS'

A: Oh! the target feature was a factor of string values: Benign and DDoS and so, immediately I converted the classes to numeric, 0 and 1, the error was resolved.


text:
Q: How to make a jQuery alert confirm box with "yes" and "no" How can I make jQuery work with my HTML and CSS? I need when I click on the button and open an alert box in the centre with some text and options "yes" , "no" and when click yes to delete the text.
My code is here:

Some text here

         x Delete

Demo

A: I won't write your code, but you are looking for something like a jQuery dialog
Take a look here
jQuery modal-confirmation
$(function() {
    $("#dialog-confirm").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $(this).dialog("close");
        },
        Cancel: function() {
          $(this).dialog("close");
        }
      }
    });
  });

    These items will be permanently deleted and cannot be recovered. Are you sure?

A: This plugin can help you:
craftpip/jquery-confirm
It's easy to setup and has a great set of features.
$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-blue',
            keys: ['enter', 'shift'], // trigger when enter or shift is pressed
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});

Other than this, you can also load your content from a remote URL.
$.confirm({
    content: 'url:hugedata.html' // location of your hugedata.html.
});

A: See the following snippet:

$(document).on("click", "a.deleteText", function() {
    if (confirm('Are you sure ?')) {
        $(this).prev('span.text').remove();
    }
});

    some text
     x Delete


text:
Q: Is it possible to iterate through a vector of vectors columnwise? I have a vector of vectors of strings. I want to find the lengths of the longest string in each column. All the subvectors are of the same length and have an element stored in it, so it would be rather easy to find it with two for loops and reversed indices.
vector<vector<string>> myvec = {
                                { "a", "aaa",   "aa"},
                                {"bb",   "b", "bbbb"},
                                {"cc",  "cc",  "ccc"}
                               };

But is it possible to do it with iterators without using indices?

A: Assuming the inner vectors are all the same length, you can have something like
template <typename T>
class columnwise {
    std::vector<std::vector<T>> * underlying;
    struct proxy {
        std::vector<std::vector<T>> * underlying;
        std::vector<T>::difference_type offset;
        struct iterator {
            std::vector<std::vector<T>>::iterator outer;
            std::vector<T>::difference_type offset;
            using reference = typename std::vector<T>::reference;
            using pointer = typename std::vector<T>::pointer;
            iterator operator++() { ++outer; return *this; }
            reference operator*() { return *(outer->begin() + offset); }
            pointer operator->() { return (outer->begin() + offset).operator->(); }
            bool operator==(iterator rhs) { return (outer == rhs.outer) && (offset == rhs.offset); }
        };
    public:
        iterator begin() { return { underlying->begin(), offset }; }
        iterator end() { return { underlying->end(), offset }; }
    };
    struct iterator {
        // member type aliases
        std::vector<std::vector<T>> * underlying;
        std::vector<T>::difference_type offset;
        iterator operator++() { ++offset; return *this; }
        proxy operator*() { return { underlying, offset }; }
        bool operator==(iterator rhs) { return (underlying== rhs.underlying) && (offset == rhs.offset); }
    };
    std::vector<T>::difference_type inner_size() { if (auto it = underlying->begin(); it != underlying->end()) { return it->size(); } return 0; }
public:
    columnwise(std::vector<std::vector<T>> & vec) : underlying(&vec) {}
    iterator begin() { return { underlying, 0 }; }
    iterator end() { return { underlying, inner_size() }; }
};

Which iterates as you expect.

A: What about something like this?
std::vector<std::size_t> max_lengths(myvec.front().size(), 0);
for (auto const& strings : myvec) {
    std::transform(max_lengths.begin(), max_lengths.end(), strings.begin(), max_lengths.begin(),
        [](std::size_t l, std::string const& s) {
            return std::max(l, s.size());
        }
    );
}

Demo

A: Here is a solution using C++20 ranges and lambdas that is similar to Nelfeals answer:
// returns a function returning the i-th element of an iterable container
auto ith_element = [](size_t i) {
    return [i](auto const& v){
        return v[i];
    };
};

// returns a range over the i-th column
auto column = [ith_element](size_t i) {
    return std::views::transform(ith_element(i)); // returns a range containing only the i-th elements of the elements in the input range
};

// returns the size of something
auto length = [](auto const& s){ return s.size(); };

// returns the max length of the i-th column
auto max_length_of_col = [column, length](auto const& v, size_t i) {
    return std::ranges::max(
        v | column(i) | std::views::transform(length)
    );
};

I personally like how the ranges library helps you convey intent with your code, rather than having to prescribe the procedure to achieve your goal.
Note that if you replace the body of inner lambda in ith_element with the following block, it will also work for iterable containers without random access.
auto it = v.cbegin();
std::ranges::advance(it, i);
return *it

Demo
As a final remark, this solution lets you iterate over one column given an index of the column. I would advise against implementing a column iterator for vector<vector>: The existence of an iterator implies that something exists in memory that you can iterate over. The existence of columns is only implied by the additional information that you have given us, namely that all rows have the same length. If you do want iterators both for columns and rows, I would wrap your container in a new type (usually called matrix or similar) that properly conveys that intent. Then you can implement iterators for that new type, see Calath's answer.
EDIT:
I realized that my argument against a column iterator can be used as an argument against the column function in this answer as well. So here is a solution that let's you iterate over columns in a range-based for loop intead of iterating over column indices:
for (auto column : columns(myvec)){
    std::cout << max_length(column) << std::endl;
}


text:
Q: Uncaught Error: Cannot instantiate interface IndexTableRowSizeEstimatorInterface I am upgrading our magento 2.1.9 to magento 2.2.7.
When reindexing catalog_category_product, it throw this error:
[23-Jan-2019 09:49:39 UTC] PHP Fatal error:  Uncaught Error: Cannot instantiate interface Magento\Framework\Indexer\IndexTableRowSizeEstimatorInterface in /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:111
Stack trace:
#0 /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/Factory/Compiled.php(108): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Framewo...', Array)
#1 /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/Factory/Compiled.php(150): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...')
#2 /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/Factory/Compiled.php(79): Magento\Framework\ObjectManager\Factory\Compiled->get('Magento\\Framewo...')
#3 /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/ObjectManager.php(70): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...')
#4 /home/don/Web/fabelio22/vendor/magento/module-catalog/Model/Indexer/Category/Product/Action/Full.ph in /home/don/Web/fabelio22/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 111

The di.xml in Magento_Catalog is
<type name="Magento\Catalog\Model\Indexer\Category\Product\Action\Full">
   <arguments>
      <argument name="batchRowsCount" xsi:type="number">100000</argument>
      <argument name="batchSizeManagement" xsi:type="object">Magento\Catalog\Model\Indexer\CategoryProductBatchSize</argument>
   </arguments>
</type>
<virtualType name="Magento\Catalog\Model\Indexer\CategoryProductBatchSize" type="Magento\Framework\Indexer\BatchSizeManagement">
   <arguments>
      <argument name="rowSizeEstimator" xsi:type="object">Magento\Catalog\Model\Indexer\Category\Product\RowSizeEstimator</argument>
   </arguments>
</virtualType>

But $rowSizeEstimator is not injected with the correct class.It tries to instantiate \Magento\Framework\Indexer\IndexTableRowSizeEstimatorInterface instead. generated/metadata/global.php is generated, but it's like Magento  ignore the compiled di file.

A: Try clearing the cache and generation directories.

*

*Clear var/generation

*Clear var/cache

*Run bin/magento setup:upgrade and bin/magento setup:di:compile
Note: If you use redis for caching then you should also consider clearing redis cache.

A: I have faced the similar issue i.e. cannot instantiate interface for some third party module.
The reason that I found out after debugging that the corresponding module's entry was missing from the app/etc/config.xml but the module's code was present in the codebase.
After manually adding the module's entry in the app/etc/config.xml file, the issue got resolved.


text:
Q: How to use Sensu email handler for contact routing Suppose I am checking some metrics of AWS instances using sensu plugins and need to trigger email alerts only to a specific instance owner rather than a cloud operations team how can it be done.
As per my research each check has a contact list but how can we make this contact list specific to an instance. Any ideas would help.


text:
Q: SQL Server 2008 Restore I'm trying to restore from a database backup to SQL Server 2008.  The backup came from a different server.  I'm executing the following query:
RESTORE DATABASE Database_Name
FROM DISK = 'C:\Path\To\Backup.file'
WITH REPLACE
GO

If the database does not exist, I'm getting the following error:

Msg 3118, Level 16, State 1, Line 1
  The database "Database_Name" does not exist. RESTORE can only create a database when restoring either a full backup or a file backup of the primary file.
  Msg 3013, Level 16, State 1, Line 1
  RESTORE DATABASE is terminating abnormally.

The file is a full backup.
If the database does exist, I get the following error:

Msg 3154, Level 16, State 4, Line 1
  The backup set holds a backup of a database other than the existing 'Database_Name'  database.
  Msg 3013, Level 16, State 1, Line 1
  RESTORE DATABASE is terminating abnormally.

From what I understand, WITH REPLACE is supposed to be a workaround for this.
I'm stumped.

A: Try this:
CREATE DATABASE foo;
GO
CREATE DATABASE bar;
GO
BACKUP DATABASE foo TO DISK = 'c:\temp\x.bak';
BACKUP DATABASE bar TO DISK = 'c:\temp\x.bak';
GO
RESTORE HEADERONLY FROM DISK = 'c:\temp\x.bak';

Relevant columns for this scenario:
Position  DatabaseName
--------  ------------
1         foo
2         bar

To restore foo, whether it exists or not:
RESTORE DATABASE foo FROM DISK = 'c:\temp\x.bak'
  WITH FILE = 1, REPLACE;

To restore bar, whether it exists or not:
RESTORE DATABASE bar FROM DISK = 'c:\temp\x.bak'
  WITH FILE = 2, REPLACE;

If you don't specify WITH FILE, you will get a slew of errors, depending on whether the database in Position = 1 already exists.
The lessons here:

*

*do not use common and generic names for backup files - name them for the database they represent and keep them separate.

*use WITH INIT if you expect a backup file to only ever contain one copy of a backup.

*understand what is in your backup by first running RESTORE
HEADERONLY and/or RESTORE FILELISTONLY.

If you show us those two columns from the output of RESTORE HEADERONLY and what database you are actually trying to restore, we can provide you with a specific command that should work.

A: Thanks for your suggestions everyone.. the issue ended up being my own mistake. The backup file that I was recovering from contained TWO database backups and a database log backup. My issue was that I was choosing to restore from the log AND one or more database backups. The solution was just ticking off ONE of the database backups contained in the backup file..
Again, thanks for the help everyone!


text:
Q: Redirect example.com to example.com/blog I have uploaded my website under a sub-directory on my server the structure is looks something like this
root
----blog
--------.htaccess
----apple
----.htaccess
Now I have written a rule inside my /blog/.htaccess file which will redirect users to

https://www.example.com/blog/

I have done this by adding the following rule.
RewriteEngine On
RewriteBase /blog/

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

so far so good it is working exactly like the requirements, Now the real issue come. User wants that when ever any one hit the domain without the preceding blog it will add the /blog/ and redirects the user to the blog site and this rule should not effect any sub-domain means if
User enters the url.

example.com

He should be redirected to.

https://www.example.com/blog/

And when he enters url.

apple.example.com

He should redirected to

apple.example.com

Now In order to do so I am writing the following rule but it is not working the rule looks like this.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) https://example.com/$1 [R=301,L]
RewriteRule ^$ /blog/ [L]

I don't know what I am doing wrong.
I have added so much detail because I thought may be the .htaccess file inside the blog directory is making an issue.

A: Found the issue with the help of @Twinkle the real issue was that I was adding
RewriteRule ^$ /blog/ [L]

which I didn't needed for obvious reasons by removing this rule and changing my current rule to the following rule resolved my problem.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) https://example.com/blog/ [R=301,L]

RewriteCond %{HTTP_HOST} ^www.example\.com$
RewriteRule (.*) https://example.com/blog/ [R=301,L]

Hope some one find this help full.

A: Try this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^(.*)$ http://www.example.com/blog/$1 [L,R=301,NC]

Let me know if it works.


text:
Q: How do I declare a global matrix in NETLOGO? (Using matrix extension) I found an example using the following sintax:
let A matrix: from-row-list [[3 5] [0 1]]
let B matrix: from-row-list [[3 0] [5 1]]

But it keeps showing: Expected keyword. It selects the let reserved word. Thanks.

A: let defines a variable that's local to a procedure or other embedded context, and it generates that error if used at the top level.  I guess that let doesn't count as a "keyword" in that context.
To define a global matrix, specify the variable name in globals, and then set it inside a procedure:
extensions [matrix]

globals [A B]

to setup
  set A matrix:from-row-list [[3 5] [0 1]]
  set B matrix:from-row-list [[3 0] [5 1]]
end

Then add a button that calls setup.  Note that you need to remove the space after "matrix:"


text:
Q: Kernel opps doesnt break into kgdb stub This is annoying.  I have the kernel built with debugging, kgdb over serial, and it works fine for normal debugging.  But when an oops occurs it doesnt break into the debugger if it is running or allow me to start the debugger and examine the oops.  This is particularly annoying as staticly declared functions dont show up in the oops stack trace making it hard to know exactly what code was called.
BTW this is running on an ARM 11 chip.
Anyone else seen this or know of a way to get it working?
Thanks in advance.


text:
Q: Excel VBA PDF Converted Text Extraction I am working with some code that was written for me, and I am having trouble with the Department value. I do not want it to only put out one word which is what it is doing now, and I do not know where to place it so that it doesn't remove all of the text except for just one word. This is the code:
(One of the lines will not space over to change it into a code view and I'm not sure how to fix that)
'===============================================================
Private Enum i_
    ž__NONE = 0
  ID
  Last
  First
  Middle
  Rank
  Department
    ž__
    ž__FIRST = ž__NONE + 1
    ž__LAST = ž__ - 1
End Enum

Public Sub EditedVersion_ExtractFieldValues()

  Const l_Table_1     As String = "Table 1"
  Const l_FieldValues As String = "FieldValues"
  Const l_last_first_middle As String = "last first middle"
  Const s_FieldNames        As String = "id " & l_last_first_middle & " rank" & " department"
  Const n_OutputRowsPerRecord As Long = 7

  Dim ƒ As Excel.WorksheetFunction: Set ƒ = Excel.WorksheetFunction
  Dim ¡ As Long
  Dim dictFields As Object

 Set dictFields = CreateObject("Scripting.Dictionary")
 dictFields.CompareMode = vbTextCompare

  With Worksheets
    On Error Resume Next
    .Add(After:=.Item(.count)).name = l_FieldValues
    On Error GoTo 0
    Application.DisplayAlerts = False
      If .Item(.count).name <> l_FieldValues Then
        .Item(.count).Delete
        .Item(l_FieldValues).UsedRange.Clear
      End If
      .Item(l_FieldValues).Columns(1).NumberFormat = "@"
    Application.DisplayAlerts = True
    .Item(l_Table_1).Activate
  End With

  Dim astrFieldNames() As String
  astrFieldNames = Split(" " & s_FieldNames, " ") ' Force index zero to a blank -> treat as base 1

  With dictFields
    .CompareMode = vbTextCompare
    For ¡ = i_.ž__FIRST To i_.ž__LAST
      dictFields.Add astrFieldNames(¡), ""
    Next ¡
  End With
  Dim lngLastUsedRow As Long
  lngLastUsedRow _
  = Cells _
 .find _
      ( _
        What:="*" _
      , After:=Cells(1) _
      , LookIn:=xlFormulas _
      , Lookat:=xlPart _
      , SearchOrder:=xlByRows _
      , SearchDirection:=xlPrevious _
      ) _
     .Row

  With Range(Rows(1), Rows(lngLastUsedRow))

    Dim arngFoundCells(i_.ž__FIRST To i_.ž__LAST) As Range
    For ¡ = i_.ž__FIRST To i_.ž__LAST
      Set arngFoundCells(¡) = .find(What:=astrFieldNames(¡),  After:=Cells(1))
    Next ¡
    Dim lngFirstFoundRow As Long
    lngFirstFoundRow _
    = ƒ.Min _
        ( _
          arngFoundCells(i_.Last).Row _
        , arngFoundCells(i_.First).Row _
        , arngFoundCells(i_.Middle).Row _
        )
    Dim lngOuputSheetNextRow As Long
    lngOuputSheetNextRow = 1

    Dim varFoundCell As Variant
    Dim lngNextFoundRow As Long
    Dim rngNextFindStart As Range
    Dim astrSplitValues() As String
    Dim strFoundValue As String
    Dim lngFieldCount As Long
    Do
      For ¡ = i_.ž__FIRST To i_.ž__LAST
        'Debug.Print arngFoundCells(¡).Address; " ";
        dictFields.Item(astrFieldNames(¡)) = ""
      Next ¡
      Debug.Print
      Select Case True
        Case arngFoundCells(i_.First).Row = arngFoundCells(i_.Middle).Row:
      ' Edge case: missing rank (found rank is for next employee) -> copy first to rank (simplifies following code)
          'If varFoundCels(
          If arngFoundCells(i_.Rank).Row <> arngFoundCells(i_.First).Row Then
            Set arngFoundCells(i_.Rank) = arngFoundCells(i_.First)
          End If

          For Each varFoundCell In arngFoundCells
            If Not varFoundCell Like astrFieldNames(i_.Department) Then
            strFoundValue = ƒ.Trim(Replace(Replace(varFoundCell.Value2, vbLf, " "), ":", "")) & " "
            If strFoundValue Like "[']*" Then strFoundValue =     Mid$(strFoundValue, 2)
            ' ID field: only retain the first word of value
            End If
            If LCase$(strFoundValue) Like astrFieldNames(i_.ID) & "*" Then
              strFoundValue = Left$(strFoundValue, InStr(InStr(strFoundValue, " ") + 1, strFoundValue, " "))
            End If
            ' Department field: only retain the first word of value'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''THIS IS THE DEPARTMENT FIELD
            If (varFoundCell) Like astrFieldNames(i_.Department) & " " Then
              strFoundValue = Trim(varFoundCell.Value)
            End If
            ' Edge case: no last name value in merged cell -> assume value is in first cell of following row
            Debug.Print LCase$(strFoundValue)
            If LCase$(strFoundValue) Like astrFieldNames(i_.Last) & " " Then
              strFoundValue = ƒ.Trim(strFoundValue & Rows(varFoundCell.Row + 1).Cells(1).Value2) & " "
            End If
            ' Edge case: Field names only in row -> assume field values are on the following row
            If LCase$(strFoundValue) Like l_last_first_middle & "*" _
            And Len(strFoundValue) - Len(Replace(strFoundValue, " ", "")) < 5 _
            Then
              strFoundValue = ƒ.Trim(strFoundValue & Rows(varFoundCell.Row + 1).Cells(1).Value2) & " "
            End If
            astrSplitValues = Split(" " & strFoundValue, " ") ' Force index zero to a blank -> treat as base 1
            ' Array contains one/some/all field names first and then the values (with a possible extra blank value)
            lngFieldCount = Int(UBound(astrSplitValues) / 2)
            For ¡ = 1 To lngFieldCount
              dictFields.Item(astrSplitValues(¡)) = astrSplitValues(¡ + lngFieldCount)
            Next ¡

          Next varFoundCell

           'Only allow the id to be on the previous row
          If arngFoundCells(i_.ID).Row <> arngFoundCells(i_.First).Row - 1 Then
            dictFields.Item(astrFieldNames(i_.ID)) = 0
          End If
        Case Else
          Debug.Print "  SKIPPED: ";
          For ¡ = i_.ž__FIRST To i_.ž__LAST
            'Debug.Print arngFoundCells(¡).Address; " ";
          Next ¡
          Debug.Print
          For ¡ = i_.ž__FIRST To i_.ž__LAST
            Debug.Print "    "; ƒ.Trim(arngFoundCells(¡).Value2)
          Next ¡
          Debug.Print
      End Select
Sheets(l_FieldValues).Columns(1).Cells(lngOuputSheetNextRow).Resize(n_OutputRowPerRecord - 1).Value = ƒ.Transpose(dictFields.Items)
      lngOuputSheetNextRow = lngOuputSheetNextRow + n_OutputRowsPerRecord
      Set rngNextFindStart = Rows(arngFoundCells(i_.First).Row + 2).Cells(1)
      For ¡ = i_.ž__FIRST To i_.ž__LAST
        Set arngFoundCells(¡) = .find(What:=astrFieldNames(¡),
After:=rngNextFindStart)
      Next ¡
      lngNextFoundRow _
  = ƒ.Min _
      ( _
        arngFoundCells(i_.Last).Row _
      , arngFoundCells(i_.First).Row _
      , arngFoundCells(i_.Middle).Row _
      )
    Loop While lngNextFoundRow <> lngFirstFoundRow
  End With

End Sub


text:
Q: Module not found: Error: Can't resolve 'classlist.js' in angular cli 6.1.3 I am getting following while running ng buid --watch command in terminal,
ERROR in ./src/polyfills.ts
Module not found: Error: Can't resolve 'classlist.js' in 'E:\eclipse_dis_workspace\tourdubai\UI\src'

following version used,
Angular CLI: 6.1.3
Node: 8.11.3
OS: win32 x64
Angular: 6.1.2
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.7.3
@angular-devkit/build-angular     0.7.5
@angular-devkit/build-optimizer   0.7.5
@angular-devkit/build-webpack     0.7.5
@angular-devkit/core              0.7.3
@angular-devkit/schematics        0.7.3
@angular/cli                      6.1.3
@ngtools/webpack                  6.1.5
@schematics/angular               0.7.3
@schematics/update                0.7.3
rxjs                              6.2.2
typescript                        2.7.2
webpack                           4.9.2

i did all the setup configuration, like npm i.
thanks in advance.

A: remove the current package
npm uninstall classlist.js --save

then run
npm cache verify

run
npm install classlist.js --save-exact

A: There are different options;
I would suggest to add
(window as any).global = window;

in polyfills.ts;
if that doesn´t work, then add
<script>
var global = global || window;
var Buffer = Buffer || [];
var process = process || {
env: { DEBUG: undefined },
version: []
};
</script>

to Index.html; either of them should work.


text:
Q: URL problem: www.sitename.com/blog and www.sitename.com/learn using same WP installation I'm sure there has to be some way to make this with single wordpress instalation. Posts for "learn" page are tagged with "learn" and I built a custom template that has loop that prints only posts from that category. Also, posts on that "learn" page should have links like they are on separate WP installaton (www.sitename.com/learn/date-postname..) and same for blog (www.sitename.com/blog/date-postname..)

A: Not sure I exactly understand your problem, but it sounds like what you want to do could easily be accomplished using Custom post types: http://codex.wordpress.org/Post_Types#Custom_Types
This would basically allow you to have an entire segment just for 'learn' completely separated from your general posts/blog - you could even give 'learn' it's own styling by using if ( 'learn' == get_post_type() )


text:
Q: About spherical coordinates I will post an image which believe it is essential to understand the question:
See the image:
Figure book

Spherical coordinates $r, \theta, \phi$ are perfectly intuitive
because the angles $\theta$ and $\phi$ correspond, respectively, to
longitude and latitude on the surface of the Earth, and $r$ is the
distance to the center of the Earth.

I believe the notation is wrong, since theta is the angle wrt north and south axis, shouldn't be the reverse?

A: Which textbook is this taken from? If it is a mathematics textbook, the convention is that $\phi$ corresponds to latitude and $\theta$ to longitude, but if it is a physics textbook, then $\theta$ will usually correspond to latitude and $\phi$ to longitude. This sort of confusion is why I usually stay away from spherical coordinates.

A: The $(r,\theta,\phi)$ convention for three dimensional spherical polar coordinates is used in mathematics, as it follows naturally from the $(r,\theta)$ convention used for the two dimensional case. However, physicists for some bizarre reason prefer $(r,\phi,\theta)$. What makes it even more confusing is that the very order the coordinates are written is also sometimes switched. Some authors order it as radial, azimuthal, polar which seems reasonable whereas some authors use radial, polar, azimuthal instead. So even if the author says "I'll use the $(r,\phi,\theta)$ convention" it might not even mean what you think it does!
So, if you're using spherical coordinates, it's best to explicitly state the coordinate transformation you're using. Here's a passage from some recent work of mine:

I will also use the $\displaystyle ( r,\theta ,\phi )$ convention for spherical coordinates, as used by Wolfram Mathworld. Explicitly, the coordinate transformation is
\begin{equation*}
\begin{bmatrix}
x\\
y\\
z
\end{bmatrix} =\begin{bmatrix}
r\cos \theta \sin \phi \\
r\sin \theta \sin \phi \\
r\cos \phi
\end{bmatrix}
\end{equation*}

Suggested reading: https://mathworld.wolfram.com/SphericalCoordinates.html


text:
Q: How to make a Pandoc table wider than textwidth? I'm adding a table to a document and discovered that the columns are too narrow, making it a bit difficult to read. Therefore I'd like to make the entire table (and thus also the individual columns relative sizes) wider while keeping the textwidth of the rest of the document unchanged. Is it possible to do this using the Pandoc multi-line tables? Or do I need to use pure LaTeX for this table?
This is what the Pandoc markdown for my table looks like:
--------------------------------------------------------------------------------------------------------------------------------------------------------
DSR Activity                           Description                                   In this thesis
-------------------------------------- --------------------------------------------- -------------------------------------------------------------------
1. Problem Identification & Motivation The specific research problem is defined,     The research problem was initially defined by Simon Hacks
                                       and the value of a solution is justified.     and Robert Lagerström in a thesis proposal. The value of
                                                                                the solution is that the produced artifact will establish
                                                                                a foundation for further work in EAD detection and analysis.

2. Defining Objectives for a Solution  The objectives of the solution are infered    In order to determine the objectives of the solution the problem
                                       from the problem definition and knowledge     definition is examined.
                                       about what is possible and feasible. This
                                       might e.g. be a description of how the
                                       artifact is expected to support solutions
                                       to problems which have not yet been
                                       addressed.
--------------------------------------------------------------------------------------------------------------------------------------------------------

And the resulting PDF (compiled simply using pandoc myfile.md -o myfile.pdf), where you can see that the table is only as wide as the textwidth:

In case it matters, I'm using
\usepackage{fancyhdr}
\pagestyle{fancy}

A: A crude but effective method is to widen the \columwidth just for the table. You'll probably want to change the \LTleft table margin, like so:
```{=latex}
\newlength{\extraspace}
\setlength\extraspace{4cm}
\setlength\columnwidth{\columnwidth + \extraspace}
\setlength\LTleft{-0.5\extraspace + \tabcolsep}
```

Table goes here

```{=latex}
% restore old columnwidth, table placement
\setlength\columnwidth{\linewidth - 4cm}
\LTleft=\fill
```

Result:

A: I ended up using this solution:
\usepackage[textwidth=12.1cm,textheight=22cm]{geometry}

...

\newgeometry{textwidth=18cm,textheight=22cm}

<!-- my table here -->

\restoregeometry


text:
Q: Superscript in axis labels in ggplot2 for ions I need to achieve superscript in an axis label within ggplot2, similiar to this question: Superscript and subscript axis labels in ggplot2
However, I will need to write something like this: Ca^2+. This seems not to work with this approach, even if I put the exponent in { } with the bquote command. I tried to read through help("plotmath") but couldn't find an example for my case. I tried escaping the + with \+ and ++ but was not successful.
Edit: I would like to not use any additional packages.

A: using the ggtext package makes this straight forward.
Code shamelessly adapted from Claus Wilke's example in the readme. https://github.com/wilkelab/ggtext
library(tidyverse)
library(ggtext)
library(glue)

data <- tibble(
  atom = "Ca",
  charge = "2+",
  value = -0.5
)

data %>% mutate(
  color = "#009E73",
  name = glue("{atom}{charge}"),
  name = fct_reorder(name, value)
)  %>%
  ggplot(aes(value, name, fill = color)) +
  geom_col(alpha = 0.5) +
  scale_fill_identity() +
  labs(caption = "Example shamelessly adapted from Claus Wilke") +
theme(
    axis.text.y = element_markdown(),
    plot.caption = element_markdown(lineheight = 1.2)
  )

Created on 2020-07-21 by the reprex package (v0.3.0)

A: Try to put the superscript as a literal, between quotes.
g <- ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot()
g + xlab(bquote('Superscript as a literal' ~~ Ca^'2+'))

A: Using the example you provided, this works
library(ggplot2)
qplot(uptake, data = CO2) +
  xlab(bquote('Assimilation ('*mu~ 'mol' ~Ca^{"2+"} ~ m^-2~s^-1*')'))


text:
Q: Newline created after each iteration I'm using tqdm combined with Pandas on Jupyter notebooks.
I have a Pandas dataframe df.
When i use df.progress_apply, new lines are printed instead of updating only one.
This is what I currently do :
tqdm.pandas(desc="Computing MONTH...")
df["MONTH"] = df.progress_apply(compute_month, axis=1)

My question is not a duplicate of this question : tqdm in Jupyter Notebook
because they said to use tqdm_notebook instead of tqdm.
I can't use tqdm_notebook as I need to implement df.progress_apply.
I can't reproduce this issue on a minimal example because my code is too heavy.
Here is an issue in Github related of this problem but couldn't help me : https://github.com/tqdm/tqdm/issues/375

A: You should do something like that:
from tqdm import tqdm_notebook
tqdm_notebook().pandas()

And that will do!


text:
Q: Auto close Tags doesnt works in neo vim Hi im newbie with neovim and i want to close a Tag
For example
Input <html and when i press '>'
i hope this <html></html>
how to do this ?

A: It's not supported natively in neovim. You have to add a plugin like https://github.com/alvan/vim-closetag

A: As mentioned, neovim doesn't natively do this.  The other answer helps for HTML but for (most) other programming language I use endwise:
For HTML tags:  https://github.com/alvan/vim-closetag
For other languages:  https://github.com/alvan/vim-closetag


text:
Q: Futura font not rendering in firefox I have a problem with displaying specific futura fonts on firefox.
Actually I use 5 futura fonts and I got problem with one of them:
@font-face {
            font-family: 'FuturaLT-CondensedBold';
            src: url('fonts/futuraltcondensedbold.eot');
            src: url('fonts/futuraltcondensedbold.eot?#iefix') format('embedded-opentype'),
                     url('fonts/futuraltcondensedbold.woff') format('application/x-font-woff'),
                     url('fonts/futuraltcondensedbold.ttf') format('truetype'),
                     url('fonts/futuraltcondensedbold.svg#futuraltcondensedbold') format('svg');
            font-weight: normal;
            font-style: normal;
    }
@font-face {
                font-family: 'FuturaLT-Bold';
                src: url('fonts/futuraltbold.eot');
                src: url('fonts/futuraltbold.eot?#iefix') format('embedded-opentype'),
                         url('fonts/futuraltbold.woff') format('application/x-font-woff'),
                         url('fonts/futuraltbold.ttf') format('truetype'),
                         url('fonts/futuraltbold.svg#futuraltbold') format('svg');
                font-weight: normal;
                font-style: normal;
        }

@font-face {
                font-family: 'FuturaBT-LightCondensed';
                src: url('fonts/futura-ltcn-bt-light.eot');
                src: url('fonts/futura-ltcn-bt-light.eot?#iefix') format('embedded-opentype'),
                         url('fonts/futura-ltcn-bt-light.woff') format('application/x-font-woff'),
                         url('fonts/futura-ltcn-bt-light.ttf') format('truetype'),
                         url('fonts/futura-ltcn-bt-light.svg#futura-ltcn-bt-light') format('svg');
                font-weight: normal;
                font-style: normal;
        }
@font-face {
                font-family: 'FuturaBT-Medium';
                src: url('fonts/futuram.eot');
                src: url('fonts/futuram.eot?#iefix') format('embedded-opentype'),
                         url('fonts/futuram.woff') format('application/x-font-woff'),
                         url('fonts/futuram.ttf') format('truetype'),
                         url('fonts/futuram.svg#futuram') format('svg');
                font-weight: normal;
                font-style: normal;
        }

So, I have problem using  font-family: 'FuturaLT-Bold'; in firefox. The others are rendering just fine, but this one it appears as dark gray in firefox inspect element with firebug, like the font doesnt exists at all. The font was coverted by codeandmore font face generator.
I also changed my .httaccess file with following rules:
AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
but it didnt helped...
Any thoughts on this?

A: I don't see the css for FuturaLT-Book listed, could be the problem.


text:
Q: What is the most efficient way to create nested div's in Javascript? Essentially, I'm trying to recreate this code:

                Content

                Content

                Content

                Content

                Content

                Content

                Content

                More Content

        <button class="btn btn-primary btn-lg btn-block" style="margin-bottom:15px">Launch GPS!</button>

to generate every time I enter more information in that gets filled into the places above marked "content".
My problem isn't writing the javascript to append the data as much as it is creating a way to generate the above code each time I enter in data.
My thought about how to go about this problem was creating individual variables like so: (this is all inside of a function that gets called to return a finished var with all of these supposed variables strung together in a chain of appendChild functions)
var divDisplay = document.createElement('div');
divDisplay.className = 'row';
description.setAttribute("style", "-moz-border-radius: 18px 18px 18px 18px; -webkit-border-radius: 18px;  border-radius: 18px 18px 18px 18px; background-color:white; margin-bottom:20px;");

..then do appendChild() calls for further implementation.. like so:
var divDisplay2 = document.createElement('div');
divDisplay2.className = 'col-lg-12';
divDisplay.appendChild(
    divDisplay.appendChild(divDisplay2)
);

But ultimately I get errors, trying to place more content into those append child's.
Is there a better way? Faster way? Could you should me what you would do to code this?

A: I would hide the main div element somewhere in html (very like a template), and when user triggers a change, the container div can be read/reused by any selector and put into desired position by $(desiredPlace).html(container). That soution does not result in recreation of nested divs actually.
with pure js:
http://jsfiddle.net/c2jghmvk/

A: Using pure javascript, you can try with innerHTML like this:

document.getElementById("parent").onclick=
function appendEl(){
    var parent = document.getElementById("parent");
    parent.innerHTML += "
 child
";
}
#parent{
    border: 1px solid blue;
}

 click to add child in parent

A: There are plenty of ways to skin this cat but depending on how much you are doing it creating a hidden template and inserting that is probably the easiest option.
Just add the hidden block to your DOM

            {ContentHeading}

        {ContentText}

Then pull the HTML out of the template and insert your text
var parentDiv = document.getElementById('someDiv');
var myTemplate = document.getElementById('template');
var newRowHtml = myTemplate.innerHTML.replace('{ContentHeading}', heading).replace('{ContentText}', text);
document.getElementById('someDiv').innerHTML += newRowHtml;

Note that using the string replace function may not be your best option if you have a large template.
Alternatively if you are going to be inserting a lot of content you may be better off using a templating library. There are plenty to choose from but Handlebars code for example would look something like this.
var templateSource   = document.getElementById("row-template").innerHTML;
var template = Handlebars.compile(templateSource);

Then when you want to insert a row just use
var newRowHtml = template({
    heading: heading,
    text: text
});
document.getElementById('someDiv').innerHTML += newRowHtml;


text:
Q: How to detect Windows Logon event using OnSessionChange in C# I am not able to detect this Logon event in Windows.
Here is my code:
namespace ConsoleApplication2
{

    public class MyService: ServiceBase
    {
        public MyService()
        {
            CanPauseAndContinue = true;
            CanHandleSessionChangeEvent = true;
        }

        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            base.OnSessionChange(changeDescription);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyService tpl = new MyService();
            Thread t = new Thread(delegate()
            {
                while (true) { }
            });
            t.Start();
        }
    }
}

How do I test run this app and then remote desktop into my laptop? I can see the event generated in Windows EventViewer, but my OnSessionChange is never called (I added a breakpoint inside).
Is my code wrong or is the way I am testing wrong?

A: Normally multiple concurrent remote desktop sessions are not allowed on any of Windows desktop systems.  So to use RDP to login as a different user then I assume that you have hacked this, or are using windows server (which rules out XP!).
Regardless, each user logged into the system will therefore have their own applications running and each set of applications are unique to that user.  So App1 could be run independently by each user.
That means that your console application cannot detect the other user that is logged on.
To do this you must use a Windows Service.  This runs in the background and can detect and work for multiple users and also detect login and logout.  See this SO link
This is the purpose of inheriting MyService from ServiceBase.  If you are not running the application as a service, then you are not running it correctly!
You need to first install your application as a service and then run it like a service.
You say that you don't think your application can run as a service.  I'm not sure why, but if this is the case then you would have to instead look at creating some kind of script to run your application upon start-up/login.
This way, every time somebody logs in then your application would run.  This might anyway be simpler for you.


text:
Q: How to remove item from ArrayList> one by one in android I am new to Android. I am Using "com.devsmart.android.ui.HorizontalListView" to show my items(playing cards). In the List I am getting 8 cards in the first attempt. What I want if I again call the method the there must be 7 cards so on means 1 cards must be remove from the list at each time till the list gets empty. But I am not able not do this removing of item from the list. I am posting my code here. Help will be appreciated.
MainActivity.java
ArrayList<HashMap<String, String>> aList9;
Button btn_aditional_card;
HorizontalListView list1;

int[] cards3 = new int[]{
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1,
        R.drawable.card1

};

public class MainActivity extends AppCompatActivity{

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

    btn_aditional_card = (Button) findViewById(R.id.btn_aditional_card);
    list1 = (HorizontalListView) findViewById(R.id.listview1);

btn_aditional_card.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          add8();
        }
    });
  }

 public void add8() {

   final android.view.animation.Animation animScale = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
    list1.startAnimation(animScale);

    aList9 = new ArrayList<HashMap<String, String>>();

    for (int i = 0; i < 8; i++) {
        HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("card", Integer.toString(cards3[i]));
        aList9.add(hm);
    }

    String[] from = {"card"};
    int[] to = {R.id.ImageView};

    final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList9, R.layout.activity_animation__adapter, from, to);
    list1.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               aList9.remove(aList9.size() - 1);
               adapter.notifyDataSetChanged();
           }
        });
     }

Here removing of item from the list must be done on list1.setOnItemClickListener but I don't have any idea how.

A: You can remove the last item from the list like;
if (aList9.size() > 0) {
   aList9.remove(aList9.size() - 1);
}

Another solution,
Take Length of your integer array and traverse the loop inside your add8 method according to this length and at the end of the method decrement the length by one, like;
int length = cards3.length;

Inside your add8 method;
for (int i = 0; i < length; i++) {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("card", Integer.toString(cards3[i]));
    aList9.add(hm);
}

After for loop decrement the length like;
length--;

Hope you'll get the solution.

A: In your list1.setOnItemClickListener, do this:
if (aList9.size() > 0) {
   aList9.remove(aList9.size() - 1);
   adapter.notifyDataSetChanged();
}

When removing item from data list, you have to notify your adapter to update view.

A: In your main activity the code should look like.I am using arraylist instead you can use hashmap.This code is only to show you way what you need to do. follow this code in your project you will get solution this is tested in my site and working fine  you need to change somewhere according to your code.In button click i am only removing last item from arraylist and notifying that dataset changed.hope it will help you.
ArrayList<String> arrlist = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arrlist.add("B");
        arrlist.add("C");
        arrlist.add("D");
        arrlist.add("E");
        arrlist.add("F");
        arrlist.add("G");
        ListView lv = (ListView) findViewById(R.id.listview);
        Button btnShowList = (Button) findViewById(R.id.btnShowList);

        final ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, arrlist);
        //Listview adapter
        lv.setAdapter(adapter);

        btnShowList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (arrlist.size() > 0) {
                    arrlist.remove(arrlist.size() - 1);
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }

A: Read the comments
class MainActivity extends AppCompatActivity {

//make your Adapter global
private SimpleAdapter adapter;
ArrayList<HashMap<String, String>> aList9;

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

    add8();

    btn_aditional_card.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // on button click you can add a view to the listview if you want
            // if you don't want this just comment out the following line
            // i still don't understand what you want to do with this button
            alist9.add(...);
            // if you add stuff in the array list then notify the adapter
            // it will update the view
            adapter.notifyDataSetChanged();
        }
    });

}

public void add8() {
    // initialize your ArrayList and listview
    //populate them
    for(int i = 0; i < 8; i++) {
        // do your stuff.
        // populate the list
    }

    // initialize your adapter as before
    adapter = new SimpleAdapter(....);
    listview.setadapter(adapter);
    adapter.notifyDataSetChanged();

    list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // delete the items like this
            // check if size is greater than 0 and then remove
           aList9.remove(aList9.size() - 1);
           adapter.notifyDataSetChanged();
       }
    });

}

}


text:
Q: Angular universal build baseHref change breaks angular routing in app I have an angular application set up to build prior to deployment to AWS lambda.  The serverless.yml file uses the stage: production entry, prefixing the deployment with /production.  When built and deployed this way, the generated styles, polyfills, and main js files return 403 errors.  If I change the production build baseHref: production/ in angular.json, the files can be found when deployed, but the angular routing breaks due to an unmatching url segment 'production'.  Adding a production route to the angular routing breaks everything completely.  Is there a way to fix this pathing issue?

A: Try using the deployUrl option in angular.json
deployUrl: '/production/'


text:
Q: AWS RDS must use vpc? When I am trying to launch a RDS DB instance, it seems like I must use a VPC -- there is no choice other than a VPC when I reach Configure Advanced Settings. Is there any way to avoid this?
To motivate this question, I am having problems connecting to the instance once it is created and previously (using a different AWS account) this connection was not a problem.
Could it be that with VPCs configured, then I am forced to choose among them?
Is it surprising that connecting to an RDS instance is more difficult when it runs in a VPC?


text:
Q: Upgrade to Windows 10: speaker volume is not as high as it used to be I recently upgraded from Windows 8.1 to 10 on my Dell XPS 13. It comes with the following audio devices and associated drivers:

I have version 6.0.1.7544 of the audio driver installed
The audio drivers available for Windows 10 on the Dell website specific to my laptop can be found here. At the time of writing, the driver version shown in the Dell site is 6.0.1.7509 which is weird because if I install the version shown by Dell, Windows 10 is happy to upgrade to the newer version.
However, no matter which of the above two versions I use, my sound volume is no where as high as it used to be before the upgrade.
Needless to say, I have checked all the obvious sound properties to no avail.
Looking to see if anyone has any suggestions as to what I can do.

A: I uninstalled both sound controllers shown, scanned for new hardware and accepted what was found. Volume increased back to what it had been previously. Worked for me, hopefully will work for you.


text:
Q: PPTP with restrictive access to local network for connecting clients How can I restrict access to my local network for VPN-clients connecting to a VPN-server (PPTPD) located on my network?
I would like clients to be able to connect to my linux node running a VPN server (PPTP) over the internet in order to access a SMB-drive located at the same node, but still limit access to the local network.
I don't want all connecting clients to have access to all my other network devices, how can I prevent this?

A: Add an iptables rule that will reference your PPTP-server internal interface (facing the LAN) that VPN clients will match. Probably with the VPN IP addresses pool you are using for your PPTP server. In order to reach your LAN SMB servers VPN client's packet will need to cross your VPN server's LAN interface, there you will filter them out.


text: Q: How is View Lifecycle managed in Android If I implement a custom view in Android, and onSaveInstanceState has been called (view is being reclaimed), is it possible that my view member variables will be reset as well on onRestoreInstanceState