text:
Q: ¿Cómo convierto un un array de String en un arbol binario? JAVA Almacené un árbol binario en una cadena (utilizando un recorrido preorden) para guardarlo en un archivo de tal manera que la información cada nodo tiene un indicativo al inicio (en este caso un $ para nodo padre, un #para nodo hijo izquierdo y un % para cada hijo derecho). Cabe aclarar que cada nodo que no tenga el indicativo $, será unahoja. EL problema está cuando necesito recuperar esa información nuevamente y armar el árbol a partir de un nodo raíz.
Necesito una función que me reciba un vector de String y me devuelva el nodo raíz. Intenté esto, pero no funciona:
     public static Node receiveFromFile(String[] tmp, int i) {
    Node $root = new Node();
    Node izq = new Node();
    Node der = new Node();
    if (tmp.length == 0) {
        System.out.println("Archivo vacío");
    } else {

        if (tmp[i].substring(0, 0) == "$" && tmp[i + 1].substring(0, 0) == "#" && tmp[i].substring(0, 0) == "%") {
            $root.setData(tmp[i].substring(1, tmp[i].length()));
            i++;
            izq.setData(tmp[i].substring(1, tmp[i + 1].length()));
            $root.setIzq(izq);
            i++;
            der.setData(tmp[i].substring(1, tmp[i + 2].length()));
            $root.setDer(der);
            return $root;
        } else {

            $root.setData(tmp[i].substring(1, tmp[i].length()));
            i++;
            izq = receiveFromFile(tmp,i);
            $root.setIzq(izq);
            i++;
            der = receiveFromFile(tmp,i);
            $root.setIzq(izq);

        }

    }
    return $root;
}


text:
Q: How to determine how to restart an application I have an application that is topping at 190% cpu usage and I'd like to get it restarted.  The problem is, I'm not sure how I should restart it.  I've looked it /etc/init.d and I don't see anything there that's related to it.  Where else should I look?  in top it's called PNetTNetServer.
I can kill it, it's just once I kill it I need to make sure it starts back up again.

A: You can use ps or top to find the process id (pid).  Once you know the pid you can find out a lot of information about the process by looking in the /proc/ directory.  That directory will contain the command line used to invoke it (cmdline), the executable (exe), the working directory (cwd) and a lot of other information.  From there you should be able to figure out what is running.  Using ps you can find the parent process id and use the same process (no pun intended) to figure out the details of what called it and so on.

A: Top is the right place to start since it gives you an overview of all processes that are running. Additionally once you learn the pid (process id) you can give that to top for more insight into the process itself. top -p [the pid of the process].
Additionally as already mentioned you could issue something like ps aux | grep PNetTNetServer that will give you more detail on the process.
Stopping it can be done in various ways but specifically with the command kill but as you mention you should look for ways to shut down that process without issuing kill. On top of that, understanding what that process is doing is probably more important than shutting it down.

A: You may try to kill it with "kill -HUP " but I give no warranty, it will restart normally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I have only one controller for multiple portlets in liferay I Have 10 different sub-portlets in one portlet. In portlet.xml file my configuration is::
<portlet>
    <portlet-name>portletA</portlet-name>
    <display-name>portletA</display-name>
    <portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class>
    <init-param>
        <name>view-template</name>
        <value>/view-a.jsp</value>
    </init-param>
    <expiration-cache>0</expiration-cache>
    <supports>
        <mime-type>text/html</mime-type>
    </supports>
    <portlet-info>
        <title>A</title>
        <short-title>A</short-title>
        <keywords>A</keywords>
    </portlet-info>
    <security-role-ref>
        <role-name>administrator</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>guest</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>power-user</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>user</role-name>
    </security-role-ref>
</portlet>
<portlet>
    <portlet-name>PortletB</portlet-name>
    <display-name>PortletB</display-name>
    <portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class>
    <init-param>
        <name>view-template</name>
        <value>/view-b.jsp</value>
    </init-param>
    <expiration-cache>0</expiration-cache>
    <supports>
        <mime-type>text/html</mime-type>
    </supports>
    <portlet-info>
        <title>B</title>
        <short-title>B</short-title>
        <keywords>B</keywords>
    </portlet-info>
    <security-role-ref>
        <role-name>administrator</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>guest</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>power-user</role-name>
    </security-role-ref>
    <security-role-ref>
        <role-name>user</role-name>
    </security-role-ref>
</portlet>

Like this way. In my functionality, only view is different and in controller I have to write same code for all portlets.
In View's I have to write one action method this would be same for all the portlets. How can I achieve this. I was thinking to write the @doview but m not sure in this case what would be my portlet classes and how can I send different actions to same class.

A: Yes, you can use the same portlet class for different portlets in your plugin.
The portal container (Liferay) will create one instance of that class per portlet and initialize it with the proper configuration.
Your given snippet is the best example, why everything else would make no sense.


text:
Q: Multi-client RPC routing daemon I've spent a few weeks looking for a daemon that is capable of the following:

*

*Handling arbitrary numbers of clients from other network hosts.

*Allowing clients to register services under an identity.

*Allowing other clients to make RPC calls to these registered services, with reliable error handling (if client registered for that service detaches, the daemon should report an error to the caller, not leave it hanging).

*Allowing clients to register to receive events, which other clients can broadcast.

*The simpler, the better.

The closest thing I've found in the F/LOSS world is D-Bus, which meets all of these criteria except the first: it cannot reliably work with remote connections.  I have spent time looking into other options (ESB and MQ daemons -- spending the most time with 0MQ and RabbitMQ) and they all fall short in one way or another: ESBs tend to be extremely complicated with a high learning curve, and MQ daemons tend to provide half of the solution (routing) while leaving the other half (error recovery) extremely complicated, if not impossible.
I'm not looking for any fantastic routing capabilities beyond one client saying "I provide service 'foo'" and another client saying "I want to invoke method 'bar' on service 'foo'."
It seems like something like this would exist already, and I hesitate to roll my own.
The use case is that I will have many processes across many hosts.  Each host will have a governor process/service that will provide control of the lifetimes of these processes from a control panel.  The processes themselves will also be services, allowing for direct inquiry about status as well as reconfiguration requests from this panel.  The trick is that processes will come and go, and so static configuration of endpoints isn't something I really want to bother with; I would rather have each process be responsible for telling a daemon "I'm service so-and-so" and then let the daemon do the inter-client routing.
The only piece I'm really missing to develop this system is something that can route RPC requests between all of these processes.  Is there any such daemon out there, or is there some other model that would better fit my needs?


text:
Q: python NameError: global name is not defined I am getting this error NameError: global name 'control_queue' is not defined
 I have checked control_queue through out and I think I created it right.
Here is my code:
import multiprocessing
import time
from threading import Thread

class test_imports:#Test classes remove
      alive = {'import_1': True, 'import_2': True};

      def halt_listener(self, control_Queue, thread_Name, kill_command):
          while True:
              print ("Checking queue for kill")
              isAlive = control_queue.get()
              print ("isAlive", isAlive)
              if isAlive == kill_command:
                 print ("kill listener triggered")
                 self.alive[thread_Name] = False;
                 return

      def import_1(self, control_Queue, thread_Number):
          print ("Import_1 number %d started") % thread_Number
          halt = test_imports()
          t = Thread(target=halt.halt_listener, args=(control_Queue, 'import_1', 't1kill'))
          count = 0
          t.run()
          global alive
          run = test_imports.alive['import_1'];
          while run:
                print ("Thread type 1 number %d run count %d") % (thread_Number, count)
                count = count + 1
                print ("Test Import_1 ", run)
                run = self.alive['import_1'];
          print ("Killing thread type 1 number %d") % thread_Number

      def import_2(self, control_queue, thread_number):
          print ("Import_2 number %d started") % thread_number
          count = 1
          while True:
                alive = control_queue.get()
                count = count + 1
                if alive == 't2kill':
                   print ("Killing thread type 2 number %d") % thread_number
                   return
                else:
                     print ("Thread type 2 number %d run count %d") % (thread_number, count)

class worker_manager:
     def __init__(self):
        self.children = {}

     def generate(self, control_queue, threadName, runNum):
        i = test_imports()
        if threadName == 'one':
            print ("Starting import_1 number %d") % runNum
            p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
            self.children[threadName] = p
            p.start()
        elif threadName == 'two':
            print ("Starting import_2 number %d") % runNum
            p = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
            self.children[threadName] = p
            p.start()
        elif threadName == 'three':
            p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
            print ("Starting import_1 number %d") % runNum
            p2 = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
            print ("Starting import_2 number %d") % runNum
            self.children[threadName] = p
            self.children[threadName] = p2
            p.start()
            p2.start()

        else:
            print ("Not a valid choice choose one two or three")

     def terminate(self, threadName):
         self.children[threadName].join

if __name__ == '__main__':
    # Establish communication queues
    control = multiprocessing.Queue()
    manager = worker_manager()

    runNum = int(raw_input("Enter a number: "))
    threadNum = int(raw_input("Enter number of threads: "))
    threadName = raw_input("Enter number: ")
    thread_Count = 0

    print ("Starting threads")

    for i in range(threadNum):
        manager.generate(control, threadName, i)
        thread_Count = thread_Count + 1

    time.sleep(runNum)#let threads do their thing

    print ("Terminating threads")

    for i in range(thread_Count):
        control.put("t1kill")
        control.put("t2kill")

    manager.terminate(threadName)

I think it is saying I am not creating it properly, but I went over a few queue tutorials and as far as I can tell it is correct. Can anyone point out where I am messing up? Thanks guys and gals!

A: In function halt_listener your parameter is control_Queue but you are using the variable control_queue (capitalization problem).

A: control_queue is not the same thing as control_Queue in python. Case sensitivity matters.
You set the parameter to control_Queue but use control_queue later on.

A: It is wrong case. isAlive = control_queue.get() should be
isAlive = control_Queue.get().
There are a few places where this is happening


text:
Q: Node.js sequelize-auto fails to connect to mssql database socket hang up I am trying to use sequelize cli with the sequelize-auto package to read an existing MSSQL database schema in order to scaffold out the models for each table.
However I am stuck on a 'ConnectionError: Failed to connect to [myDatabse FQDN]:1433 - socket hang up'.
I have another MSSQL node.js app that connects fine using /mssql/msnodesqlv8, so I feel fairly sure this is not a problem with the database server end, and all connection parameters being passed are the same for both apps.
The sequelize documentation requires tedious (which is installed), and sequelize-auto github docs seem to suggest the msssql module as the connection method (also installed), so it's not particularly clear which is being used and whether I need to manually configure anything within them such as time-out settings.
Given the sequelize modules are intended to be the top level configuration where database details are entered and simply leverage whatever is needed from the mssql connector modules once 'mssql' is passed as the dialect option, I'm not really sure where to start.
Any help greatly appreciated!
Some additional info : Have successfully tested connection with sequelize module in conjunction with tedious using the snippet from the 'sequelize getting-started' documentation:
try {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

Then tried to repeat connection test just using tedious, this failed with the same socket-hang up error.  Also tried using the API code from the sequelize-auto documentation (had been using the CLI before) but still the same socket hang up error.

A: If your Nodejs is 6.3 or higher and SQL server 2005.
Your database config should be:
var dbConfig = {

            user: "xxxx",
            password: "xxxx",
            server: "xxxx",
            database: "xxxx",
            "options": {
                "encrypt": false
            }


text:
Q: I have 2 OS on 2 separate SSDs. How does my 3rd SSD get installed/setup? Basically, I have a dual boot Windows 10 and Pop! OS on two separate SSDs. I installed them independent of each other (remove the other when installing OS).
I want to install my third (or more, later) SSD as storage supplement that can store media mostly. I don't know if I'll install large apps, but very unlikely at this point (though I'd like to know if that would change my setup). This SSD should also be accessible from both OSs. I may want to encrypt it later, I mention this in case it changes the response.
How should I install this and set it up? Do I need to remove the Windows 10 SSD first and then install it or can I just stick the SSD in, choose ext4 and it's good to go on both systems?

A: You just need to add the disk physically and format it, using the most
suitable OS for the disk format that you choose.
Sharing disks between Windows and Linux is not without risk - question of formats:

*

*ext4 is excellent on Linux and not really supported on Windows

*NTFS is excellent on Windows but only supported on Linux in a limited way
as regarding user permissions

*FAT32 is well-supported on both, but is a very limited ancient format.

So take your pick.


text:
Q: Dumbledore's note for Harry or question about sequence of tenses When I was re-watching the well-known movie about the boy who lived I noticed that the tenses in the note from Dumbledore (spoiler, sorry ><) don't really correspond, or do they?
Here's what I mean:

It is time it was returned to you.

Shouldn't it be:

It is time it is returned to you.

Of course, Dumbledore is not dumb (or movie creators, if you will :P), and I'm just wrong, but could you explain why?


text:
Q: How to Combine the First and Last Name fields into a new field logstash? Sample Data :  {
"_id": "5c53d41e80e3f817d9cec5b0",
"index": 0,
"account_number": 1623,
"balance": 22526.72,
"firstname": "Desiree",
"lastname": "Mays",
"age": 46,
"gender": "female",
"address": "931 Metropolitan Avenue, Faxon, Oregon, 3046",
"employer": "IDEGO",
"email": "desireemays@idego.com",
"city": "Rodanthe",
"state": "Tennessee"
}
Conf File:
input {
file {
        type => "json"
        path=>'path'
}}filter { json {source => "message"} mutate {add_field => { "field_name" => "%{Firstname}" "%{lastname}"}}}output {
file {
    path =>'path'
}}

I Keep on getting the tag _jsonparsefailure

A: Could you confirm if the input file is a JSON type and if the path is set appropriately? otherwise i don't see an anomaly with add_field syntax here.


text:
Q: Map values from 2 separate cells in a row using Python I require some guidance on how to extract multi-values from one cell to match to another cell within the same row. This will be applied to the whole dataframe and a new dataframe is produced.
Source data
A sample of my source data is below. I can't change the source as it is available in such format and I will have it given to me on a monthly basis.
Data source:
data = {'C1': ['Alpha, Charlie, Bravo','Beta, Gamma','Foxtrot, Delta'],
        'C2': ['Alpha, San Francisco, US ; Charlie, New York, US ;
              Bravo, London, UK', 'Beta, Singapore, Singapore ;
              Gamma, Tokyo, Japan','[Foxtrot; Delta], Seoul, South Korea'],}

df = pd.DataFrame(data)

C1
C2

Alpha, Charlie, Bravo
Alpha, San Francisco, US ; Charlie, New York, US ; Bravo, London, UK

Beta, Gamma
Beta, Singapore, Singapore ; Gamma, Tokyo, Japan

Foxtrot, Delta
[Foxtrot; Delta], Seoul, South Korea

Intended outcome as new dataframe
I wish to achieve the following result in a new dataframe:
data2 = {'C1': ['Alpha', 'Charlie', 'Bravo','Beta', 'Gamma','Foxtrot', 'Delta'],
        'C2': ['Alpha, San Francisco, US', 'Charlie, New York, US',
               'Bravo, London, UK', 'Beta, Singapore, Singapore',
               'Gamma, Tokyo, Japan','[Foxtrot; Delta], Seoul, South Korea',
               '[Foxtrot; Delta], Seoul, South Korea'],}

new_df = pd.DataFrame(data2)

N1
N2

Alpha
Alpha, San Francisco, US

Charlie
Charlie, New York, US

Bravo
Bravo, London, UK

Beta
Beta, Singapore, Singapore

Gamma
Gamma, Tokyo, Japan

Foxtrot
[Foxtrot; Delta], Seoul, South Korea

Delta
[Foxtrot; Delta], Seoul, South Korea

My actual result (failed attempt)
I have tried nested for loops where C1 will be the outer loop and C3 will be the inner loop. I get the following results:
data3 = {'C1': ['Alpha', 'Alpha', 'Alpha', 'Charlie', 'Charlie',
                'Bravo','Beta', 'Beta', 'Gamma','Foxtrot', 'Delta'],
        'C2': ['Alpha, San Francisco, US', 'Alpha, New York, US', 'Alpha, London, UK',
               'Charlie, New York, US', 'Charlie, London, UK', 'Bravo, London, UK',
               'Beta, Singapore, Singapore', 'Beta, Tokyo, Japan',
               'Gamma, Tokyo, Japan',
               [Foxtrot; Delta], Seoul, South Korea,
               [Foxtrot; Delta], Seoul, South Korea],}

result_df = pd.DataFrame(data3)

N1
N2

Alpha
Alpha, San Francisco, US

Alpha
Charlie, New York, US

Alpha
Bravo, London, UK

Charlie
Charlie, New York, US

Charlie
Charlie, London, UK

Bravo
Bravo, London, UK

Beta
Beta, Singapore, Singapore

Beta
Gamma, Tokyo, Japan

Gamma
Gamma, Tokyo, Japan

Foxtrot
[Foxtrot; Delta], Seoul, South Korea

Delta
[Foxtrot; Delta], Seoul, South Korea

The script that I used
The script I have is below.
new_list = []
for idx, vals in enumerate(df['C1']):
    vals = vals.split('; ')
    locs = (df['C2'].values[idx]).split(' ; ')
    for val in vals:
        for loc in locs:
            new_list.append((idx, val, loc))

new_df = pd.DataFrame(data=new_list, columns=['N1', 'N2'])

Any help will really be much appreciated. Thanks.

A: There are two quirks in your data.

*

*The presence of a semi-colon inside the square bracket in some of the rows, which makes splitting my ; a bad idea

*Unequal number of values to map the two columns

Try this:
import re
def replace_semi_colon(s):
    return re.sub(r'\[(.*?)\]', lambda x: '[' + x.group(1).replace(';', ':') + ']', s)

# temporarily replace the semi-colon inside square brackets with colon
df['C2'] = df['C2'].apply(lambda x: replace_semi_colon(x))

# now split the values
df['C1'] = df['C1'].str.split(',')
df['C2'] = df['C2'].str.split(';')

# make the number of values in each column equal
df['C2'] = df.apply(lambda x : x['C2'] * len(x['C1']) if len(x['C1'])>len(x['C2']) else x['C2'] , axis =1)
df = df.explode(['C1','C2'])

# replace the ':' back  to  ';'
df['C2'] = df['C2'].apply(lambda x: x.replace(':',';'))

The result it gives:

    C1      C2
0   Alpha   Alpha, San Francisco, US
0   Charlie Charlie, New York, US
0   Bravo   Bravo, London, UK
1   Beta    Beta, Singapore, Singapore
1   Gamma   Gamma, Tokyo, Japan
2   Foxtrot [Foxtrot; Delta], Seoul, South Korea
2   Delta   [Foxtrot; Delta], Seoul, South Korea


text:
Q: PowerPC version of Go I just got access to a powerful Minski IBM machine (Linux) and intend on running some go scripts on it. I have gone through a lot of the versions of golang and tried installing and using them on the machine but none of them seem to work. Is there some special version of GO that I need that is specially designed to work on this powerful computer.
I have now tried installing about 4 or 5 different versions but still keep getting:
The program 'go' is currently not installed. To run 'go' please ask your administrator to install the package 'golang-go'

I was told that there is no need for an administrator to do a system wide install and to just install golang on my machine.
I have been using this step-by-step to install GO on this machine:
https://www.digitalocean.com/community/tutorials/how-to-install-go-1-6-on-ubuntu-14-04
I do not have root access on this machine, just FYI
EDIT:
Problem solved
Had to use:
curl -O storage.googleapis.com/golang/go1.8.3.linux-ppc64le.tar.gz

A: Go Downloads
PowerPC architecture: ppc64le (64-bit PowerPC little-endian). For example, for Go 1.8.3,
go1.8.3.linux-ppc64le.tar.gz: https://storage.googleapis.com/golang/go1.8.3.linux-ppc64le.tar.gz


text:
Q: Porting a simple algorithm to TPL with thread-local data I have a very simple algorithm that clusters blobs based on their x and y distance to each other. I ported the same to use Parallel.For with thread-local data but the results were incorrect. In other words, I may not have used synchronization properly to isolate each thread.
Simply cannot figure out why the results of the two implementations are different. Any thoughts would be appreciated.
I wanted to post fully compilable code but the objects used are too tightly integrated to the project context. Since the algorithm is very simeple, hopefully that will not get in the way.
Class level declerations:
/// <summary>
/// Contains the master blobl collection to be clustered.
/// </summary>
public List<Blob> Blobs { get; private set; }

/// <summary>
/// List of clusters to be computed.
/// </summary>
public List<Cluster> Clusters { get; private set; }

Linear Example (Works fine):
Cluster cluster = null;

for (int i = 0; i < this.Blobs.Count; i++)
{
    cluster = new Cluster();

    cluster.Id = i;

    if (this.Blobs [i].ClusterId == 0)
    {
        cluster.Blobs.Add(this.Blobs [i], i);

        for (int j = 0; j < this.Blobs.Count; j++)
        {
            if (this.Blobs [j].ClusterId == 0)
            {
                if (this.Blobs [i].Rectangle.IntersectsWith(this.Blobs [j].Rectangle))
                {
                    cluster.Blobs.Add(this.Blobs [j], i);
                }
                else if (this.Blobs [i].Rectangle.IsCloseTo(this.Blobs [j].Rectangle, distanceThreshold))
                {
                    cluster.Blobs.Add(this.Blobs [j], i);
                }
            }
        }
    }

    if (cluster.Blobs.Count > 2)
    {
        this.Clusters.Add(cluster);
    }
}

Parallel Port (Incorrect clusters):
System.Threading.Tasks.Parallel.For<Cluster>
(
    0,
    this.Blobs.Count,
    new ParallelOptions() { MaxDegreeOfParallelism = degreeOfParallelism },
    () => new Cluster(),
    (i, loop, cluster) =>
    {
        cluster.Id = i;

        if (this.Blobs [i].ClusterId == 0)
        {
            cluster.Blobs.Add(this.Blobs [i], i);

            for (int j = 0; j < this.Blobs.Count; j++)
            {
                if (this.Blobs [j].ClusterId == 0)
                {
                    if (this.Blobs [i].Rectangle.IntersectsWith(this.Blobs [j].Rectangle))
                    {
                        cluster.Blobs.Add(this.Blobs [j], i);
                    }
                    else if (this.Blobs [i].Rectangle.IsCloseTo(this.Blobs [j].Rectangle, distanceThreshold))
                    {
                        cluster.Blobs.Add(this.Blobs [j], i);
                    }
                }
            }
        }

        return (cluster);
    },
    (cluster) =>
    {
        lock (this.Clusters)
        {
            if (cluster.Blobs.Count > 2)
            {
                this.Clusters.Add(cluster);
            }
        }
    }
);

A: I think your problem is misunderstanding of that "thread-local data". According to the documentation of Parallel.For(), it's:

[…] some local state that may be shared amongst iterations that execute on the same thread.

What this means is that some iterations of your loop will share the same Cluster object, which will cause incorrect results for you. If the localInit and localFinally executed for each iteration, then they would be useless, because you could do exactly the same thing by moving their code to the beginning and end of the loop.
The reason why the delegates are there is that you can use them for optimization. With them, you don't have to access shared state (in your case this.Clusters) as often, which can improve performance.
If you don't need this optimization, don't use the two delegates and instead write the body of your loop like this:
i =>
{
    var cluster = new Cluster { Id = i };

    // rest of the loop here

    if (cluster.Blobs.Count > 2)
    {
        lock (this.Clusters)
        {
            this.Clusters.Add(cluster);
        }
    }
}

(In the above code, I also switched the lock with the if as an optimization.)
If you think the optimization using thread-local data would be useful for you (i.e. it would actually speed things up), you can use it. But the data in question would have to be a list of Clusters, not just a single Cluster. Something like:
() => new List<Cluster>(),
(i, loop, clusters) =>
{
    var cluster = new Cluster { Id = i };

    // rest of the loop here

    if (cluster.Blobs.Count > 2)
        clusters.Add(cluster);

    return clusters;
},
clusters =>
{
    lock (this.Clusters)
    {
        this.Clusters.AddRange(clusters);
    }
}


text:
Q: TypeScript reuse type generics How to extend generic type generics of type to function? Is it possible to reuse generics without copy paste?
type T<FormType extends 'edit' | 'create' = 'create', RecordType extends Record = Record> = {
   type: FormType,
   record: RecordType
}

const func = <FormType extends 'edit' | 'create' = 'create', RecordType extends Record = Record>(props: T<FormType, RecordType>) => ...

How to extend this <FormType extends 'edit' | 'create' = 'create', RecordType extends Record = Record> from type generics to function generics without copy paste?

A: Something you could do is break it down to one Base type:
type GenericType = {
  formType: 'edit' | 'create'
  recordType: Record
}

type Base = {
  formType: 'edit';
  recordType: Record
}

type T<B extends GenericType = Base> = {
   type: FormType,
   record: RecordType
}

const func = <B extends GenericType = Base>(props: T<B['formType'], B['record']>) => ...

I find this helps with verbosity a lot especially as I add a lot of generics in.


text:
Q: Invalid login throws: Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() > must implement interface When I successfully login there is no problem I just get logged in. But when I type the wrong credentials it gives me this error:

Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login()
  must implement interface Illuminate\Contracts\Auth\Authenticatable,
  null given, called in
  C:\xampp\htdocs\project\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
  on line 294

This is my login controller:
<?php

namespace App\Http\Controllers\Auth;

use \Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Account;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function login()
    {
     $user = Account::where('email', request()->email)

           ->where('password',bcrypt(request()->password))
              ->first();
     Auth::login($user);
     return redirect('/');
 }
}

My Account (user) model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;

class Account extends Authenticatable
{
    use Notifiable;
    use AuthenticableTrait;
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [

 'username', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

}
What am I doing wrong?


text:
Q: How to read and display my log file info in application using Log4net I am using Log4net in my application.
Can anyone please explain how to read my log files(Txt) and show it in my application.because my log files are there in another server.
What will be the config settings to read the log files from the server and show it in the C# application.
This is the code have used to write the logs.
    <log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
  <file value="\\10.8.8.87\temp\logs.log" />
  <appendToFile value="true" />
  <maximumFileSize value="10MB" />
  <maxSizeRollBackups value="50" />
  <rollingStyle value="Size" />
  <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%identity---- %date [%thread] %-5level %logger - %message%newline" />
  </layout>
</appender>
<root>
  <level value="DEBUG" />
  <appender-ref ref="RollingFile" />
</root>
</log4net>

A: Instead of an rollingfile appender you can better use for example a sql appender to log your exceptions to a database and from your application you can query the database. On this page you can find some config examples:
http://logging.apache.org/log4net/release/config-examples.html


text:
Q: jQuery: Using .find and .addClass I am using Ajax to input some data from a JSON file. Everything is inserting fine except that I want to add the class 'checked' to an certain amount 's depending on the rating set within the JSON file. (For example a film with a rating of 3 will add the class 'checked' to the first 3 span's).
Here is my JS so far just trying to get it to work with a rating of 3:
$(document).ready(function(){
   $.getJSON("data/films.json",function(films){
       $.each(films, function(index,film){
            var $newLi = $('

Title: '+film.title+'

Genre: '+film.genre+'

Director: '+film.director+'

Release Date: '+film.release+'

');

            if (film.rating===3){
                $(".star").find("star1").addClass("checked");
                $(".star").find("star2").addClass("checked");
                $(".star").find("star3").addClass("checked");
            }

            $(".showFilm").append($newLi);

            })

       });

       }) ;

The Problem
The checked class should change the colour of the span, however it is not doing so.

A: You have multiple issues:

*

*The problem is you are selecting all the stars on the page

*The stars you are actually trying to select have yet to add to the DOM

*Your class selectors are missing the .
So you can select the elements in the jQuery object and fix your selector
var $newLi = $('

Title: '+film.title+'

Genre: '+film.genre+'

Director: '+film.director+'

Release Date: '+film.release+'

');

if (film.rating===3){
  $newLi.find(".star .star1").addClass("checked");
  $newLi.find(".star .star2").addClass("checked");
  $newLi.find(".star .star3").addClass("checked");
}

$(".showFilm").append($newLi);

How can it be improved? Instead of selecting each one and also having multtiple ifs, add the class to the group based on count.
$newLi.find(".star .fa-star").slice(0, film.rating-1).addClass("checked");

A: film.rating is probably a string, which you're trying to compare to a number like so:
if (film.rating===3)

There are a couple solutions:

*

*Use double-equals, which will treat film.rating as a number for the comparison:
if (film.rating == 3)

*Explicitly convert film.rating to a number by prepending a plus sign:
if (+film.rating == 3)
Also note that you need a period before any classnames (such as star1).  Change:
$(".star").find("star1").addClass("checked");
$(".star").find("star2").addClass("checked");
$(".star").find("star3").addClass("checked");

… to:
$(".star").find(".star1").addClass("checked");
$(".star").find(".star2").addClass("checked");
$(".star").find(".star3").addClass("checked");

A: It's untested but should work
function makeFilmHTML (film) {
    var rating = film.rating;
    var html = [
    '
',
      '',
      '
',
        '
',
          '
Title: ',film.title,'
',
          '
Genre: ',film.genre,'
',
          '
Director: ',film.director,'
',
          '
Release Date: ',film.release,'
',
        '
',
      '
',
      '
',
        '',
        '',
        '',
        '',
        '',
      '
',
    '
'
  ].join('');

  html = $(html);
  html.find('.star > .fa-star:lt('+ rating +')').addClass('checked');

  return html;
}

$(document).ready(function(){
   $.getJSON("data/films.json",function(films){
       $.each(films, function(index,film){
            var $filmHTML = makeFilmHTML(film);

            $(".showFilm").append($filmHTML);
       });
   });
}) ;


text:
Q: Can I define 2 delegates with the same name but different parameters? I tried to define a delegate override between Int32 and IntPtr. Why are the following overloads illegal?
public delegate int EnumWindowsCallback (System.IntPtr hWnd, int lParam);

public delegate int EnumWindowsCallback (System.IntPtr hWnd, System.IntPtr lParam);

That looks pretty strange. They are both structs but are different and implement from different interfaces.
Come to think of it, I have never tried to overload a delegate before. Is it even legal, and if so, why?
UPDATE: After going through the answers and some more SO posts, I was baffled that delegates cannot be declared even with a varying number of parameters. I am still wondering why this cannot be resolved at runtime.

A: No, you cannot overload a delegate.  Overloads are selected when there is type information available to the compiler to pick one... but with a delegate, you are supplying the type information and the compiler would have no way to select from overloads.
If you want a family of similar delegate types, you can use generics.
public delegate int EnumWindowsCallback<LParamType>(System.IntPtr hWnd, LParamType lParam);

Now you can define overloaded p/invoke signatures which accept different delegate types EnumWindowsCallback<int>, EnumWindowsCallback<IntPtr>, etc.

A: All delegate types are limited to a single .Invoke method.  I'm not sure what exactly the Framework would do if one were to use CIL to define a type which derived from Delegate and included multiple overloads of Invoke, but an expectation that only one Invoke method will exist is pretty well backed into the Framework.
What one may be able to do, however, is define an interface which one can use in place of the delegate type.  For example, one could define something like:
interface IInvokableAsOptionalGeneric
{
  void Invoke();
  void Invoke<T>(T param);
}

in which case code which had a reference to something that implemented InvokableAsOptionalGeneric could either call it without parameters, or with a parameter of any type; the latter form could be used with value-type arguments without boxing (whereas an Action<Object> would have to box the parameter).  Note that for any interface of the above style, one could define a class with a static method similar to Delegate.Combine that would work with any objects that implement the interface; every such interface would need its own "combining" class, though much of the code would be boilerplate.

A: I don't like those people who always say "no, you can't". ;-)
Therefore my answer is: yes, you can!
Originally I wanted to call an overloaded non-generic method from a generic-method. The compiler didn't like that. Possible solutions are in SO 5666004 and SO 3905398, but I found them to be quite complicated.
After having read this and other posts and articles, I had some blurred idea in the back of my mind. Trial and error, and learing new functions got me to a working solution.
The others are right, you cannot overload normal delegates, because each delegate has it's individual type and uses static binding.
But you can use the abstract Delegate class and dynamic binding.
Here's the ready-to-compile-and-run solution (written in C++/CLI):
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Threading;

delegate void DelegateVI (int);
delegate void DelegateVB (bool);
delegate void DelegateVAUC (array<unsigned char>^);

ref class CWorker
{
public:
  void DoWork (int i_iValue)
  {
    Console::WriteLine ("int");
    Thread::Sleep (500);
  }

  void DoWork (bool i_bValue)
  {
    Console::WriteLine ("bool");
    Thread::Sleep (1000);
  }

  void DoWork (array<unsigned char>^ i_aucValue)
  {
    Console::WriteLine ("array<uc>");
    Thread::Sleep (2000);
  }
};

generic <class T>
ref class CData
{
public:
  CData (int i_iSize, CWorker^ i_oWorker)
  {
    m_aData = gcnew array<T>(i_iSize);
    if (T::typeid == int::typeid)
    {
      Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{int::typeid});
      m_delDoWork = Delegate::CreateDelegate (DelegateVI::typeid, i_oWorker, oMethod);
    }
    else if (T::typeid == bool::typeid)
    {
      Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{bool::typeid});
      m_delDoWork = Delegate::CreateDelegate (DelegateVB::typeid, i_oWorker, oMethod);
    }
    if (T::typeid == array<unsigned char>::typeid)
    {
      Reflection::MethodInfo^ oMethod = CWorker::typeid->GetMethod("DoWork", gcnew array<Type^>{array<unsigned char>::typeid});
      m_delDoWork = Delegate::CreateDelegate (DelegateVAUC::typeid, i_oWorker, oMethod);
    }
  }

  void DoWork (CWorker^ i_oWorker)
  {
    m_delDoWork->DynamicInvoke (gcnew array<Object^>{m_aData[0]});
    // i_oWorker->DoWork (m_aData[0]);  //--> fails with compiler error C2664: cannot convert argument...
  }

  array<T>^ m_aData;
  Delegate^ m_delDoWork;
};

int main()
{
  CWorker^ oWorker = gcnew CWorker;
  CData<bool>^ oData = gcnew CData<bool>(3, oWorker);
  oData->DoWork (oWorker);
}

A:
Come to think of it, I have never tried to overload a delegate before. Is it even legal, and if so, why?

No, it's not legal. You're currently declaring two types with the same fully-qualified name.
The only thing that looks a bit like overloading when it comes to types is if you declare two types which differ in the number of generic type parameters. For example, Action<T>, Action<T1, T2> etc. The rules for delegates are no different than the rules for other types here.
So either you need to declare one generic delegate (and use different type arguments), or use two different type names.


text:
Q: How do I make some images show under a div with text in it? I'm working on a website for someone and I can't get three images to show under a div with text in it for thinner displays. Here is the HTML:

Header Here

Paragraph Here

Here is the wide resolution CSS:
#mainText {
    width: 40vw;
    margin-left: 8vh;
    margin-right: 0;
    float:left;
}

#mainText h1 {
    color: #fff;
    padding: 3vh 0;
}

#mainText p {
    color: #ff00ff;
    line-height: 5vh;
}

#Images {
    float: right;
    margin-right: 20vw;
}

#Images img {
    width: 20vw;
}

And here is the CSS in my media tag for smaller screens:
@media only screen and (max-width: 800px) {
    #mainText p {
        width: 100%;
    }

    #Images {
        float: none;
    }
}

Any help would be greatly appreciated!

A: You need to set float: none on the #mainText div also

#mainText {
  width: 40vw;
  margin-left: 8vh;
  margin-right: 0;
  float: left;
}

#mainText h1 {
  color: #fff;
  padding: 3vh 0;
}

#mainText p {
  color: #ff00ff;
  line-height: 5vh;
}

#Images {
  float: right;
  margin-right: 20vw;
}

#Images img {
  width: 20vw;
}

@media only screen and (max-width: 800px) {
  #mainText p {
    width: 100%;
  }
  #Images, #mainText {
    float: none;
  }
}

Header Here

Paragraph Here

A: It's always good to provide a visual description of what you're trying to achieve but hopefully this will help...
If you'd like to 'stack' elements vertically you're likely looking to build a column and drop your elements inside.

  ... your code

with CSS defining that new class
.my-col {
  display: flex;
  flex-direction: column;
}


text:
Q: What does TF2 coaching involve? I've read the wiki articles on the subject of TF2 coaching, but none of them detail what is actually involved and what is expected of a coach. Can someone explain this in more detail please, as I feel that I might be interested.

A: When you sign up on the main menu, you will get an alert when someone has asked for a coach.(Usually very quickly)
If you accept, you will be automatically connected to the server they are on in a spectators type view. The chat and voice chat are both limited to the player you are coaching. Also, you have a few extra features, such as "Go Here","Attack This", or "Defend This" that you can place anywhere. There is a limit of 30 units you can travel from the student.
What's usually expected of a coach is general friendliness and patience. There's players are generally new to the game and want to learn. However, you will come upon trolls who just want to waste your time. There is no punishment for leaving a student early.
After your time with eh student is over, you will be put back into the main menu.
You can then "sign up" again and get another student to teach about the basics of the game.
My tip for coaching is to point then towards the easier classes to play, then advise them to try out different classes once they get used to the feel of the class. Make sure to tell them not to worry about deaths, it's part of the game.
Overall, just give tips, be nice, and lead the way in not being frustrated with this awesome game.


text:
Q: A faster alternative to Pandas `isin` function I have a very large data frame df that looks  like:
ID       Value1    Value2
1345      3.2      332
1355      2.2      32
2346      1.0      11
3456      8.9      322

And I have a list that contains a subset of IDs ID_list. I need to have a subset of df for the ID contained in ID_list.
Currently, I am using df_sub=df[df.ID.isin(ID_list)] to do it. But it takes a lot time. IDs contained in ID_list doesn't have any pattern, so it's not within certain range. (And I need to apply the same operation to many similar dataframes. I was wondering if there is any faster way to do this. Will it help a lot if make ID as the index?
Thanks!

A: EDIT 2: Here's a link to a more recent look into the performance of various pandas operations, though it doesn't seem to include merge and join to date.
https://github.com/mm-mansour/Fast-Pandas
EDIT 1: These benchmarks were for a quite old version of pandas and likely are not still relevant. See Mike's comment below on merge.
It depends on the size of your data but for large datasets DataFrame.join seems to be the way to go. This requires your DataFrame index to be your 'ID' and the Series or DataFrame you're joining against to have an index that is your 'ID_list'. The Series must also have a name to be used with join, which gets pulled in as a new field called name. You also need to specify an inner join to get something like isin because join defaults to a left join. query in syntax seems to have the same speed characteristics as isin for large datasets.
If you're working with small datasets, you get different behaviors and it actually becomes faster to use a list comprehension or apply against a dictionary than using isin.
Otherwise, you can try to get more speed with Cython.
# I'm ignoring that the index is defaulting to a sequential number. You
# would need to explicitly assign your IDs to the index here, e.g.:
# >>> l_series.index = ID_list
mil = range(1000000)
l = mil
l_series = pd.Series(l)

df = pd.DataFrame(l_series, columns=['ID'])

In [247]: %timeit df[df.index.isin(l)]
1 loops, best of 3: 1.12 s per loop

In [248]: %timeit df[df.index.isin(l_series)]
1 loops, best of 3: 549 ms per loop

# index vs column doesn't make a difference here
In [304]: %timeit df[df.ID.isin(l_series)]
1 loops, best of 3: 541 ms per loop

In [305]: %timeit df[df.index.isin(l_series)]
1 loops, best of 3: 529 ms per loop

# query 'in' syntax has the same performance as 'isin'
In [249]: %timeit df.query('index in @l')
1 loops, best of 3: 1.14 s per loop

In [250]: %timeit df.query('index in @l_series')
1 loops, best of 3: 564 ms per loop

# ID must be the index for DataFrame.join and l_series must have a name.
# join defaults to a left join so we need to specify inner for existence.
In [251]: %timeit df.join(l_series, how='inner')
10 loops, best of 3: 93.3 ms per loop

# Smaller datasets.
df = pd.DataFrame([1,2,3,4], columns=['ID'])
l = range(10000)
l_dict = dict(zip(l, l))
l_series = pd.Series(l)
l_series.name = 'ID_list'

In [363]: %timeit df.join(l_series, how='inner')
1000 loops, best of 3: 733 µs per loop

In [291]: %timeit df[df.ID.isin(l_dict)]
1000 loops, best of 3: 742 µs per loop

In [292]: %timeit df[df.ID.isin(l)]
1000 loops, best of 3: 771 µs per loop

In [294]: %timeit df[df.ID.isin(l_series)]
100 loops, best of 3: 2 ms per loop

# It's actually faster to use apply or a list comprehension for these small cases.
In [296]: %timeit df[[x in l_dict for x in df.ID]]
1000 loops, best of 3: 203 µs per loop

In [299]: %timeit df[df.ID.apply(lambda x: x in l_dict)]
1000 loops, best of 3: 297 µs per loop

A: Yes, isin is quite slow.
Instead it's faster to make ID an index then use use loc, like:
df.set_index('ID', inplace=True)
df.loc[list_of_indices]

Actually what brought me to this page was that I needed to create a label in my df based on index in another df: "if df_1's index matches df_2's index, label it a 1, otherwise NaN", which I accomplished like this:
df_2['label'] = 1  # Create a label column
df_1.join(df_2['label'])

Which is also very fast.


text:
Q: why ng-disabled does not work? This is my html tag:
<input class="editable-input" ng-model="ac.accesses.permision.alias" ng-disabled="true">

but input tag does not disable.

A: ng-disabled will work fine either if you missed out input type
Working Demo
  <input type="text" class="editable-input" ng-model="ac.accesses.permision.alias" ng-disabled="true">

Working Demo
   <input class="editable-input" ng-model="ac.accesses.permision.alias" ng-disabled="true">

A: You must insert type="text" in your input tag or delete the class.


text:
Q: Extracting emails from excel string So I found few forumlas online to do this but every single time I get this error:
http://postimg.org/image/4flyu43kp/

I have no idea whats going on. Im using office professional plus 2013. Here is an example how emails are placed in strings
name / something <info@example1.com>
<info@example2.com>

All emails are in brackets BTW < >
I need to extract just the email, can someone plz help me?

A: With a string in A1, in B1 enter:
=SUBSTITUTE((MID(A1,FIND("<",A1,1)+1,9999)),">","")

EDIT:
So if A1 contains:
something<bionicle.bill@lego.com>

B1 will display:
bionicle.bill@lego.com


text:
Q: How to apply border styles to NPOI workbook cells I didn't find this information anywhere on the internet so thought I would post here as I found the answer myself.
I want to create cells in a spreadsheet, using NPOI, that have borders, and it isn't obvious how to do that.

A: Here is some sample code for creating a cell style to apply to cells so that they have a border.
// create workbook, sheet and a row
HSSFWorkbook wb = new HSSFWorkbook();
var sheet = wb.CreateSheet("Sheet1");
var row = sheet.CreateRow(0);

// create font style
HSSFFont myFont = (HSSFFont)wb.CreateFont();
myFont.FontHeightInPoints = (short)11;
myFont.FontName = "Tahoma";

// create bordered cell style
HSSFCellStyle borderedCellStyle = (HSSFCellStyle)wb.CreateCellStyle();
borderedCellStyle.SetFont(myFont);
borderedCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
borderedCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
borderedCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
borderedCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;

// create standard cell style
HSSFCellStyle standardCellStyle = (HSSFCellStyle)wb.CreateCellStyle();
standardCellStyle.SetFont(myFont);

// create cell and apply bordered style
var cell = row.CreateCell(0);
cell.SetCellValue("I have a border");
cell.CellStyle = borderedCellStyle;

// create cell and apply standard stlye
var cell = row.CreateCell(1);
cell.SetCellValue("I have NO border");
cell.CellStyle = standardCellStyle;

A: For XSSF file. Take this approach
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Demo");
XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
defaultStyle.WrapText = true;
defaultStyle.Alignment = HorizontalAlignment.Left;
defaultStyle.VerticalAlignment = VerticalAlignment.Top;
defaultStyle.BorderBottom = BorderStyle.Thin;
defaultStyle.BorderTop = BorderStyle.Thin;
defaultStyle.BorderLeft = BorderStyle.Thin;
defaultStyle.BorderRight = BorderStyle.Thin;

sheet.SetColumnWidth(colIndex,   100);
sheet.SetDefaultColumnStyle(colIndex, defaultStyle);


text:
Q: How can I change the current tab when the corresponding title is selected in the TabLayout? I'm working on an Android app in Kotlin in which I have a ViewPager and I have a quite simple problem.
How can I change the current tab when the corresponding title is selected in the TabLayout?
Here is my code that configures the ViewPager:
private fun configureViewPager(view: View, context: Context) {
    //Get ViewPager from layout
    val viewPager: ViewPager = view.findViewById(R.id.view_pager)
    //Set Adapter PageAdapter and glue it together
    viewPager.adapter = PageAdapter(context, (activity as AppCompatActivity).supportFragmentManager)
    //Get TabLayout from layout
    val tabs: PagerSlidingTabStrip = view.findViewById(R.id.tabs)
    //Glue TabLayout and ViewPager together
    tabs.setViewPager(viewPager)
}

Note that I use this library to create my TabLayout, but I can revert to the Android TabLayout if the functionality I'm looking for is not supported in the former.
Thanks for your help!

A: Since the functionality I'm looking for is normally supported natively, I realized that the problem was indeed with my layout. Let me explain: I have an application that contains a navigation drawer. From it, I can access three fragments, one of which contains a TabLayout + ViewPager.
Here is the layout of the fragment that contains a TabLayout + ViewPager:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.tag.TagFragment">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintTop_toTopOf="parent"
        app:tabIndicatorColor="@color/white"
        app:tabSelectedTextColor="@color/white"/>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:paddingTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.constraintlayout.widget.ConstraintLayout>

Indeed, in this layout, the TabLayout was "covering" the ViewPager. By swapping the ViewPager and the TabLayout, I can now move from tab to tab from the TabLayout.
So here is my layout know:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.tag.TagFragment">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:paddingTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintTop_toTopOf="parent"
        app:tabIndicatorColor="@color/white"
        app:tabSelectedTextColor="@color/white"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Maybe there are other (better) ways to deal with that issue, please let me know!


text:
Q: Outputting data using system.out from array that's inside a loop JAVA The code below supposed to take users input:

*

*name

*bad/good teeth

Program should allow the user to enter that in an array and loop 10 times and then output that list in a table format ( the format you can find at the bottom of the code)
import java.util.Scanner;

public class pbclass;
{
    public static void main(String[] args)
    {
        pbclass objectt = new pbclass();
        objectt.dentistpractice();
    }

    public void dentistpractice()
    {
        Scanner scan = new Scanner(System.in);
        String[] patientFamName = new String[10];
        String[] patientFirstName = new String[10];
        String[] PatientGoodTeeth = new String[10];
        String[] PatientBadTeeth = new String[10];

        for(int i = 0; i < 10; ++i)
        {
            System.out.println("Enter surname name ");
            patientFamName[i] = scan.nextLine();
            if (patientFamName[i].equalsIgnoreCase("close") ==true)
            {
                break;
            }
            System.out.println("Enter first name ");
            patientFirstName[i] = scan.nextLine();
            System.out.println("Enter good teeth ");
            PatientGoodTeeth[i] = scan.nextLine();
            int numconverterForHomeTeam = Integer.parseInt(PatientGoodTeeth[i]);
            System.out.println("Enter score for away team: ");
            PatientBadTeeth[i] = scan.nextLine();
            int numconverterForAwayTeam = Integer.parseInt(PatientBadTeeth[i]);
    }
    System.out.println(patientFamName[0] + patientFirstName[0] + " ||||||| " +PatientGoodTeeth[0]  + PatientBadTeeth[0] );
    System.out.println(patientFamName[1] + patientFirstName[1] + " ||||||| " +PatientGoodTeeth[1]  + PatientBadTeeth[1] );

}

The problem I am facing is that I do not know how to output the data in a simple way. What if the array was 1000 variables or even longer?
Additionally, how do I prevent 'null' from showing on the display table. If the user types 'exit' the loop should stop and display the already inputted data excluding null values.

A: This will do what you want. But you can improve the print outcome part.
import java.util.ArrayList;
    import java.util.Scanner;

    public class pbclass {
        public static void main(String[] args) {
            pbclass objectt = new pbclass();
            objectt.dentistpractice();
        }

        Scanner scan = new Scanner(System.in);
         int array_length=10;
         int array_length2=0;
        String[] patientFamName = new String[array_length];
        String[] patientFirstName = new String[array_length];
        Integer[] PatientGoodTeeth = new Integer[array_length];
        Integer[] PatientBadTeeth = new Integer[array_length];

        public void dentistpractice() {

            for (int i = 0; i < array_length; ++i) {
                System.out.println("Enter surname name ");
                patientFamName[i] = scan.nextLine();
                if (patientFamName[i].equalsIgnoreCase("close")) {
                    break;
                }
                array_length2++;
                System.out.println("Enter first name ");
                patientFirstName[i] = scan.nextLine();
                System.out.println("Enter good teeth ");
                PatientGoodTeeth[i] = scan.nextInt();
                scan.nextLine();
                System.out.println("Enter score for away team: ");
                PatientBadTeeth[i] = scan.nextInt();
                scan.nextLine();
            }
            for(int i = 0; i < array_length2; ++i){
                System.out.println("-----------------------");
                System.out.println(" | " +patientFamName[i] + " | "+ patientFirstName[i] + " | " + PatientGoodTeeth[i] + " | "+ PatientBadTeeth[i]+ " | ");
            }
            System.out.println("-----------------------");

        }
    }


text:
Q: Proving a Simple Fact about Slopes of Lines The following problem is a detail from a proof I wrote recently -- a detail that I left unproven, and would like to prove.
Let there be three points $a$, $b$, and $c = \frac{a+b}{2}$, with $a<b$. We have a function $f$ such that $f(a) < f(c) \leq \frac{f(a)+f(b)}{2} < f(b)$.
So we can draw a line from $(a,f(a))$ to $(b,f(b))$ and the point $(c,f(c))$ will be on or below that line.
We then claim that the slope of the line from $(a,f(a))$ to $(c,f(c))$ is less than or equal to the slope of the line from $(c,f(c))$ to $(b,f(b))$. Why is this true? The intuition is clear to me, but I don't know how to formalize this.
A diagram  below for clarity.

No matter how we place $f(c)$, the point $(c,f(c))$ will clearly always be such that the slope from $(a,f(a))$ to $(c,f(c))$ is less than the slope from $(c,f(c))$ to $(b,f(b))$ -- if this were not the case, then the point $(c,f(c))$ would have to lie above the line from $(a,f(a))$ to $(b,f(b))$. But how do I prove this?

A: Edit: I misunderstood the question and will prove the actual question while leaving what I initially understood to be the question below.
We want to show that $(f(b) - f(c))/(b-c) \geq (f(c) - f(a))/(c-a)$.
Note: $(b-c) = (c-a) = (b-a)/2$
The inequality holds as $f(c)$ is at or below the midpoint of $f(b) - f(a)$

We also show that the slope of the line from $(a, f(a))$ to $(b, f(b))$ is larger  or equal to the slope from $(a, f(a))$ to $(c, f(c))$.
To do this we must show that $(f(b) - f(a))/(b-a) \geq (f(c) - f(a))/(c - a)$.
Note that $c = (a + b)/2$
Substituting into the right hand side of the inequality yields $(f(b) - f(a))/(b-a) \geq 2(f(c) - f(a))/(b - a)$
We know the inequality holds as $f(c) - f(a)$ is strictly less than $f(b) - f(a)$ and $f(c)$ is at or below the midpoint of $f(a)$ and $f(b)$ so $2(f(c)-f(a)) \leq (f(b) - f(a))$

A: Note that this property implies that for any $t=\dfrac m{2^n}$, we have $f(ta+(1-t)b)\le tf(a)+(1-t)f(b)$. If $f$ is continuous, this implies $f$ in convex, and it is easy to prove the slope of chords that have one extremity at $A$, $\dfrac{f(x)-f(a)}{x-a}\,$ is a non-decreasing function of $x$.
So your assertion results from the fact that $f$, ig continuous, is a convex function.


text:
Q: how do I use a loop and detect key press Python I want to make a stopwatch for rubik's cube timing, where you press enter to start it and press spacebar to make it stop. Here is what I have so far:
import time
running = True
second = 0
minute = 0
mill = 0 #by the way this is for millisecond
while running:
    print('Rubik\'s cube timer: press enter to start, space bar to stop')
    print('Note: you won\'t be able to see the time until you end it')
    input()
    if mill == 100:
        mill = 0
        second += 1
    if second == 60:
        second = 0
        minute += 1
    time.sleep(.01)
    mill += 1

But all that does is go on and on without ending. It is supposed to not stop the timer or show you ho w long it was until you press space bar. I don't know how to make it stop when space bar is pressed.

A: There are a couple of design considerations you might want to think about here. First, your method of time tracking is very imprecise and will result in losses to due how long python takes to perform operations. Instead of even using a loop you could just use two inputs and note the time difference between when the first one happened and when the second one happened. Second, you should also consider using a library to handle key input (as it is different for each platform). Here I use pynput:
from pynput import keyboard
import datetime
print('Rubik\'s cube timer: press enter to start, space bar to stop')
print('Note: you won\'t be able to see the time until you end it')
input()
start = datetime.datetime.now()
with keyboard.Listener(
    on_press=lambda key: key != keyboard.Key.space) as listener:
    listener.join()
end = datetime.datetime.now()
print(f"It took you {end - start} to finish")


text:
Q: SocketException:Connection Failed(OS Error: Too many open files, errno = 24) I have a list of dio requests, and get the result by Future.wait. Maybe the number of dio requests has exceeded the maximum that dart supports, so the app throw an error -SocketException:Connection Failed(OS Error: Too many open files, errno = 24). After i limit the length of dio requests in Future.wait, it works well. So i would like to know what is maximum limit of the list in Future.wait for Dart language
resultList.addAll(await Future.wait(
              _list.map((e) => e.requestInterface()));

A: You should not try limit the amount of connections by limiting the amount of futures you are spawning and waiting on. Instead, you it is better to tell Dio (or more precise, the HttpClient instance inside Dio) the maximum amount of connections you want to the same host.
So first, make sure you are reusing the same instance of Dio at least for all requests to the same host. We can then use this property to tell HttpClient how many simultaneous requests it should try to handle to the same host. If the amount of requests are more than the limit, it will automatically handle this as a queue.
https://api.dart.dev/stable/2.17.5/dart-io/HttpClient/maxConnectionsPerHost.html
The default of this property are null which disables any maximum which is a problem in cases like your where you are doing a lot of requests. But also, performance would often there are a limit where it no longer gives better performance trying to do more requests simultaneous.
You need to play with the property to find where a good value are for you. But I would guess it is between 5 and 15 depending on the application of course.
To provide this property to Dio we can do the following:
  final dio = Dio();
  dio.httpClientAdapter = DefaultHttpClientAdapter()
    ..onHttpClientCreate =
        (httpClient) => httpClient..maxConnectionsPerHost = 20;

(And to answer the actual question, the error message comes from the operating system where your application are running on. It is hard to say what the actual limit are since it is possible to set specific limitation on the specific applications to ensure a single application are not making too much noise on the system.).


text:
Q: Resources to build software engineering skills Apologies if this question is too open-ended for the site, but it just seemed the best place to ask it.
I am a self-taught programmer with little maths in his educational background and who has, through the course of a ten-year career moved slowly from front-end web scripting and web development to middle and data-tier software engineering. As a result there are areas of my knowledge and experience that are somewhat lacking.
After a recent review with my manager, it was indicated to me that overcoming these gaps was all that was standing between me and a promotion to a senior engineer role. However in order to get that, I was going to have to find for myself a structured approach to learning and demonstrate that I'd taken on board what I needed to know.
Personally I'd identify my areas of weakness as follows. Be aware that the problem in a lot of cases is not that I don't understand, technically, how these things work but that I don't see where it is or is not appropriate to apply them. For example I know what an Interface is and, technically, what it does, but I have a hard time differentiating when it's appropriate to use an Interface over, say, a group of related OO classes which inherit from a base class. So it's kind of more ignorance of good software design than it is technical ignorance - I do have trouble appreciating, digesting and working on things like loosely coupled systems.

*

*Interfaces

*Delegates

*Design Patterns

*Network architecture & protocols

Also I've never done some of the low-level stuff like compilers and suchlike. I wonder sometimes if it'd make a big difference to my ability to write code which is not only effective but well optimised if I had a better knowledge of this sort of material.
Sometimes the worry that I can't identify weaknesses in my skill set because I don't know how to ask the right questions knaws away at me. So, in the hope that I've framed the question properly, I'd like your suggestions on:

*

*From the sound of what I'm currently lacking are there any other topics I should think about looking at?

*Where are some good resources for learning this material?

*Are there any structured, self-taught courses I can work through that are relevant? I don't, sadly, have time to take a formal qualification.

Cheers,
Matt

A: I was a self taught coder not so long ago so I can relate to your position.
Since then I've shipped 10 Millions LOC applications, so I had to develop discernment.
3 things helps me to get software engineering : books, code and people.
First of all, good engineering is about beauty, the beauty of an elegant design, of an efficient mecanism. You need to develop that sense for beauty and to do that you need to see it and discuss it.
Books like SICP, Refactoring, Head First Design Patterns and Beautiful Code are all about beautiful/better code. Most of the time they are not about a language per se (or about exotic languages). Code complete is also interesting but somehow more low level.
Online reading of code is also a good way to educate your taste. I have no example in mind but this is a common question,  you should easily find some ideas. Also, building an ambitious application (a game, 3d modeler, web server, database) is a good practive : you're likely to redo it 2 or 3 times to have a better architecture.
People is also very important. If you find a/a few passionate software architect(s) to discuss with, you will be able to confront your view on what is beauty.  I am still digesting some discussion I had with my manager a few years ago.
This "enlighment" is an ongoing process, so don't get discouraged and just move forward. One day, you'll see ugly code with an obvious alternative implementation, one you could discuss and compare objectively as better than the original.

A: Having a pet project lying around that you can continuously refactor goes a long ways in self-education.
In all honesty, I'd take a look at some of the open courseware put out by MIT or Caltech and the like. Pick a topic that you feel would benefit you, and throw a lesson on. Try and understand the concepts as best as you can. As you continue to code and refactor your pet project, you'll naturally start adding things you're learning.
You mentioned never having touched compilers -- give that course a shot and see where you stand. With dozens of full CIS programs out there on YouTube, its easy to find an instructor you enjoy learning from. I'll throw out Intro to Algorithms as taught by Leiserson and Demaine as a launching point:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/
You mention "I don't, sadly, have time to take a formal qualification." Formal or not, it will take a good investment of time to make this happen. Choose the best route for you and stick with it. Make sure you're putting your learnings into practice to solidify and grow your comprehension.


text:
Q: Client-Server Integration Test with Maven I have a simple game which consists of two projects: Client and server. Now I want to test if they interact correctly.
Setup is: One Maven-parent project, and server/client/integetion-test as child-modules.
I tried to follow this guide http://docs.codehaus.org/display/MAVENUSER/Maven+and+Integration+Testing, which is integration-testin using the maven-failsafe-plugin. Alas it is only describing how to start the jetty-server, which is available as a plugin.
How and where do I start my own client and server in this configuration (or is there a better one) for testing? I wanted to do something like this: First I want client and server to be started before the test. In the jUnittest I want to have a Socket and a Serversocket, one connected to the server and one to the client. Then I want to pipe the client/server-interaction through this setup and verify it in between, or send specific messages to them individually, verifying the answer.
Is something like that possible, or is there a better way?

A: I have done similar stuff earlier but sadly i do not have the code available now. But it was something like below. Here in pre-integration-test start your server using ant exec task and in post-integration-test stop your server.
<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <id>start-server</id>
            <phase>pre-integration-test</phase>
            <configuration>
                <target>
                    <exec executable="command to start your server">
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
        <execution>
            <id>stop-server</id>
            <phase>post-integration-test</phase>
            <configuration>
                <target>
                    <exec executable="command to stop your server">
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
       </execution>
    </executions>
</plugin>


text:
Q: Use attribute from derived class while using method from the base class? I have the following code:
    #include <map>

class vehicle {
    private:
        int id = 0;
        std::map<std::pair<int, char>, int> seats{};
    public:
        void displaySeats();
    };

    class Bus : public vehicle {
    private:
        std::string type = "Bus";
    public:
        std::map<std::pair<int, char>, int> seats{ {{1,'A'},0 }, {{1,'B'},0 }, {{ 1,'C' }, 0}, {{ 1,'D' }, 0 }, {{ 1,'E' }, 0 },
            {{2,'A'},0 }, {{2,'B'},0 }, {{ 2,'C' }, 0}, {{ 2,'D' }, 0 }, {{ 2,'E' }, 0 },
            {{3,'A'},0 }, {{3,'B'},0 }, {{ 3,'C' }, 0}, {{ 3,'D' }, 0 }, {{ 3,'E' }, 0 },
            {{4,'A'},0 }, {{4,'B'},0 }, {{ 4,'C' }, 0}, {{ 4,'D' }, 0 }, {{ 4,'E' }, 0 },
            {{5,'A'},0 }, {{5,'B'},0 }, {{ 5,'C' }, 0}, {{ 5,'D' }, 0 }, {{ 5,'E' }, 0 }};
    };

    class MiniVan : public vehicle {
    private:
        std::string type = "MiniVan";
    public:
        // Seats map. <int, char> represents seats id(1A 1B 1C) the <int> will be either 0 or 1, representing if the seat is taken(1) or free(0).
        std::map<std::pair<int, char>, int> seats{ {{1,'A'},0 }, {{1,'B'},0 }, {{ 1,'C' }, 0},
            {{2,'A'},0 }, {{2,'B'},0 }, {{ 2,'C' }, 0},
            {{3,'A'},0 }, {{3,'B'},0 }, {{ 3,'C' }, 0},
            {{4,'A'},0 }, {{4,'B'},0 }, {{ 4,'C' }, 0} };
    };
    void vehicle::displaySeats()
    {
        std::pair<int, char> seat{ 1, 'E'};
        int columns = 5?this->seats.count(seat)>0:3;

        int displayRow = 0;
        for (const auto& p : this->seats) {
            if (displayRow == columns) {
                std::cout << std::endl;
                displayRow = 0;
            }
            displayRow++;
            std::cout << p.first.first << p.first.second << "\t ";
        }

    };

In main() i have:
MiniVan testMiniVan;
testMiniVan.displaySeats();

It displays the empty seats map attribute from the base class.
I am new to c++, but in other languages, it takes the derived class attribute. How can I solve this problem? Will I have to  create displaySeats for each child class ? If  yes, then why do I need base class in the first place?

A: This is something I've done fairly often as well, the issue is how things are constructed and which functions have access to which variables. Maybe you could do something like:
class Vehicle {
    private:
        int id = 0;
        std::map<std::pair<int, char>, int> seats{};
    public:
        // Add a constructor that takes in the `seats` map
        Vehicle(std::map<std::pair<int, char>, int> s) : seats(std::move(s)) {}
        void displaySeats();
};

and then for each child class:
class MiniVan : public Vehicle {
    private:
        std::string type = "MiniVan";
    public:
        // call the parent constructor passing in the seat map
        MiniVan() : Vehicle({{1,'A'},0 }, ...}) {}
};

Another approach would be to make a virtual function on the base class like:
class Vehicle {
    ...
    protected:
        ...
        const std::map<std::pair<int, char>, int>& get_seats() const = 0;
};

that the displaySeats function would call instead of directly loading this->seats. Each child class would need to define get_seats(), but that would be pretty easy (pretty much just return seats;). Hopefully that makes sense, let me know if not!


text:
Q: How do I replace commas in a string I want to remove all commas from a string using regular expressions, I want letters, periods and numbers to remain just commas

A: You don't need RE for that trivial operation. just use replace() on string:
a="123,asd,wer"
a.replace(",", "")

A: Why a regex?
mystring = mystring.replace(",", "")

is enough.
Of course, if you insist:
mystring = re.sub(",", "", mystring)

but that's probably an order of magnitude slower.


text:
Q: How to update the only changed fields in Firestore? In the users collection in Firestore, I have all users' uid as documents, inside each user document I am storing user preferences.
For example, here's a sample of user preferences I am saving in a specific user document:
{
  "preferences": {
    "settings": {
      "themeColorMode": "light-mode",
      "debugMode": false
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": true
      }
    }
  }
}

I want to update user document with the data sent in the body of an API
I want that API to be compatible in a way such that

*

*I should be able to add another root node other than preferences

*I should be able to customize and add new nodes in preferences.settings & preferences.filterChips

*I should be able to update a specific node - examples: preferences.settings.themeColorMode& preferences.filterChips.filterChipsPreferences
For example, in the request body I am sending this info:
{
  "preferences": {
    "settings": {
      "themeColorMode": "dark-mode",
      "isSoundNotificationOn": false,
      "isAppListeningToStream": true
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": false
      },
      "FirstUsedSearch": "23/12/2021"
    },
    "columnDefs": {
      "pathName": {
        "ColumnDefsPreferences": true
      }
  },
  },
  "search": {
      "savedSearches":["searchName"]
    }
}

I am expecting this result to be saved in the user's document
{
  "preferences": {
    "settings": {
      "themeColorMode": "dark-mode",
      "isSoundNotificationOn": false,
      "isAppListeningToStream": true,
      "debugMode": false
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": false
      },
      "FirstUsedSearch": "23/12/2021"
    },
    "columnDefs": {
      "pathName": {
        "ColumnDefsPreferences": true
      }
  },
  "search": {
      "savedSearches":["searchName"]
    }
  }
}

How could I approach that?

A: Since you are using the Node.js Admin SDK on the server that calls Firestore, it is actually quite straightforward: you need to use the update() method of the DocumentReference.

The update() method accepts either an object with field paths encoded
as keys and field values encoded as values, or a variable number of
arguments that alternate between field paths and field values.

More precisely:
// 1/ Define your DocumentReference
const userId  = ...;
const docRef = admin.firestore().doc(`users/${userId}`);

// 2/ Get the desired elements from the payload received by your API and use them to build the object to pass to the update method

// For example

const updateObj = {
    preferences.settings.debugMode: false,
    preferences.settings.themeColorMode: "myColor",
    preferences.filterChips.filterChipsPreferences: "myPref",
    aNewRootNode: {
       foo: 'bar',
       bar: 'foo'
    }
}

await docRef.update(updateObj);

More info on how to update fields in nested objects can be found in the doc of the JS SDK.


text:
Q: ImportError: Unable to find an implementation of PyGUI for this installation I had a simple app up and running that used the PyGui package. After I decided I had everything working I refactored my code and basically broke it up over multiple files, but I am fairly sure I did not change the location of any files. Now when I try to run my app It gives me the following error:
Traceback (most recent call last):
File "blobedit.py", line 16, in <module>
    from GUI import Application, ScrollableView, Document, Window, Cursor, rgb
  File "/Users/<myusername>/Desktop/BlobEdit/GUI/__init__.py", line 54, in <module>
    raise ImportError("Unable to find an implementation of PyGUI for this installation")
ImportError: Unable to find an implementation of PyGUI for this installation

I have tried moving files around for weeks and can't find the problem. Any help would be much appreciated!

A: You have a directory GUI and inside it __init__.py, this makes the directory an importable package.
Unfortunately, PyGUI also provides a GUI package. Due to the way Python searches for packages to import, your GUI has come up first and this is what is causing problems.
The simple way to solve it is to rename your GUI directory /Users/Destkop/BlobEdit/GUI to something else.


text:
Q: Problema subiendo archivo al servidor Tengo un formulario con varios campos de texto y dos campos tipo file, en el subo archivos PDF, la ruta me la guarda en la base de datos, pero los archivos no suben al directorio, también los otros campos. No me muestra ningún error, hace el proceso como si todo funcionara.
$file = new File;
$file_01 = $request->file('file_01');
$file_02 = $request->file('file_02');
$path_01 = Storage::disk('public')->put('files',  $file_01);
$path_02 = Storage::disk('public')->put('files',  $file_02);
$file->fill(['file_01' => $path_01])->save();
$file->fill(['file_02' => $path_02])->save();
$file->fill(['user_id' => $user->id])->save();
$file->save();

PD: Los demás campos van a otra base de datos y funciona bien (Los campos de textos).

A: Para hacerlos accesibles, debes crear un enlace simbólico de public/storage a storage/app/public:
php artisan storage:link


text:
Q: Cauchy Integral for complex analysis I need to find the below without residue theorem and only using Cauchy Integral theorem.
$$\int\frac{\cos z}{z^2(z-2)}dz$$
The problem I am having right now is how to express $\frac{\cos z}{z^2(z-2)}$ in terms of partial fraction decomposition. So that I can apply the Cauchy Integral formula of $$f^{(n)}(z) = \frac{n!}{2i\pi}\int\frac{f(w)}{(w-z)^{n+1}}\,dw.$$

A: $$\dfrac{1}{z^2(z-2)}=\frac{a}{z-2}+\frac{b}{z}+\frac{c}{z^2}=\dfrac{(a+b)z^2+(c-2b)z-2c}{z^2(z-2)}$$
Hence $c=-\dfrac12,b=-\dfrac14,a=\dfrac14$.

A: You can use the fact that$$\frac{\cos z}{z^2(z-2)}=-\frac{\cos z}{4z}-\frac{\cos z}{2z^2}+\frac{\cos z}{z-2}.$$


text:
Q: Grafana click table row and appear data in graph bar Ok, I would like to be able to click the row within my table shown below. Then display the data within the bar graph above.

So by clicking the row with 'AREA2', it would essentially be changing 'AREA1' to 'AREA2'. So how do I make the rows clickable and be able to make the change to be represented within the bar graph? (Suppose there are more than 100 areas) What is the option I am trying to do even called?
Bar Chart Query:
select coalesce(group_name) as group_name,
  sum(sales) filter (where device_type = 'HEAD_PHONES') as HEAD_PHONES,
  sum(sales) filter (where device_type = 'GUITAR') as guitar,
  sum(sales) filter (where device_type = 'XBOX') as xbox,
  sum(sales) filter (where device_type is null ) as other
from test
where area = 'AREA1' <-- change to update every row click
group by coalesce(group_name);

Entire Table:

A: I was able to accomplish this using URL_links available within the tables.

Add created a query variable, copied the url for my dashboard and assigned passed the call value as a parameter within my URL.
Resource: https://grafana.com/docs/grafana/latest/linking/data-link-variables/


text:
Q: nvm alias default not working in MacOS Capitan EL My nvm keep forgetting about the node environment ever since I upgraded to Yosemite(A few months ago)/Capitan EL(I upgraded this week) even though I did
nvm alias default 0.12

Hilariously, it told me after I hit enter
default -> 0.12 (-> v0.12.8)

But when I opened a new terminal it said node: command is not found!!
There are a couple of solutions I tried so far:

*

*I have tried using brew uninstall nvm & brew install nvm

*as well as the installing script, since brew complaint it doesn't work with the pre-released OS(which is actually GA right now)

*I double checked bash_profile do have the following lines
export NVM_DIR=~/.nvm
source $NVM_DIR/nvm.sh
Unfortunately, none of them works. Have anyone run into a similar issue before?
Thanks!

A: This is merely a temporary solution, however, it works.

*

*Add nvm use stable in ~/.bash_profile(or whatever version you want to use to replace stable)

*Save the file

*Do source ~/.bash_profile after this or simply open a new terminal tab.

A: This worked for me on El Capitan
brew uninstall nvm
brew install nvm
mkdir ~/.nvm
export NVM_DIR="$HOME/.nvm"
 . "$(brew --prefix nvm)/nvm.sh"

It said that .nvm folder already existed but I ignored that.

A: I just used this command in MacOS el capitan
$> nvm alias default v6.4.0

It worked as expected. Please notice the small v before the version number.
And finally, just if it helps, I used this command to install nvm as is described in the nvm project readme.
$> curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash


text:
Q: Failure to force type on java generic I have a complete stumper, and pose it to all of you to see if you know whats going on.
This is the data structure
Map<String, Object> objectMap

it stores Strings and Numerical values for now, but may store more types in the future.
This is the function I'm using to retrieve those values:
public <T> T get(String variable, T defaultValue) {
    // returns either the object from the map, or the default if its not in the map.
    Object value = getObject(variable, defaultValue);
    logger.debug("default value is of type " + defaultValue.getClass().getName());

    // Attempt to get around casting issue
    if (value instanceof Number)
    {
        value = (Number) value;
    }
    T ret = (T) value;
    logger.debug("Variable " + variable + " which is of type " + value.getClass().getName() + " and returning as " + ret.getClass().getName() + " (is number: " + (value instanceof Number) + ")");

    return ret;
}

And this is the calling code:
public int getFoo() { return this.<Integer>get("foo", 0); }

This is the output i see in the logs:
default value is of type java.lang.Integer
Variable foo which is of type java.lang.Long and returning as java.lang.Long (is number: true)

Right before it fails with:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

What concerns me the most here is that the class type appears to be Long, despite attempting to force the class to using Integer.
Am i missing something, or violating some concept of Java generics?
Thanks for any help

A: The value returned by the getObject method is a java.lang.Long - the log is telling you that.
Generics are not magic, they will not convert between types, they're simply syntactic sugar that the compiler turns back into casts.  So your method:
public <T> T get(String variable, T defaultValue)

is really:
public Object get(String variable, Object defaultValue)

When the get method is invoked with:
this.<Integer>get("foo", 0)

this is really:
(Integer)this.get("foo", 0)

Hence the ClassCastException because the Object being returned is a Long, not an Integer.
Without knowing exactly what you're trying to achieve it's hard to give concrete advice but generally your Map should be using the generic type that you are expecting to deal with.  In your case this sounds like either Integer or Number.  If you really want the int value of any Number (which I doubt because the value will be truncated when it's bigger than an int) then you should use the Number.intValue() method.

A: This is caused by Java type-erasure. Java typing is only used in source code. The compiler converts the code just like if you would have cast all objects. If you get a Long value, it means that you put it as a Long value.
This code does not perform anything:
if (value instanceof Number)
{
    value = (Number) value;
}

A: The value of the key "foo" in your backing map is obviously of type Long. You cannot cast a Long to an Integer (even if both are of type Number - and both are of type Object ;)
If you want to force an Integer, you have to do it when putting the value for "foo" into the map.


text:
Q: how to modify matches to a regular expression with sed or another tool? I need to manipulate text that's in a file.
I need to append a right parenthesis – ) – after every number
that's preceded by a comma – , – e.g.,

*

*,4   ➜ ,4)

*,15 ➜ ,15)
I am struggling to find the proper way to do this with sed. I tried the following, which works for 1 digit but can't seem to be extended to 2 digits (so it's fine for first line above but not the second):
sudo sed 's/,\([0-9]\)/,\1)/g' filename
So then I tried the following for 2 digits:
sudo sed 's/,\([0-9]([0-9]?\)/,\1)/g' filename
This didn't do anything - the file remained unchanged, though I did not receive an error message. What is the proper way to search for one required digit and a second optional digit and then move them both into the replacement text? I still need to accomplish this:

*

*,15 ➜ ,15)
Any advice would be greatly appreciated.

A: You were almost there, try this:
sudo sed 's/,\([0-9]\{1,2\}\)/,\1\)/g' filename

Here in addition to your command i have just added \{1,2\} which matches the previous regex between one to two times i.e. from a minimum of one time to a maximum of two times.
\([0-9]\{1,2\}\) explained:

*

*[0-9] will match a single digit between 0 to 9

*{1,2} will match the previous regex from one to a maximum of two times. So, one match is a must and the second is optional (as you want)

*() will make a regex group so that we can reference it later.

*Also note that we have used '\' in front of all extended regex syntax so that they they don't get treated literally. We could have used the -r switch (extended regex) with gnu sed, in that case we could just write:
sudo sed -r 's/,([0-9]{1,2})/,\1\)/g' filename

EDIT: If you want to match any number of digits (minimum one) after comma you can do:
sudo sed 's/,\([0-9]\{1,\}\)/,\1\)/g' filename

or more simply:
sudo sed 's/,\([0-9]\+\)/,\1\)/g' filename


text:
Q: Knockout.js using foreach and $index with if binding I'm trying to display the elements from an iterated list grouped inside divs 3 by 3. I've used the value of $index but I can't figure out why is not looking right.

other things here

The first div should open before the first element info and close after the third. The second div will open before the fourth and close after another three and so on till the list ends. What's the best approach here?

A: You cannot (or should not, I forget) really use Knockout in an imperative way like that, where you manually do or do not generate opening/closing tags. Instead, you need to nest things properly.
Put differently, treat  and  as proper close/end tags that always need to wrap around full elements.
Put even differently, you're trying to do the equivalent of this:

  Some content

      CONTENT

Perhaps Knockout should've given you an error, but (I guess in the spirit of HTML) it tries to make the best of it.
So instead, you should do the "grouping" logic in your view model. Added benefit is that you could potentially unit test it too. Here's an example:

const chunkSize = 3;

class RootVm {
  displaySel = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
  displaySelGroups = ko.computed(() =>
    // Chunk in groups of 3 based on:
    // https://stackoverflow.com/a/44687374/419956
    [...Array(Math.ceil(this.displaySel.length / chunkSize))].map(_ => this.displaySel.splice(0,chunkSize))
  );
}

ko.applyBindings(new RootVm());
.col-2 { background: silver; border: 1px solid black; }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-P5MgMn1jBN01asBgU0z60Qk4QxiXo86+wlFahKrsQf37c9cro517WzVSPPV1tDKzhku2iJ2FVgL67wG03SGnNA==" crossorigin="anonymous" />


text:
Q: Unable to echo PHP variable in javascript I have a PHP variable which contains a JSON object in string format.
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>

Javascript:
<script>
var obj = "<?php echo $phpObj; ?>";
</script>

When I try to echo a PHP variable in javascript, I get the following error:

Uncaught SyntaxError: Invalid or unexpected token.

I've tried using json_encode, but it gives me the same error.

A: No need to use the quotes ("s) and json_encode as it is already a JSON object. Try
var obj = <?php echo $phpObj; ?>;

When I ma fetching the data and try -
<?php
$phpObj = file_get_contents("http://ip-api.com/json");
?>

<script>
var obj = <?php echo $phpObj; ?>;
console.log(obj);
</script>

I am getting -
{as: "AS45194 Syscon Infoway Pvt. Ltd.", city: "Thane", country: "India", countryCode: "IN", isp: "Syscon Infoway Pvt.", …}

in the console.

A: Passing simple arrays or arrays of objects between PHP and JavaScript can be done through json_encode and json_decode respectively. For instance, in your case, I can do the following
<?php
  $url = "http://ip-api.com/json";
  $phpObj = file_get_contents($url);
?>
 <script>
  var obj = <?php echo $phpObj; ?>;
 </script>

Since the data fetched is JSON.
However, this fully depends on your application. If $phpObj = file_get_contents($url); returns json then I will simply do the following
<script>
  var obj = <?php echo $phpObj; ?>;
 </script>

If it's an object that is returned($phpObj), then I will, first of all, convert the object to an array then parse it into JSON format then echo it to JavaScript as shown below
<script>
  var obj = <?php echo json_encode((array)$phpObj); ?>;
 </script>

If it's an array that is returned, then I will parse the variable to JSON format then echo it to JavaScript as shown below
<script>
  var obj = <?php echo json_encode($phpObj); ?>;
 </script>

For the case of json_decode, if for instance, you want to use the value returned by file_get_contents($url); and assuming this returns JSON, you can convert the JSON to a PHP array or a PHP object as shown below,
$data_obj = json_decode($phpObj); //Return object not array
$data_arr = json_decode($phpObj,true); //Return array not object


text:
Q: Why was «What's your favorite "programmer" cartoon» deleted? What's your favorite "programmer" cartoon, a fabulous geek-fun-pop-culture question with +840 upvotes and 228 answers has been deleted without any remaining trace *.
Quoting Jeff here:

Funny stuff. We do prefer that
questions on Stack Overflow stay on
the topic of programming, but as Joel
and I have discussed before on the
podcast, this is somewhat subjective,
and it's OK to err on the side of
"fun" every now and then. Not all the
time, mind you, but occasional
peripherally related digressions that
the community enjoys (and upvotes) are
perfectly fine.

and again

This question may be more on-topic
than it looks, though. One of the
major reasons we created Stack
Overflow to give every programmer a
chance to be recognized by their
peers. Recognized for their knowledge,
their passion, and their willingness
to help their fellow programmers get
better at their craft.

Why deleted and not migrated to somewhere else?
* please don't suggest to get it through some crappy internet cache or odata dumps because my furious vengeance.. :)

A: www.outcast.se is actually still available... Soo tempted for a moment :) But not really.    I was mistaken. It's not available after all.
As proposed, I'm in favour of an archive for these questions to preserve them somewhere - especially the really creative ones with loads of original content. I'm opposed to creating a community around them, though - there's little point in that. Static pages will do.
I can see, though, that SO isn't going to be running this archive. Does anybody have ideas about a good, free, ad-free long term reliable hosting location that supports static HTML? Didn't Github have something like this?

A: I disagree that the question should be deleted.
It stands as the perfect example of everything that is wrong with allowing recommendation questions with one item per answer -- exactly the kind of evil SE 2.0 sites are struggling to avoid.
Without a concrete example to point to, our experience may be mistaken for bigot alarmism by newer users.

A: Last time I checked, a very high number of answers was a bad thing.  The point of a Q&A site is to provide some sort of practical information, and more than 5 or 10 upvoted answers means that either there are no wrong answers (in which case there was never a "question" to begin with) or that the question is too open-ended to have any practical use.  Maybe both.
But just to simplify it even more, let's test it against Jeff's Good Subjective criteria:

1. Great subjective questions inspire answers that explain "why" and "how".

Fail.

2. Great subjective questions tend to have long, not short, answers.

Fail.

3. Great subjective questions have a constructive, fair, and impartial tone.

Not constructive (no hint as to a practical purpose) and not impartial (a "favourite" is simply an opinion).  Fail.

4. Great subjective questions invite sharing experiences over opinions.

More fail.

5. Great subjective questions insist that opinion be backed up with facts and references.

Even more fail.

6. Great subjective questions are more than just mindless social fun.

Massive fail.
Really now, how many questions can we point to on any site that fail on all six points and get to stick around?  It was a popular question, but it was also a terrible one.  Sorry, but popular is not the opposite of suck.

A: Because otherwise it would be migrated to Programmers.SE, and displace The Oatmeal. That would be... a shame?

A: Deleted by Jeff. see: Programmers is about to go live, which questions should we migrate?
I agree with this decision, this is not on topic on any of our sites.

Migrating all these outcast questions to outcast.se has no chance of being created by us, think about it, why would we want to drive traffic into a dead end site with no community.
I kind of predicted this kind of stuff would happen. .... Its tricky business, this question really does not belong on SO, and most certainly should not be setting the tone of SO two clicks away from the home page https://stackoverflow.com/questions?sort=votes (where the best programmer joke is hanging out like the mark of Cain).
By having these soft off topic questions on SO we are telling our new users ... its ok, post whatever crap you want on SO, if you are lucky we will give you a bunch of badges for it.
The other option is making "programmers" a dumping ground ... that programmers cartoon question on "programmers" should probably be closed on programmers.