text:
Q: AEM querybuilder class return I am attempting to use AEM's querybuilder API to do a generic search. The problem I am currently having is creating pagination with the querybuilder. While using the ResultPage class in AEM with SearchResult to getNextPage(). I am getting the result
com.day.cq.search.impl.result.ResultPageImpl@541bd4bf. How would I convert this into a URL? I already am using the offset and result total with the querybuilder but cannot find any more documentation to put me in the right direction.
  queryBuilder=resource.getResourceResolver().adaptTo(QueryBuilder.class);
//creating query based on the Query Description
Query query=queryBuilder.createQuery(PredicateGroup.create(map),session);
 //Getting and storing the Results
 List Pages1 = searchRes.getResultPages();
ResultPage nextpage = searchRes.getNextPage();
ResultPage lastpage = searchRes.getPreviousPage();
for (Hit hit:searchRes.getHits()){

String path1=hit.getPath();
String title1=hit.getTitle();
String excerpt1=hit.getExcerpt();

A: You can't. The ResultPage objects have information about your search results that you got from the QueryBuilder. You can use the information to build your own pagination and search result page(s).
As the SearchResult object contains only the results from the current page, you can use the ResultPage to easily get index and start of all the other pages that you could request from the QueryBuilder, based on the settings you used for your query, for example:
query.setStart(start);
query.setHitsPerPage(hitsPerPage);

But there is no connection to the frontend...


text:
Q: Can I use Jenkins on docker, integrate it to a private github repo and have jenkins use the host to run docker? I am a noob in programming in general, but more even so with jenkins. I have a fastapi app and postgres as db, both running on distinct docker containers and a repo at github with the code. Now I am trying to use jenkins to automate tests every time I push new code to github, but I am thinking what I want to do is not really practical or possible, which is: use Jenkins on docker, integrate it to a private github repo and have jenkins use the host to run docker. At first I was thinking in using a Docker-in-docker so that the jenkins instance would be in a container that could run docker, but I decide to follow the approach bellow because of this article.
So this is the jenkins istance:
docker run -d --name jenkins-docker --restart=on-failure
-v /var/run/docker.sock:/var/run/docker.sock -v jenkins_home:/var/jenkins_home
-p 8080:8080 -p 5000:5000 jenkins/jenkins:lts-jdk11

and it is already integrated with github, through the use a github app, so every time a push to the repo a job starts.
Now, this is the jenkinsfile:
pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
         sh 'docker compose -p testing -f docker/testing.yml up -d'
      }
    }
  }
}

And this is the error:
/var/jenkins_home/workspace/vlep-pipeline_main@tmp/durable-9098aec0/script.sh: 1: docker: not found

Shouldn't it find the command since it is running with -v /var/run/docker.sock:/var/run/docker.sock?
And, supposing the issue above is solved, would jenkins be able to build and run the images this way?

A: It turns out that mapping the sockets is not enough. I still need to have docker binary installed and in my case docker compose plugin as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to query groupby in following situation I have datatable in the following format
Id   LocationId  UserName  Startdate
1       10        xz        2017-02-21 09:05:20
2       10        xz        2017-02-21 09:15:20
3       10        xz        2017-02-21 09:25:20
4       10        xz        2017-02-21 09:35:20
5       11        xy        2017-02-21 09:45:20
6       11        xy        2017-02-21 09:55:20
7       11        xy        2017-02-21 10:05:20
8       11        xy        2017-02-21 10:15:20
9       10        xz        2017-02-21 10:15:20
10      10        xz        2017-02-21 10:25:20

I want to calculate starttime end time and differnce of time ,
and have show record as
Id      locationId  startdate     starttime         endtime    timespan
1            10      2017-02-21   09:05             09:35:20  0hr 30min0sec
2            11    2017-02-21     09:05             09:35:20  0hr 30min0sec
3            10    2017-02-21     10:15             10:25     0hr 10min 0sec

A: If you mean SQL, I hope the following can help you:
WITH TEST AS(
SELECT *,
CASE WHEN LAG(LocationId,1) OVER(ORDER BY ID) != LocationId
     OR LAG(LocationId,1) OVER(ORDER BY ID) IS NULL
     THEN ID
     ELSE 0 END FLAG
FROM [dbo].[DATATABLE]),`
`GroupData AS(
SELECT [LocationId],[UserName],[startdate],MAX(MI.FLAG) FLAG FROM TEST JOIN
(SELECT FLAG FROM TEST
WHERE FLAG != 0) MI ON TEST.ID >= MI.FLAG
GROUP BY [ID],[LocationId],[UserName],[startdate],TEST.FLAG)`
`SELECT LocationID,MIN([startdate]),MAX([startdate]) FROM GroupData
GROUP BY FLAG,LocationID


text:
Q: Are the probability of observing extreme values in hypothesis testing independent? Im trying to understand some definitions of the setup in two-sided hypothesis-testing. The probability of observing extreme values when doing two-tailed hypothesis-testing can be evaluated (if I'm not wrong) in the following integral (where $f_t$ refers to the $t$-distribution)
$P(t > |t_0|) \cup P(t < -|t_0|) = \int_{-\infty}^{-|t_0|} f_t(x)dx + \int_{|t_0|}^{\infty} f_t(x)dx - \int_{-|t_0|}^{|t_0|} f_t(x)dx$
In order to simplify to
$P(t > |t_0|) + P(t < -|t_0|) = \int_{-\infty}^{-|t_0|} f_t(x)dx + \int_{|t_0|}^{\infty} f_t(x)dx = $
$P(|t| > |t_0|) = 2\int_{|t_0|}^{\infty} f_t(x)dx$
i think I'd need some kind of confirmation that the areas $P(t > |t_0|)$ and $P(t < -|t_0|)$ are independent, but I'm unsure how to. I couldn't find any claims that the fractiles can go to negative numbers when freedom degrees $df \to \infty$, which would then contradict to the fact that they are independent for all confidence-levels.
I hope I make sense, any answers appreciated.

A: The events $t > |t_0|$ and $t < -|t_0|$ are not independent, but they are mutually exclusive since $-|t_0| \le |t_0|$ for all real $t_0$
Luckily this is what you want if you are going to add their probabilities together, since their intersection has probability $0$


text:
Q: Typesafe config with placeholder I tired to use placeholder as a key in typesafe config. I particularly use akka's reference.conf to provide some default values shipped with a library. Here it is:
my {
    properties{
        prp = test
    }
}

another {
    property {
        ${prp} {                              #doesn't work
            #default config for prp goes here
        }
    }
}

The thing is the my.properties.prp is going to be overriden in dependent modules and set to some project-specific value.
In particularly, it would be useful to provide the ability of customization actor name and then use project-specific one in a configuration.
Is there a way to do something like that?


text:
Q: I keep getting syntax error when using def on python NOTE: This is a very basic game i am working on as a practice project i get a syntax error when defining explosions ( near the end of the code list... also i am very new to programming so yeah... if anyone could help that would be great i am stuck because i am new so your help is more than appreciated
import pygame, aya, random
from pygame.locals import *
from threading import Timer

#set up pygame
pygame.init()
mainClock = pygame.time.Clock()

#set up the window
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WindowSurface = pygame.display.set_mode ( (WINDOW_WIDTH,
WINDOW_HEIGHT),0)
pygame.display.set_caption("Get Home!!")

#set up color constants
BLACK = (0,0,0)
BLUE = (0, 0, 255)

#set winning text
textFont = pygame.font.sysFont ("impact", 60)
text = textFont.render ("Welcome Home!", True, (193, 0, 0))

#set up the player and breadcrumbs
mapCounter = 0
NEW_GHOST = 20
GHOST_SIZE = 64
playerImage = pygame.image.load("playerimage.jpg")
playerImageTwo = pygame.image.load("playerimage.jpg")
ghostImage = pygame.image.load("ghost image.jpg")
ghostImageTwo = pygame.image.load("ghost image2.jpg")

player = pygame.Rect (300, 100,40, 40)
ghost = []
for i in range(20):
    ghost.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - GHOST_SIZE),
                             random.randint(0, WINDOW_HEIGHT - GHOST_SIZE),
                             GHOST_SIZE, GHOST_SIZE))
#movement variables
moveLeft = False
moveRight = False
moveDown = False

MOVE_SPEED = 6

#run the game loop
startGame = True
while startgame == True:
    #check for quit
    for event in pygame.event.get () :
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            #keyboard variables
             if event.key ++ K_LEFT:
                 moveRight = False
                 moveLeft = True
             if event.key ++ K_RIGHT:
                 moveRight = False
                 moveLeft = False
             if event.key ++ K_UP:
                 moveUp = True
                 moveDown = False

             if event.key ++ K_DOWN:
                 moveUp = False
                 moveDown = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                ays.exit()
            if event.key == K_LEFT:
                moveLeft = False
            if event.key == K_RIGHT:
                moveRight = False
            if event.key == K_UP:
                moveUP = False
            if event.key == K_DOWN:
                moveDown = False

    ghostCounter += 1
    if ghostcounter >= NEW_GHOST:
        #clear ghost array and add new ghost
        ghostCounter = 0
        ghost.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - GHOST_SIZE),
                                 random.randint(0, WINDOW_HEIGHT - GHOST_SIZE),
                                 GHOST_SIZE, GHOST_SIZE))
    #draw black background
        windowSurface.fill(BLACK)

        #move player
        if moveDown and play.bottom < WINDOW_HEIGHT:
            player.top += MOVE_SPEED
        if moveUp and play.top > 0:
            player.top -= MOVE_SPEED
        if moveleft and play.left > 0:
            player.left -= MOVE_SPEED
        if moveRight and play.right < WINDOW_HEIGHT:
            player.right += MOVE_SPEED

        windowSurface.blit(playerImage, player)
        for ghost in ghosts:
            windowSurface.blit(ghostImage, ghost)

        #check if player has intersected with ghost
        for ghost in ghosts[:]:

            if player.colliderect(ghost):
                windowSurface.blit(ghostImageTwo,ghost

                def explosion():
                     for ghost in ghosts:
                         if player.colliderect(ghost) and (moveLeft == False and
                              moveRight == False and moveUp == False and
                             moveDown == False):
                                 ghosts.remove(ghost)
                if player.colliderect(ghost) and (moveLeft == false and
            moveRight == False and moveUp == False and moveDown == False):
                     t = Timer(3, explosion)
                     t.start()

            if len(ghost == 0:
                ghostCounter = 0
                windowSurface.blit(text, (90, 104))
                startgame = False

            #draw the window
            pygame.display.update()
            mainClock.tick(40)

        while startgame == False
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

A: As @BurhanKhalid pointed out, you are missing ) at the end of line 111 (windowSurface.blit(ghostImageTwo,ghost), which is causing the error you noticed.
Additionally, you have numerous syntax errors.  You define variables in a different case than you use them (startGame being used as startgame, you forget to close several other )s (line 124, etc).  The list goes on.
Python is a forgiving language, but not that forgiving.  Find an editor and use it, learn how to debug your code, and stop being sloppy.  You will be unable to write code that works otherwise.


text:
Q: Getting location of the detected object in world coordinates Using python Segmentation-Models package, I have trained a model and now I can localize the object on the image. I would like to get the reference point into world coordinate system.

As it is seen one part of the object is kind of straight line. How can I get the middle point of this line and map it into world coordinates. I could maybe use Gabor filter or something like that but the object could be rotated, so the line is has not always same slope.

I am just looking for a tip to start off. Any idea to reference this object somehow and to map into World coordinate system ?


text:
Q: Trying to convert string into double C#?  double test = Convert.ToDouble("39,618840");

this gives me a format exception, and I have tried using the Cultureinfo.invariantculture setting, it does the same.

A: You have a trailing invisible character after the zero. Remove it.

Then, this works:
var culture = CultureInfo.GetCultureInfo("FR-fr");
var qty = Convert.ToDouble("39,618840", culture);

A: There are some invalid characters in that string.
Looking at the hex string we see the following:
"39,618840" --> 0x22, 0x33, 0x39, 0x2c, 0x36, 0x31, 0x38, 0x34, 0x30, 0xe2, 0x80, 0x8e, 0x22

And the characters actually look like:
"39,618840â€Ẑ"

A:         if (myString.Contains(","))
            myString = myString.Replace(",", "");
        double mydouble = Double.Parse(myString);

Using the above method will parse a string into a double, your issue is the comma. If you intended for the comma to act as the decimal point, the following amendment can be made:
        myString = myString.Replace(",", ".");


text:
Q: Error cannot convert 'int**' to 'int*' for argument '1' to 'int show(int*)' #include<stdio.h>

int show( int *m);
int disp(int *n);

int main()
{
    int i;
    int marks[]={55,65,70,75,78};
    for(i=0;i<4;i++)
    {
        disp(&marks[i]);
        return 0;
    }
}

int disp(int *n)
{
   show(&n);
   return 0;
}

int show(int *m)
{
   printf("%d\n", *m);
   return 0;
}

It is showing:
error[Error] cannot convert 'int**' to 'int*' for argument '1' to 'int show(int*)'

A: You are passing a pointer (int*) to disp(). Inside of disp() you pass a pointer to that pointer (int**) to show().
Just pass the pointer and not the address of it:
int disp(int *n){
    show(n);
    return 0;
}

A: YOu have to catch with double pointer in Show()function,
disp(&marks[i]) send the address of that and it be catch with pointer now u r trying to send address insted of data so u have to catch with double pointer like this
#include<stdio.h>
int show( int **m);
int disp(int *n);

int main()
{
int i;
int marks[]={55,65,70,75,78};
for(i=0;i<4;i++)
{
disp(&marks[i]);
return 0;
}
}
int disp(int *n)
{
show(&n);
return 0;
}
int show(int **m)
{
printf("%d\n", **m);
return 0;
}


text:
Q: Pandas .loc[] method only returns only DataType not Series despite calling single index TL;DR: .loc[] returns DataFrame type all the time. Even when specifying single index.
I've tried everything. This is driving me insane.
I can't seem to reproduce it anywhere else.
I've checked every Type of data that's beeing passed. Everything is as it should be. But no matter what I pass into the .loc[] it will return a DataFrame not series.
import numpy as np
import pandas as pd
import datetime

index_list = 'A B C D E F G H'.split()
df = pd.DataFrame(data=None,index=index_list)

k = 0
while k <= 2:
    now = datetime.datetime.now().strftime('%H:%M:%S')
    df.loc[:,now] = 1

    for i in index_list:
        print(df.loc[i])
        print(type(df.loc[i]))
    k += 1

The code above will run with 0 errors and return Series Type of data.
This is distilled code but it's exactly the same as the real one. Same flow, exaclty the same Type of data is beeing passed.

*

*'now' is set as a column name and all the new values for every index is now 1.

*Next the script iterates trough the index_list and prints the type.

The problem is that in the real script .loc will only return DataFrame type not Series. And I have no idea why. I even tried to manually enter the .loc index name to check if I'm not passing the wrong type of data. Still returned DataFrame.
I'm 100% out of ideas of what I could be doing wrong.
Maybe some of you have ideas?
EDIT
removed The original code.
I found that if I call
    print(df.loc[i].iloc[0])
It will return the Series data for the column.
print(type(df.loc[i].iloc[0]))

Will print:
20:48:48    1
Name: (A,), dtype: int64
<class 'pandas.core.series.Series'>

Why is the name (A,) a tuple?

A: TLDR: remove your extra brackets when building dfCoinMaster's index.
In the working code:
df = pd.DataFrame(data=None,index=index_list)

In the non-working code:
dfCoinMaster = pd.DataFrame(data=None,index=[current_coin_listings])

You're adding an extra level of list nesting, which you can see in your
Name: (A,), dtype: int64

line.  You can reproduce the same behaviour by adding the extra brackets to your test:
In [28]: df = pd.DataFrame(data=None, index=[index_list])

In [29]: df.loc[:, 'test'] = 10

In [30]: df
Out[30]:
   test
A    10
B    10
C    10
D    10
E    10
F    10
G    10
H    10

In [31]: df.loc['A']
Out[31]:
   test
A    10

In [32]: type(_)
Out[32]: pandas.core.frame.DataFrame

But:
In [33]: df.loc[('A',)]
Out[33]:
test    10
Name: (A,), dtype: int64

In [34]: type(_)
Out[34]: pandas.core.series.Series


text:
Q: C# Newtonsoft Json Converter Deserializing Generic to concrete on the fly I have a simple object that my API returns
{
"Code":0,
"Message":"String",
"Data":"Can Be Anything"
}

Data can be string or any other object like Person, Cat, List etc...
I mapped the response to c# putting Data as Object, lets say I called this object "Response"
I would like to know if is possible when I deserialize I inform the type that Data will be and make a converert to understand and cast Data to the type I´ve passed.
Would be something like
public static Response ToWrapper<T>(this string json)
{
    return JsonConvert.DeserializeObject<Response>(json, new Converter<T>());
}

In this example I would say that Data is a dummy class called Person with props string Name, string Email and int Age, so the response would be
string json = "
{
   "Code":1,
   "Message":"OK",
   "Data": {"Name": "Patrick", "Email": "aa@aaa.com", "Age" : 25}
}"

So in some point of my code I would
var ResponseWrapper = json.ToWrapper<Person>();

string personName = ResponseWrapper.Data.Name;
string personEmail = ResponseWrapper.Data.Email;
int personAge = ResponseWrapper.Data.Age; //<----- NO CAST NEEDED

The converter would transform object Data to Person Data!!!
The converter I tried some code with no sucess! I tried a lot of codes and the close that I could get was with this from here How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
public class PersonConverter<T> : JsonCreationConverter<T>
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        protected override T Create(Type objectType, JObject jObject)
        {
            T obj = Activator.CreateInstance<T>();

            if (FieldExists("Data", jObject))
            {
                return obj;
            }
            else
                return obj;
        }

        private bool FieldExists(string fieldName, JObject jObject)
        {
            return jObject[fieldName] != null;
        }
    }

    public abstract class JsonCreationConverter<T> : JsonConverter
    {
        /// <summary>
        /// Create an instance of objectType, based properties in the JSON object
        /// </summary>
        /// <param name="objectType">type of object expected</param>
        /// <param name="jObject">
        /// contents of JSON object that will be deserialized
        /// </param>
        /// <returns></returns>
        protected abstract T Create(Type objectType, JObject jObject);

        public override bool CanConvert(Type objectType)
        {
            return true; // typeof(T).IsAssignableFrom(objectType);
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override object ReadJson(JsonReader reader,
                                        Type objectType,
                                         object existingValue,
                                         JsonSerializer serializer)
        {
            // Load JObject from stream
            JObject jObject = JObject.Load(reader);

            // Create target object based on JObject
            T target = Create(objectType, jObject);

            // Populate the object properties
            serializer.Populate(jObject.CreateReader(), target);

            return target;
        }
    }

A: I think the best path forward is to use offload the deserialization of the Code and Message to a JObject, and then use JsonConvert to deserialize the data object.
https://dotnetfiddle.net/bP2Ew6
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        string json = @"
            {
               ""Code"":1,
               ""Message"":""OK"",
               ""Data"": {""Name"": ""Patrick"", ""Email"": ""aa@aaa.com"", ""Age"" : 25}
            }";

        Console.WriteLine(json);

        var response=json.ToWrapper<Person>();

        Console.WriteLine("Name: "+response.Data.Name);
        Console.WriteLine("Email: "+response.Data.Email);
        Console.WriteLine("Age: "+response.Data.Age);
    }
}

public class Person{
    public string Name {get;set;}
    public string Email {get;set;}
    public int Age {get;set;}
}

public class Response<T>{
    public int Code {get;set;}
    public string Message {get;set;}
    public T Data {get;set;}
}

public static class ResponseExtensions {
    public static Response<T> ToWrapper<T>(this string json){

        var o=JObject.Parse(json);
        var data=JsonConvert.DeserializeObject<T>(o["Data"].ToString());

        return new Response<T>{
            Code=(int)o["Code"],
            Message=(string)o["Message"],
            Data=data
        };
    }
}


text:
Q: Retrieve all notifications from firebase I have set up push notifications in my app using firebase. My question is how do I retrieve all the notifications I have previously sent so I can display them in an iOS app. Is there a firebase API for this? I have looked through the firebase documents and don't see any API for retrieving notifications.

A: There is no API for this, you can use Firebase Analytics however to log events when incoming messages are opened.


text:
Q: How to read a stream of bytes when you already know the structure of the bytes in C#? I am attempting to parse a .blend (Blender 3D Modelling Program Save File) in C#.
.blend follows a TLV pattern and using 3rd party tools I've managed to extract the majority of the data:
.blend File Format
Shown in the image; I have deserialized the .blend FileBlocks (The actual file data) and the Sdna Structs (The types of data present in a .blend file)
For example Block[1799] is sdna type sdnas[173] which means Block[1799] is a mesh.
Each block has a property "Body" which is a System.Byte[] and contains that FileBlocks data (In the case of a mesh, it's name and mesh properties, with pointers to other file blocks like it's vertices)
In this particular case I'm reading the body of a "Vec2s" sdna struct where the first 4 bytes are [31,5,246,25...]
I also know the Vec2 sdna has 2 properties (x and y) which are both of type short. So my intuition tells me that the first 4 bytes of my object are 2 shorts representing x and y. Reading these out returns (1311,9206)
All the fields of the sdna structs are of type uint, short etc. So how am I supposed to get the actual values like names, floats, vector2s, pointers etc?
As you can tell I really don't know what I'm doing.


text:
Q: Why this simple program on shared variable does not scale? (no lock) I'm new to concurrent programming. I implement a CPU intensive work and measure how much speedup I could gain. However, I cannot get any speedup as I increase #threads.
The program does the following task:

*

*There's a shared counter to count from 1 to 1000001.

*Each thread does the following until the counter reaches 1000001:

*

*increments the counter atomically, then

*run a loop for 10000 times.

There're 1000001*10000 = 10^10 operations in total to be perform, so I should be able to get good speedup as I increment #threads.
Here's how I implemented it:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdatomic.h>

pthread_t workers[8];
atomic_int counter; // a shared counter

void *runner(void *param);

int main(int argc, char *argv[]) {
  if(argc != 2) {
    printf("Usage: ./thread thread_num\n");
    return 1;
  }

  int NUM_THREADS = atoi(argv[1]);
  pthread_attr_t attr;

  counter = 1; // initialize shared counter
  pthread_attr_init(&attr);

  const clock_t begin_time = clock(); // begin timer
  for(int i=0;i<NUM_THREADS;i++)
    pthread_create(&workers[i], &attr, runner, NULL);

  for(int i=0;i<NUM_THREADS;i++)
    pthread_join(workers[i], NULL);

  const clock_t end_time = clock(); // end timer

  printf("Thread number = %d, execution time = %lf s\n", NUM_THREADS, (double)(end_time - begin_time)/CLOCKS_PER_SEC);

  return 0;
}

void *runner(void *param) {
  int temp = 0;

  while(temp < 1000001) {
    temp = atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
    for(int i=1;i<10000;i++)
      temp%i; // do some CPU intensive work
  }

  pthread_exit(0);
}

However, as I run my program, I cannot get better performance than sequential execution!!
gcc-4.9 -std=c11 -pthread -o my_program my_program.c
for i in 1 2 3 4 5 6 7 8; do \
        ./my_program $i; \
    done
Thread number = 1, execution time = 19.235998 s
Thread number = 2, execution time = 20.575237 s
Thread number = 3, execution time = 25.161116 s
Thread number = 4, execution time = 28.278671 s
Thread number = 5, execution time = 28.185605 s
Thread number = 6, execution time = 28.050380 s
Thread number = 7, execution time = 28.286925 s
Thread number = 8, execution time = 28.227132 s

I run the program on a 4-core machine.
Does anyone have suggestions to improve the program? Or any clue why I cannot get speedup?

A: The only work here that can be done in parallel is the loop:
for(int i=0;i<10000;i++)
      temp%i; // do some CPU intensive work

gcc, even with the minimal optimisation level, will not emit any code for the temp%i; void expression (disassemble it and see), so this essentially becomes an empty loop, which will execute very fast - the execution time in the case with multiple threads running on different cores will be dominated by the cacheline containing your atomic variable ping-ponging between the different cores.
You need to make this loop actually do a significant amount of work before you'll see a speed-up.


text:
Q: where query in firebase I am new in Firebase. I have problem while executing query:
new Firebase("https://blazing-fire-2739.firebaseio.com/users")
        .startAt($scope.user.email) //karank@ocodewire.com
        .endAt($scope.user.email)
        .once('value', function(snap) {
           console.log('accounts matching email address', snap.val())
        });

This shows me null.
In Firebase:
users
   -JxFNEu31LJ0Efy8PnX5
      email: karank@ocodewire.com
      firstname:karan
      lastname: sofat

Please Help

A: In the documentations for Query.startAt() and Query.endAt(), under 'Arguments', you will see that the first argument, value, is:

The value to start [or end] at. The argument type depends on which orderBy*() function was used in this query. Specify a value that matches the orderBy*() type. When used in combination with orderByKey(), the value must be a string.

The Querying Data section of the Web Guide says,

With Firebase database queries, we can selectively retrieve data based on various factors. To construct a query in your database, you start by specifying how you want your data to be ordered using one of the ordering functions: orderByChild(), orderByKey(), orderByValue(), or orderByPriority(). You can then combine these with five other methods to conduct complex queries: limitToFirst(), limitToLast(), startAt(), endAt(), and equalTo().

*

*If the user objects have a priority, and an orderBy is not specified for the Query, the query will sort by priorities and startAt/endAt by indices will work. You can use .setPriority() or .setWithPriority().

*If the user objects do not have a priority set, and the Query has no orderBy*(), snapshot.val() will be null.

For your query, if the user objects do not have priorities set, sorting by the email child will make startAt/endAt work, like so:
new Firebase("https://blazing-fire-2739.firebaseio.com/users")
    .orderByChild('email')
    .startAt($scope.user.email)
    .endAt($scope.user.email)
    .once('value', function(snap) {
       console.log('accounts matching email address', snap.val())
    });

Here is a working plnkr example of this query.

However, as Kato pointed out in the comments,

"As a general recommendation, orderByChild() supersedes priorities and should be preferred. Priorities will eventually be phased out in favor of child fields."

Since your goal is to locate a single specific user by her email address and since there should be only one user with a given email child value, you can,

*

*Order the Query object for /users by the "email" child key;

*Query for the user object for which the email child is equalTo(<email>).

For example:
var usersRef = new Firebase("https://blazing-fire-2739.firebaseio.com/users");
userRef.orderByChild("email").equalTo($scope.user.email).once("value", function(snapshot) {
  if(snapshot.exists()){
    console.log(snapshot.val());
  }
});

And here is a working plnkr example of this second query.
For more information, check out the documentation for Query.equalTo() and Query.orderByChild().
Important side-note: when ordering by a child key, if you know what the indices for your query will be, "you can define them via the .indexOn rule in your Security and Firebase Rules for better performance." Check out the Indexing Data documentation for more info.

It might be helpful to read over the Retrieving Data Guide.
To inspect your Firebase data in the browser and see objects' priorities, you can use Vulcan -- an awesome Google Chrome extension. This is what Vulcan looks like in the Chrome DevTools:

(source: firebase.com)

Hope this helps!

A: .startAt and endAt doesn't accept a string, it accept a number where to start/end at. So you would have to change to
new Firebase("https://blazing-fire-2739.firebaseio.com/users")
  .startAt(1)
  .endAt(50)
  .once('value', function(snap) {
    console.log('accounts matching email address', snap.val());
});

Or just leave out the endAt() altogether.


text:
Q: Passing Creds - New-PSSession I am trying to connect to exchange via the following
 $Cred = Get-StoredCredential "User"

 Function Connect-OnPremExchange {

    $ExOPSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://server101/PowerShell/ -Credential $Cred

    Import-PSSession $ExOPSession -AllowClobber
 }

However, I'm still getting prompted for a username/password. I don't want to hardcode it into the script and need to use the creds in my credential manager. How would I go about doing this?

A: Your credential manger may not be storing your credentials in a way that PowerShell can read. Have you tried storing your credentials in an encrypted xml file? You can at least test them this way.
Example:
Step 1 - outside of script
    Get-Credential | Export-Clixml -Path "C:\temp\creds.xml"

Step 2 - inside script
    $creds = import-clixml -path "c:\temp\creds.xml"


text:
Q: Why is Linux Java UI larger than Windows Java UI? I'm using both Fedora 17 and Windows 7 for my software development, and I'm using Eclipse.
One thing that I noticed with the Eclipse in Fedora 17 and in Windows 7 is the workspace.
Apparently the element spacing in Fedora is much larger than in Windows 7, resulting in smaller typing area for Eclipse in Fedora than in Windows 7.
I also noticed that the large element spacing happens not only in Eclipse, but also on any Java GUI program that I run on Fedora 17.
Does anybody know how to deal with this kind of issue?

A: Basically because they are different OSes, and they have different UI design directives. Moreover, while you have a common interface for java UI libraries like SWT, their implementations are different on each platform and use native libraries.


text:
Q: Can you find squares in this class? For a problem I am working over, I would like to prove that numbers of the following type are not squares
$p(l^4+6l^2m^2-3m^4)$
where $p,l,m$ are integers an $p$ prime. I have already found various necessary condition but could not conclude what I want, so I won't include them here in order not to lead you astray.
What I would like to get is to prove that class does not contain squares, for any $p$, or find a subclass of primes $p$ for which it is true.
If you want, just consider that in my case $p\equiv 1\;(3)$, and the first computations you carry out will suggest you to take $p\equiv -1\;(4)$ (which combined gives you $p\equiv 7\;(12)$) so you might want to assume this for the start.
I'm also looking hard trying to find some general problem it might be related to, I know there is, for example the theory of square free polynomials, but this is multivariate and I am looking for non squares, not square free. Well, it would suffice to show that $l^4+6l^2m^2-3m^4$ is square free (and not prime) to get something I could appreciate.
EDIT: Since some solutions were found I restate the problem: are there any solutions with $p\not\equiv 1\;(12)$ or, in particular $p\equiv 7\;(12)$?

A: Here's a bit more detail about my comment. We're searching for integer solutions to $y^{2} = p(l^{4} + 6l^{2}m^{2} - 3m^{4})$. Assume for simplicity that $\gcd(l,m) = 1$ and $p \geq 5$. If $p \equiv 2 \pmod{3}$ and $\gcd(l,3) = 1$, then the right hand side is $\equiv 2 \pmod{3}$, which is a contradiction, while if $l$ is a multiple of $3$, then $3 \nmid m$ and the right hand side is a multiple of a single power of $3$, again a contradiction. Thus, $p \equiv 1 \pmod{3}$.
On the other hand, if there's a solution then $p$ must divide $l^{4} + 6l^{2}m^{2} - 3m^{4} = (l^{2} + 3m^{2})^{2} - 12m^{4}$, and $p$ cannot divide $m$. This implies that $\left(\frac{l^{2} + 3m^{2}}{2m^{2}}\right)^{2} \equiv 3 \pmod{p}$ and this forces $p \equiv 1 \text{ or } 11 \pmod{12}$.
The equation $y^{2} = p(l^{4} + 6l^{2}m^{2} - 3m^{4})$ defines a homogeneous space for the elliptic curve $E : y^{2} = x^{3} + 6px^{2} - 3p^{2} x$ (for more detail, see Chapter III of Silverman and Tate's "Rational Points on Elliptic Curves"). This is the quadratic twist by $p$ of $E : y^{2} = x^{3} - 15x + 22$, which has CM by $\mathbb{Z}[\sqrt{-3}]$.
In some cases, one can use this to prove there are no solutions, even when there are local ones. For example if $p = 61$, the curve $y^{2} = p(l^{4} + 6l^{2}m^{2} - 3m^{4})$ has points in $\mathbb{Q}_{\ell}$ for all primes $\ell$, but represents an element of $Ш(E)[2] \cong (\mathbb{Z}/2\mathbb{Z})^{2}$. The elliptic curve has rank zero because $L(E,1) \approx 4.308 \ne 0$, and Coates and Wiles's theorem implies that since $E$ has CM and $L(E,1) \ne 0$, then $E$ has rank zero. This implies there are no solutions to the equation when $p = 61$. (If you're not familiar with elliptic curves, I highly recommend Silverman's book "Arithmetic of Elliptic Curves".)


text:
Q: How does eventbrite's organizer_get function work? I haven't been able to get eventbrite's /organizer_get API endpoint to give me back a successful result. I've included the app_key just like with all other api requests.
https://www.eventbrite.com/json/organizer_get?id=52803052&app_key=FOO
(replacing FOO with the actual app_key)
{"error": {"error_type": "Not Found", "error_message": "Invalid email and/or password."}}
(but it is valid: http://www.eventbrite.com/org/52803052?s=8134061)

A: Note, I work on the platform team at Eventbrite.

Currently, organizer_get only returns a result if the client making the request is the owner of the organizer record.  If you have an organizer account/id and make a request with that organizer id, it will work.
This is, obviously, quite unintuitive and not documented at all.  I'll look into lifting this restriction or at the very least documenting the behavior.


text:
Q: ASP.NET MVC Enitity framework calculate quotient How can I get quotient of 10 / 100 in asp.net mvc controller.I always get 0 return.Is there anyway to get the right answer 0.1.
decimal newpercent = percent / 100;

A: You were doing integer division so that's why you will get 0 in the output.
try this it will work.
class Program
{
    static void Main(string[] args)
    {
        double test =  10.0 / 100.0;
        Console.WriteLine(test);
    }
}


text:
Q: Using php to fill a  on webpage. Looking for a faster load time I added this :
<select>
    <option value=""></option>
    <?php include 'connect/config.php'; ?>
    <?php include 'connect/opendb.php'; ?>

    <?php
        $query = $db->query('SELECT type FROM card_type');
        $rows = $query->fetchAll();
        foreach($rows as $row) {
        print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
        }
    ?>
    <?php $db =null ?>
</select>

to my page and now it's takeing about 5 seconds longer to load the page.
Is there a more effecient way to fill a  option box from a database?

A: These are some issues in your code that affects performance:

*

*You should not call print for each row of your table. That penalizes
performance (if the server is not caching the output) as everytime
you call print you will be sending bytes across the net which is a
costly operation that is better be done once for one big chunk of
data rather than many times for small chunks of data , that is
the reason web servers will often cache all your PHP output prior to
sending it to the browser.

*You should pass by reference the array value when traversing the
array with foreach, to avoid the copy of a variable in each
iteration of the loop.

*Echo with commas, not periods. If
you use periods, PHP has to concatenate the string before it
outputs. If you use commas, it just outputs them in order with no
extra processing.

*You should use echo instead of print(). As a language construct rather than a
function, echo has a slight performance advantage over print().
So this is your code with points 2, 3 and 4 above corrected, thus assuming your web server is caching output:
<?php
      $query = $db->query('SELECT type FROM card_type');
      $rows = $query->fetchAll();
      foreach($rows as &$row) {
          echo '<option value="', $row['type'] ,'">' ,$row['type'] , '</option>';
      }
?>

and this is your code with point 1 and 2 above corrected, thus assuming your web server is not caching the output:
<?php
      $query = $db->query('SELECT type FROM card_type');
      $rows = $query->fetchAll();
      $out = '';
      foreach($rows as &$row) {
          $out .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
      }
      echo $out;
?>

A: Right now, you're putting the entire database table into a php array. If your table is large, this may cause the delay in response.
Try this instead, for the part where you fill the <select>:
<?php
    $query = $db->query('SELECT type FROM card_type');
    while($row = $query->fetch_array()) {
        print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
    }
?>

A: Try this one..
<select>
  <option value=""></option>
        <?php
    include 'connect/config.php';
    include 'connect/opendb.php';
    $query = $db->query('SELECT type FROM card_type');
    $rows = $query->fetchAll();
    $select_option = '';
    foreach($rows as $row) {
      $select_option .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
    }
    echo $select_option;
    unset($db);
    ?>
</select>


text:
Q: error: cast from 'char*' to 'int' loses precision [-fpermissive] on using reinterpret_cast (C++) I was trying out the different casting operators in C++.
In my understanding of reinterpret_cast, it converts don't type into a fundamentally different type.
But the following piece of code throws this error "cast from 'char*' to 'int' loses precision [-fpermissive]".
#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
    int i;
    char *p = "This is a string";
    i = reinterpret_cast<int>(p);
    cout << i;
    return 0;
}

What does the error mean?

A:
What does the error mean?

Most importantly, the message means that the program is ill-formed. A conversion from the type char * into the type int is not defined in the language (in this case).
The message also contains extra detail "loses precision". From that we can deduce that there can be more memory addresses representable by the pointer type than there are numbers representable by the integer type (in this particular implementation of the C++ language). This detail is the reason why the conversion isn't allowed. Reinterpret cast from pointer to integer is defined only in the case where the integer can represent all of the possible values of the pointer type. In language implementations where such integer type exists, there is a type alias for the type in the standard library: std::uintptr_t

char *p = "This is a string"

This implicit conversion is also ill-formed. A string literal, which is an array of const char is not implicitly convertible to char* in C++ (since C++11; prior to that such conversion was allowed but deprecated).

Can you please provide a snippet of code where reinterpret_cast is used correctly?

Correct uses of reinterpret_cast are extremely rare. There are many rules restrictions on its use, and in order to be able to write a correct program, you must understand all of the relevant rules and their subtleties.
I can show an example, but you must understand that making any change, no matter how subtle, has very high chance of producing an incorrect program. Here is the example, as promised:
struct standard_layout_struct {
    int first_member;
};

int main() {
    standard_layout_struct  instance { .first_member=42 };
    standard_layout_struct* pointer_to_instance = &instance;
    int* pointer_to_member = reinterpret_cast<int*>(pointer_to_instance);
    std::cout << *pointer_to_member;
}

A: To convert strings to values, a typecast wont work.
The input string needs to be parsed, the standard library can do this for you like this:
#include <iostream>
#include <string>

int main()
{
    std::string str{ "42" };
    auto value = std::stoi(str);
    std::cout << value;
    return 0;
}


text:
Q: How to handle suggested edits with no Edit Summary? This suggested edit appears to have no edit summary whatsoever - the proper HTML source is:
<span class="revision-comment" title="comment on this suggested edit">                                    </span>

So as you can see by viewing the characters it's the infamous "double space".
How should we deal with this? If the suggestion is good guess it's better to approve it, but should we comment on one of the suggestor's posts asking him nicely to behave? Or something else?
Edit: for those with more than 2K+ rep - this field is mandatory:

So avoiding it is kind of tricking the system.

A: If the edit is a good edit approve it, if it's a bad edit reject it.
Obviously if there's no comment you might be more inclined to reject if there's no obvious reason why the edit was made. For example if a link or image was changed unless you know why from the comment it could be just vandalism.
There's nothing that forces anyone to enter anything sensible in the summary, but not having a sensible comment is something that will probably affect your decision making (and quite rightly too).
I suppose it all comes down to the actual edit. Does it make sense even without the comment? If so accept it.

A: Suggested edits have a mandatory revision comment, in contrast to edits by 2k+ users who can omit the edit comment. If there is an empty comment there, the user intentionally circumvented that check, which isnt't exactly a point in their favor.
If the edit was a good and complete edit I would still approve it. If it's not obvious why something was changed I would just reject it, or if it is otherwise a bad edit. I personally would be likely more strict with borderline edits than usually, as I don't think evasion of the enforced revision comment is something we should encourage.


text:
Q: Dependent method types conflict with default arguments When playing with scala's dependent method types, I encountered a conflict with default method parameters:
abstract class X {
  type Y
  case class YY(y: Y)
}

object XX extends X {
  type Y = String
}

trait SomeTrait {
  def method(x: X)(y: x.YY, default: Int = 3): Unit
}

object SomeObject extends SomeTrait {
  def method(x: X)(y: x.YY, default: Int): Unit = {}

  method(XX)(XX.YY("abc")) // fails to compile
}

The message is:
[error]  found   : me.alexbool.XX.YY
[error]  required: x$1.YY
[error] Error occurred in an application involving default arguments.
[error]     method(XX)(XX.YY("abc")) // fails to compile

If I remove the argument with default value from method definition and implementation, the example compiles successfully. What am I doing wrong? Is it a bug?
P.S. I am using Scala 2.11.4

A: Half an hour of googling and I have an answer.
Yes, this is a bug. https://issues.scala-lang.org/browse/SI-7371


text:
Q: AutoCompleteTextView 1. add buttons, 2. create contact adapter, 3. spaces in AutoCompleteTextView i am trying to make a Compose New Message screen like the Messaging app built-in in Android 4.1

*

*i noticed that when a person selects a contact, there is a Button sort of thing in the AutoCompleteTextView inserted. HOW is that possible? Please help, as I do not even have any idea to give a starting code for it.
P.S. : I would LOVE to implement something like in the "Tags" entry in StackOverflow when creating a new post. I.E. the words (matched contacts) being replaced by buttons, with a little X on the right edge to remove them! :-)

*how do you create the adapter which loads so fast? one idea would be to cache a List of all contacts (names, phone no.s, phone no. types). any other ideas ?
(like, if we could query the content provider with an initial search string of say 2 characters, which would reduce the no. of autocomplete results tremenduously, thus reducing the time taken to load the adapter. but of course, this would require to set the adapter for the autocompletetextview as each character is typed. My doubt is that, can the ContactsContract be queried for search results starting with a few given letters, rather than just scanning the entire database from the starting using a Cursor?)

*the autocompletetextview does not recognize spaces, and just gives no results.
i have already read this  but could not implement it, does anyone have any working code for this?

A: You free to look at source code of built-in messaging app at Android GitHub. All you need is patience to read and understand code. And i remind you that not all of code are in public SDK so careful in usage.
1, The MultiAutoComplete with Contact tag RecipientEditTextView. And RecipientsEditor is class extended RecipientEditTextView they use it in app
Update : Here is layout of Compose screen. Line 37 is the autocompletetextview you want. And below is its layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">

<com.android.mms.ui.RecipientsEditor
    android:id="@+id/recipients_editor"
    android:hint="@string/to_hint"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textFilter"
    android:layout_weight="1"
    android:textColor="#000000"
/>

<ImageButton android:id="@+id/recipients_picker"
    android:src="@drawable/ic_launcher_contacts"
    android:layout_marginLeft="5dip"
    android:layout_width="50dip"
    android:layout_height="fill_parent"
    android:layout_weight="0"
    android:visibility="gone"
/>

A: I built TokenAutoComplete to solve this issue as there did not appear to be a simple way to do this. Here's a basic example solving points 1 and 3:
public class ContactsCompletionView extends TokenCompleteTextView {
    public ContactsCompletionView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected View getViewForObject(Object object) {
        Person p = (Person)object;

        LayoutInflater l = (LayoutInflater)getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        LinearLayout view = (LinearLayout)l.inflate(R.layout.contact_token, (ViewGroup)ContactsCompletionView.this.getParent(), false);
        ((TextView)view.findViewById(R.id.name)).setText(p.getName());

        return view;
    }

    @Override
    protected Object defaultObject(String completionText) {
        //Stupid simple example of guessing if we have an email or not
        int index = completionText.indexOf('@');
        if (index == -1) {
            return new Person(completionText, completionText.replace(" ", "") + "@example.com");
        } else {
            return new Person(completionText.substring(0, index), completionText);
        }
    }
}

Layout code for contact_token (you'll need to find your own x drawable)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/token_background">
    <TextView android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="14sp"
        android:text="Test Me"
        android:padding="2dp" />

    <ImageView
        android:layout_height="10dp"
        android:layout_width="10dp"
        android:src="@drawable/x"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="5dp" />
</LinearLayout>

Token backgound drawable
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#ffafafaf" />
    <corners
        android:topLeftRadius="5dp"
        android:bottomLeftRadius="5dp"
        android:topRightRadius="5dp"
        android:bottomRightRadius="5dp" />
</shape>

Person object code
public class Person implements Serializable {
    private String name;
    private String email;

    public Person(String n, String e) { name = n; email = e; }

    public String getName() { return name; }
    public String getEmail() { return email; }

    @Override
    public String toString() { return name; }
}

Sample activity
public class TokenActivity extends Activity {
    ContactsCompletionView completionView;
    Person[] people;
    ArrayAdapter<Person> adapter;

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

        people = new Person[]{
                new Person("Marshall Weir", "marshall@example.com"),
                new Person("Margaret Smith", "margaret@example.com"),
                new Person("Max Jordan", "max@example.com"),
                new Person("Meg Peterson", "meg@example.com"),
                new Person("Amanda Johnson", "amanda@example.com"),
                new Person("Terry Anderson", "terry@example.com")
        };

        adapter = new ArrayAdapter<Person>(this, android.R.layout.simple_list_item_1, people);

        completionView = (ContactsCompletionView)findViewById(R.id.searchView);
        completionView.setAdapter(adapter);
        completionView.setTokenClickStyle(TokenCompleteTextView.TokenClickStyle.Delete);
    }
}

Layout code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.tokenautocomplete.ContactsCompletionView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Here's what it looks like:


text:
Q: datetime.timedelta in google charts line chart I'm struggling to use a datetime.timedelta value as the y-axis in my line chart.
Here is what I have:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Day');
data.addColumn('timedelta', 'Time Average');

data.addRow(['Oct-20', {{ timedeltaObject }})]);

I am guessing the graph does not render due to the invalid type. I need to use time as a value for my y-axis, specifically only hours and minutes. Say on Oct-20, I spent 2 hours and 5 minutes doing X. It should plot that value on the graph.
I know it is possible to plot a datetime object but I specifically need a time value not a date value.

A: I managed to get it to work, instead of passing a timedelta object through Jinja, in my python code, I get the hours and minutes from the timedelta object and add them to a list [hours, minutes, seconds] with appropriate values.
Then in the googleVisualization I use data.addColumn('timeofday', 'Time Average'); and pass in my list.
Note: this approach only works for values under 24 hours.


text:
Q: Prestashop product upload with csv error I am trying to upload csv file of products in prestashop. Below are the errors that I am getting :

No Name (ID: 61,1,Orous Women's A Line Dress,Home,1399,IN Reduced Rate (4%),0,0,,,,,D2_Yellow,,,,,,,,,,,2,,,,,,"Fabric: Crepe A-line
  Exquisite style patterns Gentle machine wash, dry clean, do not
  bleach",,,,,,,,,1,,,,http://www.spademark.com/1154X1500/orous/D2_Yellow-_1.jpg,,,,New,,,,,,,,)
  cannot be saved

and

Property Product->name is empty

What am I doing wrong?

A: docs http://doc.prestashop.com/display/PS16/CSV+Import+Parameters
Please use this structure for successful upload:
"Enabled";"Name";"Categories";"Price";"Tax rule ID";"Buying price";"On sale";"Reference";"Weight";"Quantity";"Short desc.";"Long desc";"Images URL"
1;"Test";"1,2,3";130;1;75;0;"PROD-TEST";"0.500";10;"'Tis a short desc.";"This is a long description.";"http://www.myprestashop/images/product1.gif"


text:
Q: Connecting ESP32 to GameSir T4 pro controller via Bluetooth I try to connect a "GameSir T4 pro" controller (https://www.gamesir.hk/products/gamesir-t4-pro)
to ESP32 using Bluetooth.
Since i already have it and it supports Bluetooth connection, it was my first choice...
using several servos i want to build a tiny crane, controlled by the Gamesir controller.
does anyone here have some experience with programming the controller?
any known guide or repository to a similar project?
im searching for a few days now and no progress so far..
Much appreciation for all the helper and advisers!:)


text:
Q: ng-list in angularJS is not working as expected I have the following code in place
<input class="fill" name="keywords" ng-model="textbook.keywords"
type="text" ng-list=","  ng-required="true"></input>

where textbook.keywords is an array of strings.
I expect the above code to create a text box filled with comma separated values of the array, textbook.keywords. Instead, the textbox is empty. I made sure textbook.keywords has values in it by debugging.

A: First: Please check whether the library properly added in index.html.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Second: Please check whether the ng-app is added properly in HTML:
<html ng-app="listApp">

Third: Please check whether the ng-controller is added properly in HTML:
<body ng-controller="ListCtrl">

Forth: The app.js should should contain the following minimum code:
var app = angular.module('listApp', []);

app.controller('ListCtrl', function($scope) {
  $scope.textbook = {
    keywords: ['Text1', 'Text2', 'Text3']
  };
});

Fifth: Don't forget to add app.js in index.html
<script src="app.js"></script>

Final:  The working code snippet is added here:

var app = angular.module('listApp', []);

app.controller('ListCtrl', function($scope) {
  $scope.textbook = {
    keywords: ['Text1', 'Text2', 'Text3']
  };
});
<html ng-app="listApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
  <body ng-controller="ListCtrl">
    <input class="fill" name="keywords" ng-model="textbook.keywords"
type="text" ng-list=","  ng-required="true">
  </body>

</html>


text:
Q: Unit test async UI change in Swift I am trying to unit test a custom UIView, which changes the UI asynchronously. This is the code for the custom view:
import UIKit

class DemoView: UIView {

    var label: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    func setup() {
        label = UILabel(frame: .zero)
        self.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        self.centerXAnchor.constraint(equalTo: label.centerXAnchor).isActive = true
        self.centerYAnchor.constraint(equalTo: label.centerYAnchor).isActive = true
    }

    @MainActor
    func setLabel(_ text: String) {
        Task {
            try await Task.sleep(for: .milliseconds(100))
            label.text = text
        }
    }
}

I want to test, that after calling the setLabel(_:) function, the text on the label did change, therefore I wrote the following test:
@MainActor
func testExample() async throws {
    let demoView = DemoView(frame: .zero)
    XCTAssertEqual(demoView.label.text, nil)

    demoView.setLabel("New Text")
    let expectLabelChange = expectation(for: NSPredicate(block: { _, _ in
        demoView.label.text != nil
    }), evaluatedWith: demoView.label)
    await waitForExpectations(timeout: 5)

    XCTAssertEqual(demoView.label.text, "New Text")
}

But the exception runs into a timeout and the assert fails. When I set breakpoints, I can see that the Task inside setLabel(_:) is executed, but never reenters after sleeping, even though the timeout is long enough. Only after the waitForExpectations finishes, the task inside setLabel(_:) is continued, however this is too late for the assert to catch the changes.
How can I write the test, so that the Task in setLabel(_:) continues?
NOTE: The code is adjusted for demonstrating the issue. In the real app I call an API instead of sleeping.

A: You don't need async testing for this, and you shouldn't use it. setLabel is not async, and you're using an expectation! This test will pass (and I've rewritten a few minor things along the way):
@MainActor func testExample() {
    let demoView = DemoView(frame: .zero)
    XCTAssertEqual(demoView.label.text, nil)

    demoView.setLabel("New Text")
    let predicate = NSPredicate { _, _ in
        demoView.label.text != nil
    }
    let expectLabelChange = expectation(for: predicate, evaluatedWith: nil)
    wait(for: [expectLabelChange], timeout: 5)

    XCTAssertEqual(demoView.label.text, "New Text")
}

Even better, remove the @MainActor from your setLabel call; you can then remove it from the test function too.

Under what circumstances would async for the test be appropriate? If setLabel were async! Suppose you rewrite setLabel like this:
func setLabel(_ text: String) async throws {
    try await Task.sleep(for: .milliseconds(100))
    label.text = text
}

Now you need your tests to be async — and now you don't need an expectation! Look how simple everything becomes:
@MainActor
func testExample() async throws {
    let demoView = DemoView(frame: .zero)
    XCTAssertEqual(demoView.label.text, nil)

    try await demoView.setLabel("New Text")
    XCTAssertEqual(demoView.label.text, "New Text")
}


text:
Q: Deserialize nested json to string property I have a json file that contains nested json which I would like to deserialize into a string property upon configuration binding.
This is the configuration file:
{
  "Service": {
    "Id": "ccApiMicroservice",
    "Configuration": {
      "Option1": "value1",
      "Option1": "value2"
    }
  }
}

And this is the corresponding configuration class:
public class ServiceOptions
{
    public string Id { get; set; }

    [JsonConverter(typeof(JsonStringConverter))]
    public string Configuration { get; set; }
}

I have tried to use a custom json converter to convert the nested json to string, however the converter is ignored by the binding mechanism (have breakpoints in the converter's methods, but not one is hit), even though I have configured it in the ConfigureServices like so:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(
            options => options.SerializerSettings.Converters.Add(new JsonStringConverter()));

    services.Configure<ServiceOptions>(this.Configuration.GetSection("Service"));
}

What am I missing? Why is the converter ignored? Or is there another way how can I deserialize the nested json to string property?
Edit
The reason why I tried to use a custom JSON converter is that if I try to access the ServiceOptions instance anywhere in the application I get the following exception:
System.InvalidOperationException: 'Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.'

A: Here is an example of a possibly easier way for you to get and parse your json items:
JObject config = JObject.Parse(File.ReadAllText("config.json"));
string service_id = (string)config.SelectToken("Service").SelectToken("Id");
Console.WriteLine(service_id);


text:
Q: Php script running as scheduled task hangs - help! I've built a php script that runs from the command line. It opens a connection into a pop3 email account and downloads all the emails and writes them to a database, and deletes them once downloaded. I have this script being called from the commandline by a bat file. in turn I have created a scheduled task which invokes the bat file every 5 minutes. The thing is that I have set the time out to zero for the fact that at times there could be emails with large attachments and the script actually downloads the attachments and stores them as raw files offline and the no timeout is so that the script doesnt die out during downloading.
I've found that the program hangs sometimes and its a bit annoying at that - it always hangs are one point i.e. when negotiating the connection and getting connected to the mail server. And because the timeout is set to zero it seems to stay stuck up in taht position. And because of that the task is not run as its technically hung up.
I want that the program should not timeout when downloading emails - however at the points where it is negotiating a connection or trying to connect to the mailserver there should be a timeout only at that point itself and not the rest of the program execution.
How do I do this :(

A: The timeout value can be set using socket_set_timeout() if you're using sockets directly. You can have a look at this other question for details. If you're using a library, you should check its docs. But I would rather check if it really is the timeout issue. Log php errors into a file and you can browse them all. Set the max_execution_time to some acceptable value (like 10 minutes) and check the logs when it hangs again, if it's always the same line where it's failing.

A: I ran into this problem recently for those who are looking for an answer.  I had task scheduler calling the .php file directly.  It would hang and never return anything.
I found that running firefox.exe and sending the url as a parameter was the proper way to run a .php file through task manager.
firefox.exe "http://host/dir/file.php"


text:
Q: php how to output json encoded document in form without decoding I would try to show the steps leading to my issue.
I have obtained a document from my mongodb database as below:
$monrow= $collection->findOne(array('_id' => new MongoId($id))); //works fine

I then json-encoded $monrow as below (i need to use the json-encoded format)
$monrow= json_encode($monrow);   //works fine
var_dump($monrow);   //works fine
var_dump($monrow->properties);   //does not work where properties is an object.

Now my issue is, when I do the above I don't see the values of my form anymore (only see the json encoded monrow thanks to var_dump). I have to json_decode($monrow) to see my form again and by decoding, I get object(stdClass) in front of the values (which is not wanted).
The question is how do I work with json_encoded format directly in my form? or is it possible to ignore the object(stdClass) in the output of var_dump.
Here is my output for var_dump($monrow):
string(1804) "{"_id":{"$id":"52e0f51f64657635f1000000"},"campaign_id":1111111,"description":"test","interface_id":2121212121,"mp_commands":"","name":"full pack","properties":{"graph":{"cells":[{"type":"basic.Rect","position":{"x":220,"y":180},"size":{"width":80,"height":40},"angle":0,"script":"Begin","group":"MP Generic","id":"953fd4dc-6a82-4ee3-b03b-7e3eba4c6f6b","embeds":"","z":0,"attrs":{"rect":{"fill":"#1DCC64","stroke":"#3E7F0C","rx":10,"ry":10,"stroke-width":3},"text":{"text":"Begin","fill":"#000000"}}},{"type":"basic.Rect","position":{"x":220,"y":260},"size":{"width":80,"height":40},"angle":0,"script":"Send","group":"SMS","id":"5a158c43-f22a-4380-952f-173f309adfaf","embeds":"","z":1,"message":"Please call number 23094072304","attrs":{"rect":{"fill":"#FFC9C0","stroke":"#7F3124","stroke-width":3},"text":{"text":"Send","fill":"#000000"}}},{"type":"basic.Rect","position":{"x":220,"y":340},"size":{"width":80,"height":40},"angle":0,"script":"End","group":"MP Generic","id":"827f9533-22d1-4331-b21c-5d12c291631d","embeds":"","z":2,"attrs":{"rect":{"fill":"#FF3329","stroke":"#7F1A15","rx":10,"ry":10,"stroke-width":3},"text":{"text":"End","fill":"#000000"}}},{"type":"link","id":"4fadab02-ef30-4a1b-9581-4bc2f03b11c6","embeds":"","source":{"id":"953fd4dc-6a82-4ee3-b03b-7e3eba4c6f6b"},"target":{"id":"5a158c43-f22a-4380-952f-173f309adfaf"},"z":3,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"link","id":"694d255f-de4e-4a1b-b7e5-9634f6e529bd","embeds":"","source":{"id":"5a158c43-f22a-4380-952f-173f309adfaf"},"target":{"id":"827f9533-22d1-4331-b21c-5d12c291631d"},"z":4,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"}}}]}}}"

A: Try to use json_decode($monrow, true) to obtain assoc array insteed of stdClass object. But looks like you simply should not call json_encode directly after retreiving document from mongodb.


text:
Q: architecture suggestion if web server is removed in 3 tier app We have a java j2ee web application deployed in AWS in following manner.
Requests come to External load balancer which terminates SSL and forwards to web server which forwards to internal load balancer which forwards request to tomcat app server which is connected to database (rds).
Here are few questions:

*

*The purpose of apache web server is just that of reverse proxy. it does not have static content. all content including jss,css are served from tomcat. apache does have page speed module for minification
If static content is served from cloudfront , why even have apache web server ?
This will improve network hops and latency.

*If content is in fact served from cloud front, how can we get functionality of page speed to avoid issues such as caching ?

*If we remove apache, we open the front door of the application but is security really compromised?
Appreciate thoughts and suggestions from experts.

A: *

*You don't need both apache HTTP web server and internal load balancer. Generally, web servers are placed before app server for purposes like they will be able to handle networks connections efficiently, mitigating slow read attacks, caching static contents etc. since tomcat server HTTP connectors are optimized for above cases over a period of time you dont need HTTP server. Your External load balancer will do the load balancing so don't need the internal load balancer as well.

*Consider serving only the static content like css, js files through CDN.

*Your app is not exposed to internet directly, request comes through ELB. Apart from public ELB both app and RDS should be booted in private subnet(instances will have private ip). Make sure you configure security groups correctly to avoid security breach.


text:
Q: Generate variable type and initializer from macro I would like to generate a variable type and initializer from a (procedural) macro. Since macros consume and generate streams (and not trees) of tokens, morally, it should be possible to do something like:
extern crate quote;
use quote::quote;

#[proc_macro]
pub fn foo(tokens: TokenStream) -> TokenStream {
    TokenStream::from(quote! {
        : u8 = 42
    })
}

pub static FOO foo!();

But alas, this fails with
   |
28 | pub static FOO foo!();
   |                ^^^ expected one of `:`, `;`, or `=`

Now, of course I could turn this inside out and require writing something like
foo!(FOO)

which would expand to
pub static FOO: u8 = 42;

but the reason I would like to do things piecewise is to be able to use the same macro to generate types-and-initializers in different contexts (e.g. for local let bindings, not just statics).

A: You can't do what you are trying to do, not because : u8 = 42 is not correctly converted to a TokenStream, but simply because macro invocations (independently of their definition) cannot occur anywhere. In particular, they can only occur where a handle of the TokenStream would be reduced to a node, which is not the case in your example. This is because Rust has to parse the file once, before it knows anything about what macros do, exactly to find out all macros. In this first step, it only knows about its own syntax. It is smart enough to say "ok, this whole node of my AST is just this macro invocation" without knowing what the macro invocation will actually do, but it can't say "this macro invocation will feed me these tokens, so the next token I should read is ;" (which would be the case in your example), because it doesn't know what the macro does yet!
To convince yourself, image that the macro foo!() produces the token mod A {, and bar!() the token }. Then, the following example auto-destroys itself
foo!()

#[proc_macro]
fn foo(_: TokenStream) -> TokenStream { ... }
#[proc_macro]
fn bar(_: TokenStream) -> TokenStream { ... }

bar!()

Because if you expand correctly the macros, then they hide themselves by putting themselves into a module, which prevents the macros from being expanded, which makes them visible again, ... Even worse examples (where the issue occurs before visibility checks, at the parsing step) are easy to provide as soon as you allow what you are trying to do.


text:
Q: Confusion over hadoop job tracker api I'm try to collect some information from the job tracker. For starters I'd like to start with getting running jobs info such as job id or job name etc. But already stuck, here is what I've got (prints out job ids for currently running jobs):
public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "zk1.myhost,zk2.myhost,zk3.myhost");
        conf.set("hbase.zookeeper.property.clientPort", "2181");

        InetSocketAddress jobtracker = new InetSocketAddress("jobtracker.mapredhost.myhost", 8021);
        JobClient jobClient = new JobClient(jobtracker, conf);
        JobStatus[] jobs = jobClient.jobsToComplete();

        for (int i = 0; i < jobs.length; i++) {
            JobStatus js = jobs[i];
            if (js.getRunState() == JobStatus.RUNNING) {
                JobID jobId = js.getJobID();
                System.out.println(jobId);
            }
        }
    }

This above works as charm when trying to display job id, but now I want to display the job name as well. So I added this line after printing job id :
System.out.println(jobClient.getJob(jobId).getJobName());

I get this exception :
Exception in thread "main" java.lang.NullPointerException
    at org.apache.hadoop.mapred.JobClient$NetworkedJob.<init>(JobClient.java:226)
    at org.apache.hadoop.mapred.JobClient.getJob(JobClient.java:1080)
    at org.apache.test.JobTracker.main(JobTracker.java:28)

jobClient is not null. I know this because I tried with null check if statement, but this jobClient.getJob(jobId) is null. What am I doing wrong here?
According to the API I should be ok,
http://hadoop.apache.org/mapreduce/docs/r0.21.0/api/org/apache/hadoop/mapred/JobClient.html#getJob(org.apache.hadoop.mapred.JobID)
First get RunningJob from jobClient than once you have running job then get it's name http://hadoop.apache.org/mapreduce/docs/r0.21.0/api/org/apache/hadoop/mapred/RunningJob.html#getJobName()
Anyone did something like this before? I could use jsoup to obtain this information trough GET request but I think this is better way to get this information.
Question update here is my hadoop/hbase dependencies :
<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>0.23.1-mr1-cdh4.0.0b2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>0.23.1-mr1-cdh4.0.0b2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jetty</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase</artifactId>
            <version>0.92.1-cdh4b2-SNAPSHOT</version>
        </dependency>

Bounty update :
Here are my imports :
import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.JobStatus;

Here is the output of System.out.println(jobId) :
job_201207031810_1603

There is only one job currently running.

A: Have a look at the inner class NetworkedJob of JobClient.
(source: /home/user/hadoop/src/mapred/org/apache/hadoop/mapred/JobClient.java)
Its constructor tries to fetch the Configuration object from JobClient in line 225 but it's null since new JobClient(InetSocketAddress jobTrackAddr, Configuration conf) doesn't set it:
// Set the completion poll interval from the configuration.
      // Default is 5 seconds.
      Configuration conf = JobClient.this.getConf();
      this.completionPollIntervalMillis = conf.getInt(COMPLETION_POLL_INTERVAL_KEY,
          DEFAULT_COMPLETION_POLL_INTERVAL); //NPE occurs here!

As a workaround, set it manually after creating the JobClient object. This will solve your problem:
..
JobClient jobClient = new JobClient(jobtracker, conf);
jobClient.setConf(conf);
....

Sidenote:
I instantiated the Configuration object via:
Configuration conf = new Configuration();
conf.addResource(new Path("/path_to/core-site.xml"));
conf.addResource(new Path("/path_to/hdfs-site.xml"));


text:
Q: mongorestore issue : Cannot restore users with schema version 1 to a system with server version 2.5.4 or greater I have a mongodb production database running on mongo 2.4.8 and I would like to upgrade to 2.6.x.
The way we want to do that is first load the data to another server running 2.6.3 using mongorestore. However when running the mongorestorecommand we get the following error:
Cannot restore users with schema version 1 to a system with server version 2.5.4 or greater

I cannot find anything related to this issue and do't know what to do. In case it matters, the database itself was not created from scratch with mongo 2.4.x but with previous versions.
What ca I do ? Is there another way of doing this other than using mongorestore ?
Thank you in advance for your help ...

A: There are two approaches you can take to upgrade your user schema with the 2.4 mongodump.
1) Restore into MongoDB 2.4 and then upgrade to 2.6
This follows the normal 2.6 upgrade path. Instead of trying to mongorestore your 2.4 backup directly into 2.6, restore into a 2.4 instance and then upgrade to 2.6.
It is recommended that before upgrading, you run db.upgradeCheckAllDBs() via a 2.6 mongo shell. This checks for any potential compatibility issues due to changes in MongoDB 2.6. For example, 2.6 implements stronger enforcement of index field definitions and key length restrictions.
2) Restore into MongoDB 2.6 using 2.4 mongorestore and then upgrade the user schema
This approach requires the MongoDB 2.4 version of  mongorestore

*

*start up your MongoDB 2.6 mongod without auth enabled

*mongorestore your backup using a 2.4 version of mongorestore

*run the authSchemaUpgrade command in your 2.6 mongo shell:
db.adminCommand({authSchemaUpgrade: 1 });

*restart your 2.6 mongod with auth enabled

A: Three approaches that I can think of:

*

*First, if you are running as a replica set, I'd upgrade the members
one by one. If you're not running as a replica set that's bad,
MongoDB is really not designed for production usage with a single
instance. Details on converting to a replica set and in a rolling
upgrade here:
http://docs.mongodb.org/manual/release-notes/2.6-upgrade/ and here:
http://docs.mongodb.org/v2.6/tutorial/convert-standalone-to-replica-set/#

*Second, if you are running on a file system that supports snapshots
(like Amazon EBS or Linux LVM) you can snapshot the database files,
restore to a new file system and start up a new mongod process using
2.6. http://docs.mongodb.org/manual/tutorial/backup-with-filesystem-snapshots/

*Third, try exporting the data via mongoexport and loading it via
mongoimport. It's not the same as mongodump/mongorestore so it has
some limitations (it's not a full backup of the database, just a
text dump of the collections) but might help you get past this issue
with mongorestore: http://docs.mongodb.org/v2.6/core/import-export/


text:
Q: Encrpyting requests on client side Suppose I have a function which makes a POST request to an HTTP endpoint. I want to encrypt the payload on the client side. Suppose my web app has a function encrypt. I would like to implement the following workflow:
 encrpyt(data) {
     // do some encrpytion
     return encrypted;
 }

 onPost(data) {
     encrypted = encrpyt(data);
     post(encrypted, endpoint);
 }

My question is: would it be possible for the client to know the encrypt function. I know that over the network the encrpyted data can be seen, but it is possible that there is no way to know the code of the encrypt function on the client side. Also, for the app, data is not directly implemented by the client but rather it is data = data(client_input).
This question has a generalization which is: if I am using a framework like React/Angular, when I compile my app, are source code functions visible to the client?


text:
Q: Linking CSS to HTML enter image description herefirst time posting here. I restructured all the files on my website since I wanted to experiment with how to organize files, and I ran into a few issues. When I launch the site HTML appears but the CSS stylesheet doesn't seem to want to attach. I also think the js sheet is also not attaching properly but can't test it till css shows up. I double-checked spelling as well as placed the index.html on the root folder but still nothing I'll post the code below and hopefully someone can help me out. I appreciate you guys.

A: When you link a CSS or JS file to an HTML file, you need to provide a relative path from the HTML file to the CSS or JS file. In this case, it looks like index.html is already in the Root directory, so you shouldn't include that in the CSS file paths. The relative path to the css files (the path from the directory where index.html is to where the css file is) would be /Css/index.css, and the same for your javascript files (/Scripts/index.js).


text: Q: A tool for completing data on forms I work in a low-code system and create web forms. I would like to automate my work so that during the tests I do not have to enter all the data every time. Of course, there are plugins that allow you to complete the content such as first name, last name, etc. But I would also like check checboxes, radio buttons and it's nice if it clicks by itself, confirm, calculate or continue after some time. Is there a tool or another way that will make it possible?


text:
Q: Javascript Scrolling all the way up in Google Hangouts How can I scroll all the way up to the beginning of the chat in Google Hangouts?
I tried window.scrollTo(0,0); and some other things but they don't seem to work.

A: Try this:
$('html,body').scrollTop(0);


text:
Q: Using VIM to make acronyms? I have a file with lot of full names like ....
Light Machine Gun
Statistical Analysis System
etc

I want to capture the first character of every word in a line and want to make an acronym. For example Light Machine Gun would be LMG etc. I want to do it in VI editor record it as a macro and run it over the entire file.If anyone can help me that would be great? Thanks in advance.

A: Assuming one name per line and that the words are space separated, the following works:
%s/\(\w\)\w*\ */\1/g

If you also want to capitalize each letter, add an up-case flag (\u):
%s/\(\w\)\w* */\u\1/g

The "very magic" version (see :help /magic):
%s/\v(\w)\w*\s*/\u\1/g

A: Vim can define acronyms, called abbreviations, say you want
Light Machine Gun Statistical Analysis System -> LMGSAS

Just enter:
:ab LMGSAS Light Machine Gun Statistical Analysis System

And whenever you type LMGSAS it will substitute it for you.
Use :ab to list out all abbreviations, una xxxxx to unabbreviate something. And finally abc clears everything.
Edit: I misunderstood your question, if your trying to go, words -> abbreviations, then the regex s/\(\w\)\w*\s*/\1/g suggested by Thor works fine.


text:
Q: useEffect is causing a infinite loop when updating state? any idea how to refactor this code so I can be able to simply use firestore snapshot (Realtime data) to update the current state with those changeable data the SetState function simply update the current state with the new data but since i am calling is in useEffect it is triggering a loop can I use callback instead to work around this issue ?

  const [data, setData] = useState<any>(null);

  useEffect(() => {
    let colRef = collection(db, 'Weeks');
    const docRef = doc(colRef, context.focus as string);
    const unsub = onSnapshot(docRef, (doc) => {
      setData(doc.data());
      if (doc.data()) {
        context.SetState({ arr: doc.data()?.arr });
      }
      return () => unsub;
    });
  }, [data]);

A: remove data from the dependency and the infinate loop will end.
you do not use the data in the useEffect, remember to not useEffect on a state that you use its setter inside that useEffect or you will find yourself in such a situation its kinda like a recusive call without a condition to exit the loop.


text:
Q: Using awk to remove leading zeros gives octal results Background
I have a simple problem that has consumed the better part of a day for me.  In short, I am trying to remove leading zeroes from a string using awk.  Before everyone flags this as a duplicate, however, the question is NOT about how to remove leading zeroes (that is simply the end I am trying to achieve).  Additoinally, this is specifically about variables as they are read; I am well aware of format strings for output operations.
The Problem
My problem is thus: whenever I try to typecast a given variable to an integer, awk is reading the leading zeroes and treating the input number as an octal string.  I have some simple examples to demonstrate the behavior below:
$ echo "0012" | awk '{$1=$1+0}1'
10
$ echo "0012" | awk '{$1=+$1}1'
10
$ echo "0011" | awk '{print ($1 + 0)}'
9
$ echo "0000" | awk '{$1=$1+0}1'
0

Now, I have seen a number of solutions offering a variety of sed commands to 'pre-process' and remove the leading zeroes.  Unfortunately, a completely valid input for me is 0000, which string-based solutions collapse to an empty string.
The Question
In short, how to I force awk to treat a variable it reads as decimal, regardless of leading zeroes?
References
How to delete all characters but the last
strip leading zeros in awk program
Removing Leading Zeros within awk file
Update
Things I forgot to mention in the original post: I am trying to coalesce 0000 into a single 0.  Additionally, my ideal solution is awk-only due to the slim nature of my environment (is halfway between embedded Linux and a desktop OS).  The awk in question is provided by BusyBox 1.18.1 but everything else should be extremely close to a modern desktop version of Linux.

A: With what busybox calls awk, it seems to be possible to do the following:
$ printf '%s\n' 0000 0011 0012 |
  busybox awk '{print ($1".")+0}'
0
11
12

Posix requires that awk use the equivalent of strtod to convert data values to numbers, and all the awk implementations I could find do just that, except for busybox awk. (Busybox does not claim to be Posix compatible, of course, but it is sometimes aggressively incompatible, as in this case.) So {print $1 + 0} should work just fine, but it doesn't in the case of busybox awk, which will allow hexadecimal or octal integers in input data.
Appending a . to the number forces an integer to be treated as a floating point number, and has no effect on real floating point numbers, since strtod just stops when it encounters a character which can't be decoded as part of a number. Of course, it will also have no effect if the field is not entirely numeric, so if you expect fields like 0017a which you want to convert to 17a (or even 17), this solution is not for you.
As a side note, the precedence of string concatenation in awk is lower than the precedence of addition (and higher than comparison operators), so the parentheses are actually necessary; awk would parse print $1""+0 as print $1(""+0), which would append a 0 to the string value of $1. The GNU awk manual suggests that you should always parenthesize concatenation except in trivial expressions, and that strikes me as good advice.
Also, as I was trying to reverse engineer busybox awk's numeric conversion algorithm, I discovered that it treats 012e3 as the integer 10, rather than 12000. Both 12e3 and 012.e3 are converted to 12000, though. busybox is nothing if not idiosyncratic.

A: $ awk '{printf "%o\n", $1 + 0}' <<< 0012
12

A: builing upon answers from above, one can simplify

($1".")+0

… by pruning away the "0" ...

+($1 ".")

gawk -n '( $++NF = +($!_ ".") )^_'

0021 21
0020 20
0019 19
0018 18

0012 12
0011 11
0010 10
0000 0

012 12
011 11
010 10
000 0


text:
Q: The class may be defined in source code or a library that is not linked I have set MLSData on AppDelegate as Below
func getMLSBoards() {
    Service.shared.getMlsBoards(completion: { (mlsResponse) in

        if mlsResponse?.respCode == Code.success.rawValue {
            Defaults.shared.setMLSBoards((mlsResponse?.data?.mlsBoard)!, forKey: Default.mlsBoards)

            for mlsBoard in (mlsResponse?.data?.mlsBoard)! {
                if mlsBoard.id == 1 {
                    Defaults.shared.setInt(mlsBoard.id!, forKey: Constants.kProviderID)
                    Defaults.shared.setString(mlsBoard.title!, forKey: Constants.kProviderValue)
                    Defaults.shared.setMLSBoard(mlsBoard, forKey: Default.mlsBoard)
                }
            }

            NotificationCenter.default.post(name: NSNotification.Name.init(Notifications.nReceivedMetadata), object: nil)
        }
    })
}

and I want to get that MLSData on my iMessage APP
let mlsBoard = Defaults.shared.getMLSBoards(forKey: Default.mlsBoards)

but my app is crash with this message

Terminating app due to uncaught exception
  'NSInvalidUnarchiveOperationException', reason: '***
  -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Sarnail.MlsBoard) for key (NS.objects); the class may be
  defined in source code or a library that is not linked'

I had tried this also
NSKeyedArchiver.setClassName("Employee", forClass: Employee.self)
NSKeyedUnarchiver.setClass(Employee.self, for: "Employee")

but it not works for me
Some one please help me!


text:
Q: Spring Security ignore path for filter How can I configure Spring Security to use a custom filter for all requests except the ones I whitelist in the same level, e.g. "/login" skips my filter but every thing else "/**" goes through the filter.
As a workaround I could use different prefixes, "/secured/**" vs "/whitelist/**" or ignore the whitelisted ones in the filter, but that does not seem to be a clean solution.
I already tried setting up two configurations with @Order(1 and 2) but it didn't work.
@EnableWebSecurity
public class SpringSecurityConfig {

    @Configuration
    @Order(1)
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public static class JwsSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private StatelessAuthenticationFilter statelessAuthenticationFilter;

        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                    .ignoring()
                    .antMatchers("/login");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/**").authenticated()
                    .anyRequest().authenticated()
                    .and().addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return authenticationManager();
        }
    }
}


text:
Q: Elliptic curves over $\mathbb C$ have same endomorphism ring but not isomorphic I am finding elliptic curves over $\mathbb C$ have same endomorphism ring but not isomorphic.
Elliptic curves over $\mathbb C$ can be identified with $\mathbb C/\land$ for some lattice $\land$. And endomorphism ring is just a set of z s.t. z$\land \subseteq \land$.
But I am stuck here, the lattice in my mind is too simple, I guess I need to see more example. Can somebody help me?
What about lattice generated by {$1$,$\sqrt{2} i$} and {$i$,$\sqrt{2} $}? Is this an example?

A: Your two lattices actually give isomorphic elliptic curves, because one can be rotated into the other via multiplication by $i$.  So it doesn't work.
It is actually slightly tricky to find an example.  You need two lattices which are both closed under multiplication by some subring $R \subseteq \mathbb{C}$ strictly containing $\mathbb{Z}$, but are not multiples of each other.  Note that "multiple" can be any complex number.
One way to find an example is to fix a subring $R$, then look for sublattices within $R$ which are closed under multiplication by $R$.  By definition, these sublattices are the ideals of $R$.  So we are looking for 2 ideals of $R$ that are not multiples of each other by any complex number.
Now we enter the land of algebraic number theory: Two ideals of $R$ are complex multiples of each other iff they belong to the same ideal class.  So to find our example, we need a ring $R \subseteq \mathbb{C}$ with more than one ideal class.  This is equivalent to the statement that $R$ does not have unique factorization into elements.
The standard example is $R = \mathbb{Z}[\sqrt{-5}]$.  It has 2 ideal classes. There is the trivial ideal class represented by $R$ itself, and the non-trivial ideal class represented by the ideal $J = (2, 1 + \sqrt{-5})$.  So $R$ and $J$ represent two elliptic curves which are non-isomorphic, but both have endomorphism ring $R$.  For some more details on the ideal classes in $\mathbb{Z}[\sqrt{-5}]$, see here.


text:
Q: Segment fault when ifstream declared in a function, but not main, only when optimizations are turned on As the title says, I'm having an issue with ifstream. I was trying to read a text file and that would work fine when debugging but not in the release build. I was able to narrow it down to the example below.
The following code segfaults when it reaches the declaration of file in foo() if optimizations are turned on.
#include <iostream>
#include <fstream>

void foo (){
    std::cout << "I'm here 3" << std::endl;

    std::ifstream file;

    std::cout << "I'm here 4" << std::endl;
}

int main()
{
    std::cout << "I'm here 1" << std::endl;

    std::ifstream file;

    std::cout << "I'm here 2" << std::endl;

    foo();

    return 0;
}

Output:
I'm here 1
I'm here 2
I'm here 3

I'm compiling and linking with the following commands:
g++ -Wall -std=c++17 -O1 main.cpp -o main.exe

If I change the -O1 to O0 it doesn't segfault and runs to the end. I'm not really sure what the issue is.
My system is Windows 10 and I'm running g++.exe (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 8.1.0. Is this a compiler bug or am I just doing something stupid?

A: Since --static fixes it, this means your program picks up incorrect DLL versions.
Open your compiler's bin directory, and make a list of all DLLs in there.
Then:

*

*Search for those DLLs in C:\Windows (recursively). Delete any matching DLLs, they shouldn't be there.

*Make sure your compiler is the first thing in the PATH, or at least that any directories before it don't contain those DLLs (or better, all those directories except the compiler one).
This includes not having two different MinGW versions in the PATH (or you can just uninstall all but one).


text:
Q: error: static assertion failed: template argument must be a complete class or an unbounded array I'm deriving from a base class in which I try to define a type. That type is dependent on itself via a variant, so it would require to know the memory layout of the base class upon definition. However, I'm not prematurely defining the type? So I thought this would work but it doesnt (CompilerExplorer):
#include <variant>
#include <cstddef>
#include <array>

template <size_t V> struct container_base;
template <size_t V> struct container;

template <size_t V>
using val = std::variant<std::monostate, int, container_base<V>>;

template <size_t V>
struct container_base
{
    using iterator = typename std::array<val<V>, V>::iterator;
};

template <size_t V>
struct container : public container_base<V>
{
};

int main()
{
    container<100> A;
}

This yields:
In file included from /opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/variant:37,
                 from <source>:1:
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/type_traits: In instantiation of 'struct std::is_copy_constructible<container_base<100> >':
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/type_traits:3202:33:   required from 'constexpr const bool std::is_copy_constructible_v<container_base<100> >'
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/variant:329:5:   required from 'constexpr const bool std::__detail::__variant::_Traits<std::monostate, int, container_base<100> >::_S_copy_ctor'
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/variant:1334:11:   required from 'class std::variant<std::monostate, int, container_base<100> >'
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/array:109:55:   required from 'struct std::array<std::variant<std::monostate, int, container_base<100> >, 100>'
<source>:15:11:   required from 'struct container_base<100>'
<source>:19:8:   required from 'struct container<100>'
<source>:25:20:   required from here
/opt/compiler-explorer/gcc-trunk-20220726/include/c++/13.0.0/type_traits:1012:52: error: static assertion failed: template argument must be a complete class or an unbounded array
 1012 |       static_assert(std::__is_complete_or_unbounded(__type_identity<_Tp>{}),
      |

I understand it so that variant needs a complete type to work with when it's first used (which is in main! But the type is complete until then, so I don't know why it doesn't work. What can I do to fix this?