text:
Q: Is there a way to only add a property if it is defined via the spread operator? I have a variable name and I want to add it to an object only if it's defined and not null. For example, I check the value of name:
let name = null;
if(nameExists) {
    name = 'John Smith';
}

Then I only want to add it to the object as a field if it exists and is not null.
const results = {
   title: $(el).find('.title').text(),
   name
};

But this doesn't work. Any ideas?

A: Well, to do that, you have to spread an object containing the property or an empty object, depending on whether you want to add the property:
const results = {
   title: $(el).find('.title').text(),
   ...(
     name !== null
       ? {name}
       : {}
   )
};

But I think a conditional assignment could be clearer:
const results = {
   title: $(el).find('.title').text()
};

if(name !== null)
  results.name = name

A: I hope this example clears your concept.
function addName(name) {
    let obj = {"site":"stackoverflow"}; // create an object)=(it may be pre-existing)
    if(name) {
        obj = {...obj, name}; // add name field to obj only if it exists
    }
    return obj;
}

const ex1 = addName();
const ex2 = addName('John Smith');
console.log('If name is null: ', ex1);
console.log('If name exists: ', ex2);


text:
Q: Subspaces of locally compact spaces A topological space $X$ is called locally compact if every point $x \in X$ has a compact neighborhood. (It seems that this notion of "locally compact" is sometimes called weakly locally compact.)
I know that in a locally compact Hausdorff space all open, closed and locally closed subspaces are again locally compact. What is an example for an arbitrary subspace which is not locally compact?
Also, I am quite lost what happens if one drops the Hausdorff assumption. Do the above results still hold? If not, what are counterexamples?

A: In $\Bbb R$, endowed with its usual topology, $\Bbb Q$ is not locally compact. Actually, in $\Bbb Q$, if $V$ is any neighborhood of any point, then $V$ is not compact.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the proper format for the "date" datatype? My model "User" has a date attribute :birthday. But if I submit a birthday with any format other than x/x/x, it just becomes nil. So, for example, 1/1/1 becomes "0001-01-01", but 1/1/15 becomes nil. 1/1/2 becomes "0001-01-02", but 22/1/3 becomes nil.
I feel like I'm missing something here. It can't possibly be true that date attributes can only be x/x/x, right?

A: How are you setting the date?  Is it something like @user.birthday = params[:birthday]?  This is going to cause you problems because it's not a date, it's a string, and a string in a different format to how your database stores the date, at that.
You've got two options:
A) Ideally you should convert the input to a date, and then set the field using the actual date object.
B) make sure the format of your parameter matches how your db stores dates (which is "yyyy-mm-dd" by the looks of it).
A is preferable.  I would override the User#birthday= method to try to get it to process the date as usefully as possible.  eg
#in User model
 def birthday=(arg)
   if arg.is_a?(Date)
     self[:birthday] = arg
   elsif arg =~ /\d+\/\d+\/\d+/
     self[:birthday] = Date.strptime(arg, "%d/%m/%y")
   elsif arg =~ /\d+\-\d+\-\d+/
     self[:birthday] = Date.strptime(arg, "%y/%m/%d")
   else
     self[:birthday] = arg
   end
 end


text:
Q: How to set up mulitple signatures for one account in Claws-Mail I'm new to Claws-Mail. Claws-Mail has GPG signature capability. This is for using digital signatures.  I don't think this is what I'm looking for. I'd like a signature that is automatically added to the end of an email that gives my name, address and phone number. I'd like to set up multiple signatures for an account if possible. I found in Configuration > Preferences for Current Account > Compose

There was no .signature file so I created one in the specified directory using Libre Writer (the "edit" button didn't open an editor). The signature is automatically inserted to my emails. Is there a way or a plugin for setting up multiple signatures.

A: Just looked for the same thing and couldn't find it. I think the next best thing is to have multiple (almost) identical accounts with different signature settings.


text:
Q: How can you unit test for a correct configuration of a complex TypeToken? I have some service code that uses generics and TypeTokens to deserialize JSON. The service is needed to deserialize a complex TypeToken that keeps its generic parameters type.
Here is the code that creates it:
<T extends IPolicy> TypeToken<PolicyWrapper<T>> makePolicyWrapperTypeToken(Class<T> policyClass) {
    TypeToken<T> policyTypeToken = TypeToken.of(policyClass);
    return new TypeToken<PolicyWrapper<T>>() {}
        .where(new TypeParameter<T>() {}, policyTypeToken);
  }

It appears that the TypeToken isn't working correctly because I get a class cast error from GSON.
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap
cannot be cast to com.myStuff.IPolicy

It looks like I have it right when debugging. The toString() function shows that it knows its generic type parameter:
com.myStuff.PolicyWrapper<com.myStuff.PolicyImpl>

Finally, I have a unit test. It passes but it doesn't test the generic type parameter. I test the rawType() of the TypeToken and get the correct class but I'm not sure how to test its generic type.
@Test
 public void makePolicyWrapperTypeToken() throws NoSuchMethodException {

    TypeToken<?> wrapperToken = makePolicyWrapperTypeToken(PolicyImpl.class);
    assertEquals(wrapperToken.getRawType(), PolicyWrapper.class);

     //the getContent returns a list but it needs the generic type tested
     TypeToken<?> contentToken = wrapperToken.resolveType(PolicyWrapper.class.getMethod("getContent").getGenericReturnType());
     assertEquals(contentToken.getRawType(), List.class);

  }

A:
It appears that the TypeToken isn't working correctly because I get a class cast error from GSON.
  java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.myStuff.IPolicy

Not really. It looks like Gson, in your case, does not receive enough type information while deserialization. LinkedTreeMap is an internal Gson map implementation Gson uses to deserialize objects of unknown types with arbitrary structure by default. It may happen, for example, if generic classes parameterization information is lost/erased for some reason. For example, private final List<IPolicy> list; can be processed by tools like ProGuard so it may become private final List list; unless -keepattributes Signature is used -- generally speaking it's legit Java code, but Gson does not have enough type information and uses LinkedTreeMap. And this what you should get once trying to assign such a list element to a IPolicy reference. Another scenario is typeToken.getRawType() instead of type.getToken(): raw types do  not contain parameterization info, so new TypeToken<List<IPolicy>>(){}.getRawType() is just a List.class -- still no information on elements type that makes Gson to use the default strategy.

the getContent returns a list but it needs the generic type tested

Just use TypeToken.getType() that returns java.lang.reflect.Type that is the base interface for all types. Parameterized generic types are represented with ParameterizedType that provides more information on the type parameterization unlike the more general Type does, and this information can be built with type tokens as well. So, the following assertion is true:
// not really necessary, but just for the demonstration purposes:
assertTrue(contentToken.getType() instanceof ParameterizedType);
// this is enough:
assertEquals(new TypeToken<List<PolicyImpl>>() {}.getType(), contentToken.getType());


text:
Q: Error while trying to port a repo from github There is a github code I am trying to use that is located here.
I am trying to run params.py which is a code that will take a binary file and converts it so that I can plot it (or so I think).
I tried to run:
pip install git+https://github.com/PX4/pyulog.git

However, that gave me an error:
C:\Users\Mike\Documents>pip install git+https://github.com/PX4/pyulog.git
Collecting git+https://github.com/PX4/pyulog.git
  Cloning https://github.com/PX4/pyulog.git to c:\users\mike\appdata\local\temp\pip-t_vvh_b0-build
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Anaconda3\lib\tokenize.py", line 454, in open
        buffer = _builtin_open(filename, 'rb')
    FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Mike\\AppData\\Local\\Temp\\pip-t_vvh_b0-build\\setup.py'

A: Pip install tries to install the module from :

*

*PyPI (and other indexes) using requirement specifiers.

*VCS project urls.

*Local project directories.

*Local or remote source archives.

When looking at the items to be installed, pip checks what type of item each is, in the following order:

*

*Project or archive URL.

*local directory (which must contain a setup.py, or pip will report an error).

*Local file (a sdist or wheel format archive, following the naming conventions for those formats).

*A requirement, as specified in PEP 440.

In your case, git repo doesn't meet the requirement. It doesn't have setup.py that's why you get the error.
Instead try cloning the repo on your local machine.


text:
Q: J2EE - Do we require transaction management support for anything other than Database? As we know , one of the major difference between web server and application server is transaction management. What exactly the transaction management refers. Does it mean the Database transaction support?. Database is external entity , we can use Database with Web server as well as Application server.
So , other than Database entity, do we require transaction management support for any thing else?
Thanks

A: Yes transaction management applies to other concepts such as  JMS (and queues generally)
You can find more information on jms and transactions on the java documentation.
Another example that is outside of the application server domain are the transactions regarding the azure service bus.

A: From Oracle docs:
"Transaction management contract is used for outbound communication from WebLogic Server to Enterprise Information Systems (EISes)".
For Weblogic, you must create datasource specifing name, jndi-name, driver, host, port, user, password and type of transaction that you need (XA or not XA).
XA transaction is global, not-XA local.
To learn more, see: https://docs.oracle.com/cd/E13222_01/wls/docs100/resadapter/transact.html


text:
Q: how can I use sympy to add expressions with index I have a dataframe in pandas, the first columns is named x0 and the second is x1. It has many(like 100) rows. Thus I have 100 groups of [x0,x1], and then I want to generate a long expression with every related to one group. More clearly, the task I want to do is to generate a expression:
exp(b0*x00+b1*x10)+exp(b0*x01+b1*x11)+...exp(b0*(x0 100) + b1*(x1 100))

b0 and b1 are both unknown value (symbols) here and I will find their solution later on.
In brief, I need to expression sigma(exp(b0*x0+b1*x1)) and the sigma has 100 items with x0,x1 n a dataframe, but I don't know how to program the loop.
Please help me.

A: i hope this helps, i'm not familiar with Panda, but you need the summation(f, (i, a, b)) from sympy.
essentially, you will just need to declare something like expr = summation(exp, (i, 0, 101))
in this case, your 'exp' function already has symbolic b0 and b1 terms inside it.
and when you want to pretty print it out, you just need to use pprint(expr) instead of print().

A: A simple python for-loop would suffice to generate that expression:
>>> import numpy as np  # pandas uses numpy arrays
>>> import sympy as sym
>>> x = np.random.rand(5,2).view(dtype=[('x0', np.float), ('x1', np.float)])
>>> b0, b1 = sym.symbols('b0 b1')
>>> x['x0']  # to show the contents
array([[ 0.1389724 ],
       [ 0.14091647],
       [ 0.08886302],
       [ 0.48792306],
       [ 0.749205  ]])
>>> expr = 0
>>> for x0, x1 in zip(x['x0'], x['x1']):
...     # build up the expression term by term:
...     expr += sym.exp(b0 * float(x0) + b1 *float(x1))
...
>>> expr
exp(0.0888630154325879*b0 + 0.597823474111901*b1) + exp(0.138972400914926*b0 + 0.0275642343608167*b1) + exp(0.140916465250792*b0 + 0.0662746588259522*b1) + exp(0.487923064546991*b0 + 0.922545565808876*b1) + exp(0.7492050039088*b0 + 0.911117507753871*b1)


text:
Q: Mongodb getting the entire sub-schema for all results I have a simple schema as below,
Post {
createdAt: Date,
createdBy: ObjectID,
...
}

User {
_id: ObjectID,
name: String,
...
}

When a user creates such a record, I save it with his ID.
For the Post collection, I want to create a query and retrieve the records, with sending the entire User schema for all results. For example, a simple result:
 [
    {
    createdAt: xxx,
    createdBy: {
       _id: xxx,
       name: xxx
    },
    ...
 ]

A: You can do that with population, like this:
Posts.find({}).populate('createdBy');


text:
Q: Image not uploading to web server I am having some difficulty uploading an image to a folder on my web server. Here's my code:
HTML:
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload Image" name="upload">
</form>

PHP:
<?php
    if (isset($_POST["upload"])) {
        $name = $_FILES["image"]["name"];
        $type = $_FILES["image"]["type"];
        $size = $_FILES["image"]["size"];
        $temp = $_FILES["image"]["tmp_name"];
        $error = $_FILES["image"]["error"];
        $target_file = "/profiles/images/$name";
        move_uploaded_file($temp, $target_file);
    }
?>

I've tried echoing out the file name ($name), but it doesn't return anything at all. It's blank for some reason. This is when I try to upload an image. When I echo $target_file, I get this "/profiles/images/", the $name part is not included for some reason.

A: Check your max upload file size. If in the settings the size is smaller than the file you are trying to upload, nothing is send.

A: This is happens in those cases when we try to upload very heavy size image, Please try to check your maximum file size, and please for testing try to upload maximum 100kb size of pic through this code. Hope this will work.


text:
Q: Different result solving differential equation? I'm trying to solve this differential equation.
But I get a different result when I solve it with Maple. What am I missing?

A: Your $e^{-P(t)} = e^{-(-7\cos t)} = e^{7\cos t}$.  You dropped the minus in the 7th line.


text:
Q: Using "thereof" to refer to people, in my case to "staff" Somehow I feel like the word "thereof" doesn't fit well, but I can't put my finger on it. Can you help me decide between the following formulations (or find a working alternative)?

Target is organizational and technical managerial staff, and representatives thereof.

First, I'm not sure if I'm starting the sentence correctly. Would it perhaps be better to write something along the lines of

The target group consists of organizational and technical managerial staff, and their representatives.

or even to insert the word "respectively"? The sentence should describe the target group of an application we wrote, that is, the end users of the application. Any input is very welcome as this is the first time I have to write a business-related text in English.
Edit: Though I'm mainly interested in the American English view on this, I'm also glad for suggestions regarding British English.

A:
Target is organizational and technical managerial staff, and representatives thereof.

The only thing I'd change about this sentence is adding the to the beginning, in front of target, because it needs a specifier. Your use of thereof is correct, meaning the target also includes representatives of organizational and technical managerial staff. This is extremely formal diction; perhaps that's why it feels a little strange to you?

The target group consists of organizational and technical managerial staff, and their representatives.

This is just fine, and conveys the same meaning, though it is less formal. It's not informal, mind; this is perfectly acceptable language in a professional setting. Additionally, it's a little more accessible than the first sentence, precisely because it's not as rigidly formal.

or even to insert the word "respectively"?

Don't do this, because it will be confusing to the reader. Use respectively to indicate that items in two lists correspond to each other in sequential order. For example, we have meetings on Monday and Tuesday, at 1:00 and 3:00 respectively. Here, respectively tells us that Monday's meeting is at 1:00 and Tuesday's meeting is at 3:00. You don't have this kind of structure in your sentences, so you don't need respectively.
Ultimately, both of your sentences are acceptable in a business setting, so it's up to you how formal you want to sound. If you're writing a legal document (a contract or bill) or giving a speech to heads of state or other equally important people at a formal business event, the first is more appropriate. If you're writing something up for your manager and your office is a casual dress sort of place, stick to the second. Beyond that, it's your call.


text:
Q: Custom icon for status when using service Android I am using a foreground service. With it I have to show notification and add an icon to the status bar like this:
    val notification = Builder(this, CHANNEL_ID)
    .setContentTitle("adf")
    .setSmallIcon(R.drawable.ic_baseline_settings_input_component_24)
    .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
    .setSmallIcon(R.drawable.ic_baseline_settings_input_component_24,2)
    .setContentText("ewr").build()
    startForeground(1, notification)

Text displayed correctly but icon doesn't changed and shows only the default Android's icon. How can I add a custom icon?

A: Did you add this into your android manifest xml?
<application
    android:icon="@drawable/icon"
    android:label="@string/app_name">

    <!-- Add your meta-data here-->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_baseline_settings_input_component_24" />

    ...
</application>


text:
Q: Conversão Farenheit Celsius Fazer um algoritmo que calcule e escreva uma tabela de centígrados em função de graus
Farenheit, que variam de 50 a 150 de 1 em 1
Eu encontrei a solução em C não em C++,
#include <iostream>
using namespace std;

int main()
{

    for (float F = 50; F < 150; F++) {
        float Ce;
        Ce = (5 / 9) * (F - 32);
        cout << "\nFarenheit " << F << "\nCentigrados  " << Ce;
    }
}

A: Ao fazer a divisão de um inteiro por um inteiro o resultado será, também, um inteiro. Ou seja, se você dividir 5 por 9, sendo ambos inteiros, terá como resultado 0, pois é a parte inteira do resultado real. Desta forma, independente do valor de F, você sempre multiplicará por zero, o que justifica a sua saída ser sempre zero.
Se você precisa de uma divisão real, utilize pelo menos um dos operandos como sendo real.
C = (5.0/9)*(F-32)


text:
Q: How to clear all contents of textbox when spacebar is pressed? VB.Net I'm creating a simple typing test program.
I want the space bar to trigger checking if the typed word is correct, then clear the contents of the textbox.
What happens here is the first typed word will work and be counted when the space bar is pressed and the typed word will be cleared, but the space character still remains and so the next typed word will contain a space char and will be read wrong.
I tried interchanging where the txtInput.Clear() should be placed but results in the same problem.
Private Sub txtInput_TextChanged(sender As Object, e As KeyEventArgs) Handles txtInput.KeyDown

    If e.KeyValue = Keys.Space Then
        Space()
    End If

End Sub

Public Function Space()

    If txtInput.Text = txtWord.Text Then
        ctr = CInt(txtWord.TextLength)
        charTotal = charTotal + ctr
        lblScore.Text = charTotal.ToString
    End If

    txtInput.Clear()
    txtWord.Text = rdmWord()

End Function

A: In KewDown Event the value of TextBox isnot setted yet. So, use KeyUp Event as the code below shows
Private Sub txtInput_KeyUp(sender As Object, e As KeyEventArgs) Handles txtInput.KeyUp
    If e.KeyValue = Keys.Space Then
        Space()
    End If
End Sub

A: You could also override ProcessCmdKey and trap the spacebar there:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    If keyData = Keys.Space Then
        If Me.ActiveControl Is txtInput Then
            Space()
            Return True ' suppress space
        End If
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

If you want to allow space or enter, then change to:
    If keyData = Keys.Space Or keyData = Keys.Enter Then


text:
Q: Obtaining Context from an embedded Glassfish 3.1 Does anyone now a way to obtain server Context using Embeddable API (using org.glassfish.embeddable.GlassFish, not javax.ejb.embeddable.EJBContainer)?
It would be possible if there's a way to obtain EJBContainer from a running Glassfish, but I can't find even the list of services available for lookup.

A: Here's a workaround - we can obtain InitialContext as an external client.
For the full explanation check EJB_FAQ . This way at least remote EJBs could be tested:
So the full example will look like:
//Start GF
GlassFishRuntime gfRuntime = GlassFishRuntime.bootstrap();
GlassFish gf = gfRuntime.newGlassFish();
gf.start();
//Deploy application with EJBs
Deployer deployer = gf.getService(Deployer.class);
String deployedApp = deployer.deploy(new File(...), "--force=true");
//Create InitialContext
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
    "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
    "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state",
    "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
InitialContext ic = new InitialContext(props);
//Lookup EJBs
ic.lookup(...)
//Stop GF
gf.stop();
gfRuntime.shutdown();
//CORBA stuck thread, have to kill it manually
System.exit(0);

Note there's a System.exit(0) at the end - com.sun.corba.ee.impl.javax.rmi.CORBA.Util.KeepAlive thread is running even after the server stop preventing JVM from stopping...

A: As far as I know, you can initialize the InitialContext class to obtain a context, that can further be used to perform the lookup. This was tested, and found to work in the context of looking up an EJB, deployed in the embedded container. The EJB was not configured to allow access to specific roles, in which case the com.sun.appserv.security.ProgrammaticLogin class (not exposed via the Embeddable EJB API) might help; this was not tested, but is the recommended way to initialize the Principal for the thread accessing an EJB.
A more or less complete example that runs from Maven and uses the embedded Glassfish dependency in a POM (not reproduced here, for brevity) follows:
The EJB interface:
public interface EchoManager
{
    String echo(String message);
}

The Session Bean:
@Local(EchoManager.class)
@Stateless
@EJB(name="java:global/glassfish-ejb-validation/EchoManager",beanInterface=EchoManager.class)
public class EchoManagerBean implements EchoManager
{

    public String echo(String message)
    {
        return message;
    }

}

The unit test:
public class EchoManagerTest
{

    @Rule
    public TestName testMethod = new TestName();

    private static final Logger logger = Logger.getLogger(EchoManagerTest.class.getName());

    @Test
    public void testEchoWithGlassfishRuntime() throws Exception
    {
        logger.info("Starting execution of test" + testMethod.getMethodName());

        GlassFish glassFish = null;
        Deployer deployer = null;
        String appName = null;
        try
        {
            //Setup
            BootstrapProperties bootstrapProps = new BootstrapProperties();
            GlassFishRuntime glassFishRuntime = GlassFishRuntime.bootstrap(bootstrapProps);

            GlassFishProperties gfProps = new GlassFishProperties();

            glassFish = glassFishRuntime.newGlassFish(gfProps);
            glassFish.start();

            deployer = glassFish.getDeployer();
            ScatteredArchive archive = new ScatteredArchive("glassfish-ejb-validation", Type.JAR);
            archive.addClassPath(new File("target", "classes"));
            archive.addClassPath(new File("target", "test-classes"));

            appName = deployer.deploy(archive.toURI(), "--force=true");

            // Setup the context
            InitialContext context = new InitialContext();

            //Execute (after lookup the EJB from the context)
            EchoManager manager = (EchoManager) context.lookup("java:global/glassfish-ejb-validation/EchoManager");
            String echo = manager.echo("Hello World");

            //Verify
            assertEquals("Hello World", echo);
        }
        finally
        {
            if(deployer != null && appName != null)
            {
                deployer.undeploy(appName);
            }
            if(glassFish != null)
            {
                glassFish.stop();
                glassFish.dispose();
            }
            logger.info("Ending execution of test" + testMethod.getMethodName());
        }
    }
}

Note that the EJB is deployed with a explicit portable JNDI name (via the @EJB annotation), as I have other tests that use the public embeddable EJB API in other tests, and it is more or less difficult to specify an application name in such tests; each test execution might result in a different JNDI name for the EJB, thus necessitating an explicit JNDI name to be specified.


text:
Q: confusing: How to obtain the AUC for implicit feedback recommender system? I am confusing how to calculate the AUC (area under the curve) for implicit feedback recommender system. Since it is implicit data, that means we just know the positive entries while we do not know the negative entries. For evaluating such recommender system, recall-based metric (such as MPR, mean percentile ranking) is ok. But AUC calculation should also need the negative entries, that is unknown in fact for implicit data. But I notice some papers also showed the AUC, can you help me or give me a hint about how to calculate AUC for implicit data-based recommender system?
How to obtain the negative entries?

A: The AUC Curve is calculated from the True Positive and False Positive rates. True positives are the items that the recommender recommends for a given user and are as well in the test set for a given user. False positives are items recommended by the algorithm for a given user and are missing in the user's test vector.


text: Q: Umbraco - Configure entity tags (ETags) I am using Umbraco. There are three suggestion is coming when I check my performance in pingdom. I have already enabled compression in IIS Manager. But still that suggestion is coming. I don't know how to configure ETags also. Kindly let me know how to overcome this


text:
Q: omnet++ : how to rebuild added source codes to existing class? I am using Omnet 4.2.2. For my project, I want to write a function calculateKShortestPaths(src, dest) to calculate k-shorstest paths from src to dest nodes. I come up with two options to make it available for use. One option is to add directly into existing cTopology class. The other option is to subclass the cTopology class in my own project class. I prefer option 1 (to add directly to cTopology class) since it has just a little change, and I can use cTopology seamlessly, but how can I rebuild it? And any idea for option 2 please? Thanks a lot.
Danh

A: To rebuild cTopology just open terminal, go to the main directory of OMNeT++ and type make.


text:
Q: Converting a c++ unordered_map to java hashMap before returning it to java using JNI I have a very large c++ unordered_map on android platform I would like to return this as a hashMap in java using JNI.
extern "C" JNIEXPORT jobject JNICALL Java_quantum_QUANTUM_getMessage(JNIEnv *env, jobject thisObj, jdoubleArray bbox) {

    unordered_map<int, Foo> Map;
    Map = getData(filename, bbox);

    // convert Map to java object
    // return java object
}

I am quite new to JNI. I haven't found any helpful material on how to do this.
I tried the approach in the link below but I am getting a lot of compilation errors on this.
how to correctly send a std::map<> from C++ to Java through JNI?
Another suggestions was to pass an empty javaHashmap over JNI and populate it. But I am not sure on how to do that. what is the better solution?

A: It will require some tweaking. You can do it by creating Map object inside C++ or by passing Map from Java to C++ and filling it there.
Basically, what you need is to:

*

*create HashMap
  jclass mapClass = env->FindClass("java/util/HashMap");
  if(mapClass == NULL) {
    return NULL;                  // alternatively, throw exception (recipeNo019)
  }

  jobject hashMap = env->NewObject(mapClass, mapConstructorID);
  if(hashMap == NULL) {
    return NULL;                  // as above
  }

*making sure to embed your primitive types inside object (e.g. you can embed int inside Integer)

  jclass integerClass = env->FindClass("java/lang/Integer");
  if(integerClass == NULL) {
    return NULL;                  // alternatively, throw exception (recipeNo019)
  }

  jmethodID integerConstructorID = env->GetMethodID(integerClass, "<init>", "(I)V");
  if(integerConstructorID == NULL) {
    return NULL;
  }

  ...
  ...

  jobject key = env->NewObject(integerClass, integerConstructorID, pair.first);

*filling HashMap with data

  for (auto const& pair: map) {
    jobject key = env->NewObject(integerClass, integerConstructorID, pair.first);
    jobject value = env->NewObject(integerClass, integerConstructorID, pair.second);
    if(key == NULL || value == NULL) {
      return NULL;
    }
    env->CallObjectMethod(hashMap, putMethodID, key, value);
  }

That's it. You can find full sample code here:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo047
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo048


text:
Q: Weird conditional probability question My teacher gave us a problem
Let the random variable X have probability density function
$$
f(x) =
\left\{
\begin{array}{cc}
2(1-x)& \text{if } 0 < x < 1 \\
0& \text{elsewhere}
\end{array}
\right.
$$
He asks us to find the PDF, which I have as:
$$
F(x) =
\left\{
\begin{array}{cc}
0& \text{if } x < 0 \\
2x - x^2& \text{if } 0 < x < 1 \\
1& \text{if } x > 0 \\
\end{array}
\right.
$$
He then asks us to find the median of X, which I don't know how to do?? I know how to find the mean.
And then he asks: "given $X \geq 0.5$ what is probability that $X$ will be less than $0.75$" and I am not sure how that works? Is that $F(0.75)-F(0.5)$?

A: I think you have a typo: you have found the CDF.

Hint 1: The median of $X$ is the number $m$ satisfying $P(X \ge m) \ge 1/2$ and $P(X \le m) \ge 1/2$.

 From your CDF computation, this means finding $m \in (0,1)$ such that $1 - (2m - m^2) \ge 1/2$ and $2m - m^2 \ge 1/2$. Actually, there will only be one such $m$, and both inequalities will be equality.

Hint 2:
For your second question, you need to compute
$$P(X \le 0.75 \mid X \ge 0.5).$$
Apply the definition of conditional probability.

 $$P(X \le 0.75 \mid X \ge 0.5) = \frac{P(0.5 \le X \le 0.75)}{P(X \ge 0.5)}$$


text:
Q: Why does switching power supply output AC I've been trying to troubleshoot some a 3D printer. It wouldn't power up. I checked the power supply (NES-350-24). The positive and negative outputs measured 0VDC, and 8VAC rms (confirmed with o-scope). I figured it should be outputting DC, and that the supply must be broken. I replaced it with a similar PS (LRS-350-24). Connected it to 120VAC power, and the outputs are still 8VAC RMS (60Hz).
Is this supply behaving normally? Is there some other issue? What am I overlooking? I would very much like to understand better what the issue is here, but I am no expert in these kinds of devices.
Edit: The new supply appears to be working as expected. I am still not able to ascertain the reason for the failure of the old supply. There are no obviously burned out components. Thank you all for your input.

A: First, the right way to measure the PSU output is directly across its terminals with a voltmeter, not a scope to ground. Verify you have output this way.
Now, about that AC voltage. It's normal, and it a characteristic of supplies like this have have an isolated secondary. What that means is, the output floats with respect to the line input and to earth (safety) ground. Meanwhile, the primary line/neutral connects to frame ground through a special capacitor called a Y cap. The PSU datasheet shows this in the diagram.
In the ideal case the primary-to-secondary isolation is complete: there is no circuit between earth or line and the power supply outputs. The output is said to be floating, and can have any offset with respect to ground.
In reality there is some coupling between the line input primary that appears on the secondary output that happens through the DC-DC transformer. This will show up as a common-mode AC voltage on the output, when measured using a high-impedance tester, measured from outputs to earth ground. This AC voltage is called leakage, and is usually under 5mA max for a typical supply (medical supplies are lower).
If this small leakage is a problem for your system, you can ground the secondary to earth (safety) ground.
On the other hand, Never connect safety ground to neutral! The two inputs (L1 and Neutral) could be swapped, resulting in a hot chassis and an unsafe system.


text:
Q: atoi is a standard function. But itoa is not. Why? Why this distinction? I've landed up with terrible problems, assuming itoa to be in stdlib.h and finally ending up with linking a custom version of itoa with a different prototype and thus producing some crazy errors.
So, why isn't itoa not a standard function? What's wrong with it? And why is the standard partial towards its twin brother atoi?

A: No itoa has ever been standardised so to add it to the standard you would need a compelling reason and a good interface to add it.
Most itoa interfaces that I have seen either use a static buffer which has re-entrancy and lifetime issues, allocate a dynamic buffer that the caller needs to free or require the user to supply a buffer which makes the interface no better than sprintf.

A: An "itoa" function would have to return a string.  Since strings aren't first-class objects, the caller would have to pass a buffer + length and the function would have to have some way to indicate whether it ran out of room or not.  By the time you get that far, you've created something similar enough to sprintf that it's not worth duplicating the code/functionality.  The "atoi" function exists because it's less complicated (and arguably safer) than a full "scanf" call.  An "itoa" function wouldn't be different enough to be worth it.

A: The itoa function isn't standard probably for the reason is that there is no consistent definition of it. Different compiler and library vendors have introduced subtly different versions of it, possibly as an invention to serve as a complement to atoi.
If some non-standard function is widely provided by vendors, the standard's job is to codify it: basically add a description of the existing function to the standard. This is possible if the function has more or less consistent argument conventions and behavior.
Because multiple flavors of itoa are already out there, such a function cannot be added into ISO C. Whatever behavior is described would be at odds with some implementations.
itoa has existed in forms such as:
void itoa(int n, char *s); /* Given in _The C Programming Language_, 1st ed. (K&R1) */

void itoa(int input, void (*subr)(char)); /* Ancient Unix library */

void itoa(int n, char *buf, int radix);
char *itoa(int in, char *buf, int radix);

Microsoft provides it in their Visual C Run Time Library under the altered name: _itoa.
Not only have C implementations historically provided it under differing definitions, C programs also provide a function named itoa function for themselves, which is another source for possible clashes.
Basically, the itoa identifier is "radioactive" with regard to standardization as  an external name or macro. If such a function is standardized, it will have to be under a different name.


text:
Q: Read Specificst from txt file - javascript I begin with variables userId, userPoints and userCodes.
And I want a text file with the following contents:

[userId: user9283], [userPoints: 45], [userCodes: kjsdnosd, sndjncjks, nsdjknckjs]

In javascript, how would you go about writing gathered data to a txt file using that format, changing when the variable changes and grabbing for example just the contents of userCodes in an array when asked for.
This would be somewhat like a database, but locally for a small amount of data. I have looked into fs.WriteFile and AppendFile, but not sure how to go about reading specific contents of a line and/or adding to specific contents, checking if a userid is already in there, and if so, appending it.
Thank you :)
var fs = require('file-system');

fs.writeFile('SavedAccounts.txt', "", function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

fs.appendFile('AccountsToBeMade.txt', userID, function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")

A: If you intend to only use the data within JavaScript, I would suggest that you write stringified JSON to the file. You could then do:
const fs = require('file-system');
const users = [{userId: 123, userPoints: 45, userCodes: [1, 2, 3]}]

fs.writeFile('SavedAccounts.json', JSON.stringify(users), function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

Instead of appending to the file, you would add/remove and alter your array of users, then write the whole thing back to the file.
You would need to JSON.parse() when reading the file back out
If you wanted to update a specific user you could do:
const userId = 123;
const user = users.indexOf(user => user.id === 123);

user.userPoints = 46;

fs.writeFile('SavedAccounts.json', JSON.stringify(users), function (err) {
  if (err) {
    console.log("write failed")
  } else {
    console.log("write success")
  }
})

This should be split up into methods properly, but hopefully explains the idea


text:
Q: Is there a better/closed form for the Cauchyproduct $A^k + A^{k-1}(A+I)/2 + A^{k-2}((A+I)/2)^2 + ... +( (A+I)/2)^k$ ($A,I=A^0$ matrices)? Is there a better/closed form for  the Cauchyproduct $$A^k + A^{k-1}(A+I)/2 +  A^{k-2}((A+I)/2)^2 + ... +( (A+I)/2)^k$$ ?Here $I$ is the identity and $A$ the upper subdiagonal filled with the unit ($a_{r,c}= \delta_{r+1,c}$).  Clearly $A$ and $I$ commute so we can do some reformulations, but unfortunately $A$ is not invertible.
$$A=\small {\begin{bmatrix} 0&1&0&.&.&... \\ .&0&1&0&.&... \\ .&.&0&1&0&... \\ ...\end{bmatrix} }$$

A: When $A$ is strictly triangular and $B=\frac{A+I}2$, the matrix difference $A-B=\frac{A-I}2$ is invertible. Since $A$ and $B$ commute, $A^k+A^{k-1}B+\ldots+AB^{k-1}+B^k=(A-B)^{-1}(A^{k+1}-B^{k+1})$.


text:
Q: Single Instance at a Time and Single Operation Target I am currently developing a visual c# application which shall run in background on the first instance "A" it was created. Now, I want that for the other time "B" the same application is run, the arguments in "B" be passed and processed in the existing instance "A". Thus, the "B" will not anymore open a new background application.
I already have searched about making a single instance applications but never have I encountered any solution to this problem of passing the arguments to the running instance.

A: The only way to solve your problem in my experience is with some form of inter-process communication - Named Pipes, Memory Mapped file, even TCP/WCF are all candidates. So you would use a Mutex to detect if instance A is already running and then connect to it via IPC to pass the parameters.


text:
Q: Install azure integration runtime on linux and move data from Linux to Azure blob storage I want to move data from Linux RHEL 8.5 to Azure blob storage.
I have a server of postgreSQL running on that linux vm and I want to move some table periodically from vm to azure blob storage.
After reading their official documentation, Azure IR only support windows environment.
Is there any way that I can use Azure data factory to move data from linux RHEL 8.5 to Azure blob storage?

A: Azure data factory has a connector to PostgreSQL. If your server can be connected from the internet, then you can use data factory directly. If your server is behind a firewall, you need to install self hosted IR, which you will need to install on another (windows) server, in the same network of your PostgreSQL server.


text:
Q: React autocomplete in a textarea like in an IDE (e.g. VS Code, Atom) I try to code an auto completion feature like in the gif in React.
So suggestions appear while writing text.
However all packages I could find so far work
a) only in the beginning of the input/textarea (e.g. react-autosuggest)
b) or need a trigger character (like @ or #) to open (e.g. react-textarea-autocomplete)
Do I miss some React limitation? Any hints / packages?

A: We ended up using the fantastic editor Slate.js.
The Mentions example can easily be changed so that the suggestions are triggered by any character (not only '@'). There you go: perfect auto suggest.

A: I'm actually having the same problem in regards to needing a textarea implementation, but I can help with autocomplete triggering behavior.
We have an implementation of template variables that look like this {{person.name}} which get resolved into whatever the actual value is.
In regards to the autocompletion being triggered only on the first word, you can get around that with a couple modifications to the required functions.
For instance my required functions look like this. (not a completely working example, but all the important bits)

    const templateVars = Object.values(TemplateVarMap);

    const variables = templateVars.map((templateVar) => {
        return {
            name: templateVar,
        };
    });

    //This func, onChange, and onSuggestionSelected/Highlight are the important
    //parts. We essentially grab the full input string, then slice down to our
    //autocomplete token and do the same for the search so it filters as you type
    const getSuggestions = (value) => {
        const sliceIndex = value
            .trim()
            .toLowerCase()
            .lastIndexOf('{{'); //activate autocomplete token
        const inputValue = value
            .trim()
            .toLowerCase()
            .slice(sliceIndex + 2); //+2 to skip over the {{
        const inputLength = inputValue.length;
        //show every template variable option once '{{' is typed, then filter as
        //they continue to type
        return inputLength === 0
            ? variables
            : variables.filter(
                (variable) => variable.name.toLowerCase().slice(0, inputValue.length) === inputValue
            );
    };

    const getSuggestionValue = (suggestion) => suggestion.name;

    const renderSuggestion = (suggestion) => <div>{suggestion.name}</div>;

    onSuggestionsFetchRequested = ({ value }) => {
        this.setState({
            suggestions: getSuggestions(value),
        });
    };

    onSuggestionsClearRequested = () => {
        this.setState({
            suggestions: [],
        });
    };

    onChange = (event, { newValue }) => {
        //onChange fires on highlight / selection and tries to wipe
        //the entire input to the suggested variable, so if our value
        //is exactly a template variable, don't wipe it
        if (templateVars.includes(newValue)) {
            return;
        }
        this.setState({
            value: newValue,
        });
    };

    //These both need to do similar things because one is a click selection
    //and the other is selection using the arrow keys + enter, we are essentially
    //manually going through the input and only putting the variable into the
    //string instead of replacing it outright.
    onSuggestionHighlighted = ({ suggestion }) => {
        if (!suggestion) {
            return;
        }
        const { value } = this.state;
        const sliceIndex = value.lastIndexOf('{{') + 2;
        const currentVal = value.slice(0, sliceIndex);
        const newValue = currentVal.concat(suggestion.name) + '}}';
        this.setState({ value: newValue });
    };

    onSuggestionSelected = (event, { suggestionValue }) => {
        const { value } = this.state;
        const sliceIndex = value.lastIndexOf('{{') + 2;
        const currentVal = value.slice(0, sliceIndex);
        const newValue = currentVal.concat(suggestionValue) + '}}';
        this.setState({ value: newValue });
    };

    const inputProps = {
        value: this.state.value,
        onChange: this.onChange,
    };

    render() {
        return (
            <Autosuggest
                suggestions={this.state.suggestions}
                onSuggestionSelected={this.onSubjectSuggestionSelected}
                onSuggestionHighlighted={this.onSubjectSuggestionHighlighted}
                onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
                onSuggestionsClearRequested={this.onSuggestionsClearRequested}
                getSuggestionValue={getSuggestionValue}
                renderSuggestion={renderSuggestion}
                inputProps={inputProps}
            />
        )
   }

This lets me type something like This is some text with a {{ and have autocomplete pop up, upon choosing a selection it should go to This is some text with a {{person.name}}.
The only problem here is that it requires the final two characters in the input to be {{ (or whatever your token is) for the autocomplete box to come up. I'm still playing with cursor movement and slicing the string around in different ways so if I edit a template thats not at the end the box still pops up.
Hopefully this helps.

A: You can try react-predictive-text


text:
Q: cp copy command with bash brace expansion at the bash prompt I can perform this copy
cp file.txt test1.txt
but if I try to copy file.txt to several files like so
cp file.txt test{2..4}.txt

I get error

cp: target `test4.txt' is not a directory

A: Well, you have to understand how *nix shells work.
In the DOS/Windows world, wildcards are handled by the programs. Thus, xcopy *.txt *.bak, for instance, means xcopy is given 2 parameters: *.txt and *.bak. How the wildcards are interpreted fully depends on xcopy.
In the *nix world, wildcards are handled by the shell. A similar command xcopy *.txt *.bak, for instance, gets expanded first becoming xcopy <list of files ending with .txt> <list of files ending with .back>. Thus assuming the existence of file1.txt to file4.txt, plus another file old.bak, the command will be expanded to xcopy file1.txt file2.txt file3.txt file4.txt old.bak
For the cp command, it's exactly what Michael has written: If you give cp more than 2 args, the last arg must be a directory.

A: It's not about bash, it's about cp. If you supply cp with more than two parameters the last one should be a directory to which all others are to be copied.
for f in test{2..4}.txt ; do cp file.txt $f ; done


text:
Q: How to parse bitcoin blockchain blkxxxxx.dat files, especially transaction parts I have tried pyblockchain package from emcpow2. But this package seems just return header information. What I really need is the transaction scripts and address. As in the picture shows, there is no transaction scripts method
Is there any other way enter image description hereto parse blkxxxxx.dat files or am I using this package incorrectly?
Thanks in advance

A: Just parse as:
      for transaction in block.transactions:
          for output in transaction.outputs:
              for addr in output.addresses:
                  print(addr.address)

A: It is not recommended to read binary files directly, because there should be a change in the binary format.
Alternatively, please use REST API instead.
$ curl http://localhost:8332/rest/blockhashbyheight/1.json
$ curl http://localhost:8332/rest/block/00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048.json


text:
Q: What is the difference between crossinline and noinline in Kotlin?
*

*This code compiles with a warning (insignificant performance impact):
inline fun test(noinline f: () -> Unit) {
    thread(block = f)
}

*This code does not compile (illegal usage of inline-parameter):
inline fun test(crossinline f: () -> Unit) {
    thread(block = f)
}

*This code compiles with a warning (insignificant performance impact):
inline fun test(noinline f: () -> Unit) {
    thread { f() }
}

*This code compiles with no warning or error:
inline fun test(crossinline f: () -> Unit) {
    thread { f() }
}

Here are my questions:

*

*How come (2) does not compile but (4) does?

*What exactly is the difference between noinline and crossinline?

*If (3) does not generates a no performance improvements, why would (4) do?

A: From the inline functions reference:

Note that some inline functions may call the lambdas passed to them as parameters not directly from the function body, but from another execution context, such as a local object or a nested function. In such cases, non-local control flow is also not allowed in the lambdas. To indicate that, the lambda parameter needs to be marked with the crossinline modifier

Hence, example 2. doesn't compile, since crossinline enforces only local control flow, and the expression block = f violates that. Example 1 compiles, since noinline doesn't require such behavior (obviously, since it's an ordinary function parameter).
Examples 1 and 3 do not generate any performance improvements, since the only lambda parameter is marked noinline, rendering the inline modifier of the function useless and redundant - the compiler would like to inline something, but everything that could be has been marked not to be inlined.
Consider two functions, A and B
A
inline fun test(noinline f: () -> Unit) {
    thread { f() }
}

B
fun test(f: () -> Unit) {
    thread { f() }
}

Function A behaves like function B in the sense that the parameter f will not be inlined (the B function doesn't inline the body of test whereas in the A function, the body: thread { f() } still gets inlined).
Now, this is not true in the example 4, since the crossinline f: () -> Unit parameter can be inlined, it just cannot violate the aforementioned non-local control flow rule (like assigning new value to a global variable). And if it can be inlined, the compiler assumes performance improvements and does not warn like in the example 3.

A: Let me try to explain this by example: I'll go through each of your examples and describe what it orders the compiler to do. First, here's some code that uses your function:
fun main(args: Array<String>) {
    test {
        println("start")
        println("stop")
    }
}

Now let's go through your variants. I'll call the functions from your examples test1..test4 and I'll show in pseudocode what the above main function would compile into.
1. noinline, block = f
This code compiles with a warning (insignificant performance impact)
inline fun test1(noinline f: () -> Unit) {
    thread(block = f)
}

fun compiledMain1() {
    val myBlock = {
        println("start")
        println("stop")
    }
    thread(block = myBlock)
}

First, note there's no evidence of inline fun test1 even existing. Inline functions aren't really "called": it's as if the code of test1 was written inside main(). On the other hand, the noinline lambda parameter behaves same as without inlining: you create a lambda object and pass it to the thread function.
2. crossinline, block = f
This code does not compile (illegal usage of inline-parameter)
inline fun test2(crossinline f: () -> Unit) {
    thread(block = f)
}

fun compiledMain2() {
    thread(block =
        println("start")
        println("stop")
    )
}

I hope I managed to conjure what happens here: you requested to copy-paste the code of the block into a place that expects a value. It's just syntactic garbage. Reason: with or without crossinline you request that the block be copy-pasted into the place where it's used. This modifier just restricts what you can write inside the block (no returns etc.)
3. noinline, { f() }
This code compiles with a warning (insignificant performance impact)
inline fun test3(noinline f: () -> Unit) {
    thread { f() }
}

fun compiledMain3() {
    val myBlock = {
        println("start")
        println("stop")
    }
    thread { myBlock() }
}

We're back to noinline here so things are straightforward again. You create a regular lambda object myBlock, then you create another regular lambda object that delegates to it: { myBlock() }, then you pass this to thread().
4. crossinline, { f() }
This code compiles with no warning or error
inline fun test4(crossinline f: () -> Unit) {
    thread { f() }
}

fun compiledMain4() {
    thread {
        println("start")
        println("stop")
    }
}

Finally this example demonstrates what crossinline is for. The code of test4 is inlined into main, the code of the block is inlined into the place where it's used. But, since it's used inside the definition of a regular lambda object, it can't contain non-local control flow.
About the Performance Impact
The Kotlin team wants you to use the inlining feature sensibly. With inlining the size of the compiled code can explode dramatically and even hit the JVM limits of up to 64K bytecode instructions per method. The main use case is higher-order functions that avoid the cost of creating an actual lambda object, only to discard it right after a single function call which happens right away.
Whenever you declare an inline fun without any inline lambdas, inlining itself has lost its purpose. The compiler warns you about it.

A: To the first and second question

How come (2) does not compile but (4) does?.. difference between noinline and crossinline

2. inline fun test(crossinline f: () -> Unit) {
    thread(block = f)
}

4. inline fun test(crossinline f: () -> Unit) {
    thread { f() }
}

Both cases have inline modifier instructing to inline both the function test and its argument lambda f. From kotlin reference:

The inline modifier affects both the function itself and the lambdas
  passed to it: all of those will be inlined into the call site.

So the compiler is instructed to place the code (inline) instead of constructing and invoking a function object for f. crossinline modifier is only for inlined things: it just says that the passed lambda (in f parameter) should not have non-local returns (which "normal" inlined lambdas may have).  crossinline can be thought of as something like this (instruction to the compiler ): " do inline but there is a restriction that it is crossing the invoker context and so make sure the lambda does not have non-local returns.
On a side note, thread seems like a conceptually illustrative example for crossinline because obviously returning from some code (passed in f) later on a different thread cannot possibly affect the return from test, which continues to execute on the caller thread independently from what it spawned (f goes on to execute independently)..
In case #4, there is a lambda (curly braces) invoking f(). In case #2, f is passed directly as an argument to thread
So in #4, call f() can be inlined and the compiler can guarantee there is no non-local return. To elaborate, the compiler would replace f() with its definition and that code is then "wrapped" inside the enclosing lambda, in other words, { //code for f() } is sort of another (wrapper) lambda and it itself is further passed as a function object reference (to thread).
In case #2, the compiler error simply says it cannot inline f because it is being passed as a reference into an "unknown" (non-inlined) place. crossinline becomes out of place and irrelevant in this case because it could be applied only if f were inlined.
To sum up, case 2 and 4 are not the same by comparing to the example from the kotlin reference (see "Higher-Order Functions and Lambdas"): below invocations are equivalent, where curly braces (lambda expression) "replace" the wrapper function toBeSynchronized
//want to pass `sharedResource.operation()` to lock body
fun <T> lock(lock: Lock, body: () -> T): T {...}
//pass a function
fun toBeSynchronized() = sharedResource.operation()
val result = lock(lock, ::toBeSynchronized)
//or pass a lambda expression
val result = lock(lock, { sharedResource.operation() })

Case #2 and #4 in the question are not equivalent because there is no "wrapper" invoking f in #2

A:
Q1: How come (2) does not compile but (4) does?

From their doc:

Inlinable lambdas can only be called inside the inline functions or passed as inlinable arguments...

Answer:
The method thread(...) is not an inline method so you won't be able to pass f as an argument.

Q2: What exactly is the difference between noinline and crossinline?

Answer:
noinline will prevent the inlining of lambdas. This becomes useful when you have multiple lambda arguments and you want only some of the lambdas passed to an inline function to be inlined.
crossinline is used to mark lambdas that mustn't allow non-local returns, especially when such lambda is passed to another execution context. In other words, you won't be able to do a use a return in such lambdas. Using your example:
inline fun test(crossinline f: () -> Unit) {
    thread { f() }
}

//another method in the class
fun foo() {

    test{

       //Error! return is not allowed here.
       return
    }

}

Q3: If (3) does not generates a no performance improvements, why would (4) do?

Answer:
That is because the only lambda you have in (3) has been marked with noinline which means you'll have the overhead cost of creating the Function object to house the body of your lamda. For (4) the lambda is still inlined (performance improvement) only that it won't allow non-local returns.


text:
Q: How i can compile my project including jar files I am trying to compile my java project by including some .jar files that are imported into the SearchEngine class, but when trying to use the command below, the imports in SearchEngine class, such as the Query class and the jar import as well, are not found. What is the correct way to compile this project considering the import dependency between classes and the inclusion of jar files?
obs: I already compile the other classes like Query
The current folders structure
my command:
javac -Xlint -classpath ".:jackson/*.jar" engine/SearchEngine.java

error output


text:
Q: Why newly released package version is not available in Partner Security Portal scanner? We have released a new minor 2GMP release version and try to check it for Security and Quality rules in Partner Security Portal scanner, but the new version doesn't show up in the picklist for Select Package Version ID to scan:.
We have create a new beta version for the future release and this version is shown in the picklist, but the released version and the previous beta version is not shown.
Why is this not shown?
The latest available package version build number is 32, while the released version build number is 34.
I can't find anything in documentation here or here to explain this.

A: My client has opened a case in Salesforce support.
Meanwhile I have some conjectures.
There were no changes between the beta version 33 and released version 34 and there were only LWC changes between version 32 and version 33.
Since Checkmarx scanner verifies only Apex, this might be the reason for the package version not showing up in the checkmarx scanner, since there were no Apex changes between versions 32 through 34.
Still need to confirm this conjecture with Salesforce Support.


text:
Q: pandas read csv use delimiter for a fixed amount of time Suppose I have a log file structured as follow for each line:
$date $machine $task_name $loggedstuff

I hope to read the whole thing with pd.read_csv('blah.log', sep=r'\s+'). The problem is, $loggedstuff has spaces in it, is there any way to limit the delimiter to operate exactly 3 times so everything in loggedstuff will appear in the dataframe as a single column?
I've already tried using csv to parse it as list of list and then feed it into pandas, but that is slow, I'm wondering if there's a more direct way to do this. Thanks!

A: Setup
tmp.txt
a b c d
1 2 3 test1 test2 test3
1 2 3 test1 test2 test3 test4

Code
df = pd.read_csv('tmp.txt', sep='\n', header=None)
cols = df.loc[0].str.split(' ')[0]
df = df.drop(0)

def splitter(s):
    vals = s.iloc[0].split(' ')
    d = dict(zip(cols[:-1], vals))
    d[cols[-1]] = ' '.join(vals[len(cols) - 1: ])
    return pd.Series(d)

df.apply(splitter, axis=1)

returns
   a  b  c                        d
1  1  2  3        test1 test2 test3
2  1  2  3  test1 test2 test3 test4

A: When using expand=True, the split elements will expand out into separate columns.
Parameter n can be used to limit the number of splits in the output.
Details about the same cane From pandas.Series.str.split
Pattern to use

df.str.split(pat=None, n=-1, expand=False)
  expand : bool, default False
Expand the splitted strings into separate columns.
If True, return DataFrame/MultiIndex expanding dimensionality.
If  False, return Series/Index, containing lists of strings

df.str.split(' ', n=3, expand=True)

A: I think you can read each line of the csv file as a single string, then convert the resulted dataframe to 3 columns by regular expression.
df = pd.read_csv('./test.csv', sep='#', squeeze=True)
df = df.str.extract('([^\s]+)\s+([^\s]+)\s+(.+)')

in which you can change the separator to whatever not appeared in the document.


text:
Q: php usort deep-nested subarray optimization Ok Gurus,
In searching the web I have seen usort doing similar to my issue but nothing I found really answered this question so I am posting for advice.
I have the following array:
$details = array(
[1]=>array (
["2022-02-12"]=>array(
[0]=>array( ["IN_PUNCH"]=> int(1644927415), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644927450), ["OUT_PUNCH"]=> int(1644927471), ["PUNCH_TYP"]=>  "SJ_EJ" ),
[2]=>array( ["IN_PUNCH"]=> int(1644927946), ["OUT_PUNCH"]=> int(1644939760), ["PUNCH_TYP"]=> "SB_EB" ),
[3]=>array( ["IN_PUNCH"]=> int(1644939774), ["OUT_PUNCH"]=> int(1644942307), ["PUNCH_TYP"]=> "SJ_EJ" ),
[4]=>array( ["IN_PUNCH"]=> int(1644942317), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SB" )),
["2022-02-13"]=>array( ),
 ["2022-02-14"]=>array (
[0]=>array( ["IN_PUNCH"]=> int(1644947652), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644957123), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SJ" )
 ),
["2022-02-15"]=>array( ),
["2022-02-16"]=>array( ),
 ),
[2]=>array(
["2022-02-14"]=>array(
[0]=>array( ["IN_PUNCH"]=> int(1644947652), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "CI" ),
[1]=>array( ["IN_PUNCH"]=> int(1644957123), ["OUT_PUNCH"]=> bool(false), ["PUNCH_TYP"]=> "SJ" )
) ,
["2022-02-15"]=>array( ),
["2022-02-16"]=>array( ),
["2022-02-17"]=>array( )
 )
 )

And I have a need to sort each date sub-array by the "IN_PUNCH" field. To do so I have this:
function sortByOrder($a, $b) {
    if ($a['IN_PUNCH'] < $b['IN_PUNCH']) return -1;    // return -1 if $a is earlier
    return  $a['IN_PUNCH'] > $b['IN_PUNCH'];    // return 1 if $a is later, or 0 if equal
}

foreach($details as $a=> $b){

        foreach($b as $c => $d){
              usort($d, 'sortByOrder');
              $details[$a][$c] = $d;

    }
}

Which is doing the job, but is there a more optimized way to do this without the nested loops?

A: Though there is nothing wrong with your approach. But you can also use array_map() to achieve the same thing. Try this
$details = array_map(function($array){ // ~ outer foreach
    return array_map(function($arr){ // ~ inner foreach
        usort($arr, function($a, $b){ // ~ sortByOrder function
            $a = $a['IN_PUNCH'];
            $b = $b['IN_PUNCH'];
            return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
        });

        return $arr;
    }, $array);
}, $details);


text:
Q: Angular 2, post method to local json file I am starting to learn angular 2 and I want to add a new object in a json file, but I always have the following errors.

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

  zone.js:2164 POST http://localhost:50149/src/data.json 405 (Method Not Allowed)
   scheduleTask @   zone.js:2164
   ZoneDelegate.scheduleTask    @   zone.js:384
   onScheduleTask   @   zone.js:274
   ZoneDelegate.scheduleTask    @   zone.js:378
   Zone.scheduleTask    @   zone.js:209
   Zone.scheduleMacroTask   @   zone.js:232
   (anonymous)  @   zone.js:2188
   send @   VM45:3
   (anonymous)  @   http.umd.js:1229
   Observable.subscribe @   Observable.ts:98
   AppComponent.addb    @   app.component.ts:61
   View_AppComponent0.handleEvent_44    @   /AppModule/AppComponent/component.ngfactory.js:366
  (anonymous)   @   platform-browser.umd.js:3221
   ZoneDelegate.invokeTask  @   zone.js:398
   onInvokeTask @   core.umd.js:4426
   ZoneDelegate.invokeTask  @   zone.js:397
   Zone.runTask @   zone.js:165
   ZoneTask.invoke  @   zone.js:460

The service class:
 @Injectable()
export class AppServices {

    constructor(public http: Http){}

    headers = new Headers({

        'Content-Type': 'application/json',
        'Accept': 'application/json'
    });

    public getJSON(): Observable<any> {
        return this.http.get("data.json")
            .map((res: any) => res.json())
            .catch((error: any) => console.log(error));
    }

    public add(body: any): Observable<any> {
        let options = new RequestOptions({
            method: RequestMethod.Post,
            headers: this.headers,
            body: JSON.stringify(body),
            url: "data.json"
        });
        return this.http.request(new Request(options))
    }
}

The method get doesn't give any error, the problem is with methods post and put, the ones that modify the file json.


text:
Q: Python create Ordered Dict with 30 most recent day keys Hello I'm writing a Django application that reports on daily items purchased.
I want to organize the data in a dictionary structure like so..
monthly_items = {
    "Apr-27" : [ list of objects purchased on April-27th ]
    "Apr-26" : [ list of objects purchased on April-26th ]
    "Apr-25" : [ list of objects purchased on April-25th ]
    "Apr-24" : [ list of objects purchased on April-24th ]
    ...
    "Mar-27" : [ list of objects purchased on March-27th ]
}

right now my code looks like this (start_date and end_date are configured for last month and today, respectively):
month_dict = {
    1: 'Jan',
    2: 'Feb',
    3: 'Mar',
    4: 'Apr',
    5: 'May',
    6: 'June',
    7: 'July',
    8: 'Aug',
    9: 'Sept',
    10: 'Oct',
    11: 'Nov',
    12: 'Dec',
}

from collections import OrderedDict
monthly_items = OrderedDict()

# pull items from last 30 days
items = Item.objects.filter(create_date__gte=start_date, create_date__lt=end_date).order_by('-create_date')

for item in items:
    day = str(month_dict.get(item.create_date.month)) + '-' + str(item.create_date.day)
    day_items = monthly_items.get(day, [])
    day_items.append(item)

this works great, and I get the dictionary structure that I want, but my problem is that if there are no items purchased on April 24th, there will be no key in the dictionary, and when I print my dict to html, I am missing a Apr-24 column when in reality, I want one but with an empty list. Is there a way to pre-populate an ordered dict with the 30 most recent days  as keys (with compatibility to cross months)?


text:
Q: Lenovo e520 won't start with new hard disk I use my e520 Lenovo laptop with Ubuntu since several years.
I bought a new hard disk (SEAGATE 2 TB Firecuda) and inserted into my laptop.
I booted via usb stick with an Ubuntu 17.04 iso and installed Ubuntu on my new internal hard disk.
Until here everything worked fine. I shut down the laptop, removed the usb stick and tried to boot.
But I only see the splash screen of Lenovo, but it hangs there.
I enabled "diagnostic" view in the bios, but still no error message or other hint to what could be wrong here.
Is the bios unable to access such a big hard disk (2 TByte)?
root@ubuntu:~# gdisk -l /dev/sda
GPT fdisk (gdisk) version 1.0.1

Partition table scan:
  MBR: MBR only
  BSD: not present
  APM: not present
  GPT: not present

***************************************************************
Found invalid GPT and valid MBR; converting MBR to GPT format
in memory.
***************************************************************

Disk /dev/sda: 3907029168 sectors, 1.8 TiB
Logical sector size: 512 bytes
Disk identifier (GUID): E118E296-B60A-4D65-8729-98F0508AC202
Partition table holds up to 128 entries
First usable sector is 34, last usable sector is 3907029134
Partitions will be aligned on 2048-sector boundaries
Total free space is 2157 sectors (1.1 MiB)

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048      3907028991   1.8 TiB     8300  Linux filesystem

A: I found a solution to get the new disk work.
I booted with the Ubuntu 17.04 iso via usb stick.
sudo bash
mount /dev/sda1 /mnt  # sda1 is the new installation which did not boot
cd /mnt/
mount -t proc proc proc/
mount -t sysfs sys sys/
mount -o bind /dev dev/
chroot .
grub-install
update-grub
exit # exit chroot
reboot


text:
Q: Adaptive Server requires encryption of the login password on the network in Oracle SQL Developer Tool I am getting error while connecting to my database in Oracle SQL developer tool
"Adaptive Server requires encryption of the login password on the network"

Can any paramater be set in the tool to fix it out or any other suggestions ?

A: Maybe look at this link which all the possible parameters:
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc39001.0605/html/prjdbc/prjdbc14.htm
Most likely you need
ENCRYPT_PASSWORD=true

A: net password encryption reqd
the default value is 0
if set to 2
then maybe the error reported in your case

A: we should pass the ENCRYPT_PASSWORD=true:
example python:
import glob
driver_name='com.sybase.jdbc4.jdbc.SybDriver'
driverpath=r"C:\Users\RameshPonnusamy\AppData\Roaming\DBeaverData\drivers\drivers\sybase\jconnect\jconn4.jar"
import jaydebeapi
jclassname=driver_name
url="jdbc:sybase:Tds:{h}:{pr}".format(h=host,pr=port,db=database)
driver_args={'user': username, 'password':password,
                 'database': database,
                 'ENCRYPT_PASSWORD':'true'}
jars=glob.glob(driverpath)
conn = jaydebeapi.connect(jclassname=jclassname,url=url, driver_args=driver_args, jars=jars)

If you are using IDE(Ex:Dbeaver)
Update  ENCRYPT_PASSWORD parameter as true
right click on connection
 -->edit_connection(if it is already saved)
    -->Driver Properties-->click on value column cell of ENCRYPT_PASSWORD
    ***type true*** and click ok


text:
Q: react-google-maps: how to use fitBounds API in the parent component I reproduce my issue in this live demo:
https://codesandbox.io/s/p3yv83o7x7
Simple speaking, in the following code:
class MapWrapper extends React.Component {
  constructor() {
    super();
    this.state = {
      zoom: 8,
      strictMode: false
    };
    this.mapRef = null;

    this.onMapMounted = this.onMapMounted.bind(this);
    this.setZoom = this.setZoom.bind(this);
    this.setStrictMode = this.setStrictMode.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  setZoom() {
    this.setState({ zoom: this.mapRef.getZoom() });
  }

  onMapMounted(ref) {
    this.mapRef = ref;
  }

  setStrictMode(e) {
    this.setState({ strictMode: e.target.checked });
  }

  handleClick() {
    // Here I want the map fit a new bound
    // With mapRef reference I can call fitBounds, it ok
    // But how I can create a new bounds object with new google.map.LatLngBounds()?
    // how I can access google lib here?
    //this.mapRef.fitBounds()
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>abc</button>
        <MyMapComponent
          isMarkerShown={this.state.zoom < 10}
          onZoomChanged={this.setZoom}
          onMapMounted={this.onMapMounted}
          zoom={this.state.zoom}
        />
      </div>
    );
  }
}

my confusing point is marked in the handleClick function as comment. In this callback function, I want to use the google map mapRef reference to  call fitBounds API. But in order to run this API, I need to make a new LatLngBounds object with new google.map.LatLngBounds(). But how I can access google lib in the parent component? That's my confusing point

A: Try creating a new LatLngBounds object with new window.google.map.LatLngBounds()


text:
Q: Avoid text to push a div placement in CSS I have a text that will dynamically change length and when the length increase, it pushes the div to the right for it further to the right. What I want is to make sure the text length is not affecting the div on the right, not pushing it. The text start out with one char and will not be longer than two char.
In the picture below I tried to illustrate the problem first, and how I want it to look second.

#hjertePic {
position: relative;
margin-top: 29%;
margin-right: 26%;
float: right;
margin-left: 25%;
}

#heartCount {
position: relative;
float: left;
margin-top: 5%;
margin-left: 20%;
margin-right: 5%;
font-size: 100px;
color: white;
text-align: center;
}

heartCount is the text and hjertePic is the div I don´t want to move. Appreciate all the help I can get. :)

A: You might want to use display: inline-block and a fixed width for the div containing number:

.row .number, .row .text {
  display: inline-block;
}

.row .number {
  width: 20px;
}

1

DIV

2

DIV

13

DIV


text:
Q: testing private before filter that relies on request body in rspec I have the following controller:
class ApiController < ApplicationController
  before_filter :authenticate_user_from_token!

  private
    def authenticate_user_from_token!
      @json = JSON.parse(request.body.read)
      --auth logic goes here extracting user credentials goes here--
      request.body.rewind
      if auth_valid
         authenticate
      else
         render nothing: true, status: :unauthorized
      end
    end
end

Testing this method has proven to be surprisingly difficult. I have tried the following approaches:
1) Sending the private method directly:
 @controller.send(authenticate_user_from_token!)

The flaw here, is that I am unsure how to mock out request.body to contain valid/invalid credentials. I have tried the following:
 before do
    class Hash
       def body
          self['body']
       end
    end
    @request = {}
    @request['body'] =StringIO.new({auth_goes_here}.to_json)
 end

However, in the method, request still gets overriden with a brand new ActionController::TestRequest.
2) Posting directly:
before do
  post :authenticate_user_from_token!, my_preconstructed_credentials, format: :json
end

which results in:
 *** AbstractController::ActionNotFound Exception: The action 'authenticate_user_from_token!' could not be found for ApiController

3) Defining an exposed method at runtime:
  before do
    @controller.class_eval <<-RUBY_EVAL
      public
        def update
        end
    RUBY_EVAL
  end

followed by post :update, which still results in *** NoMethodError Exception: undefined methodfoobar' for #`
My question is: how can I test a private before filter on a controller that depends on request.body? I realize I could mock out request and body in my third approach, but I would still require it to respond to read/rewind. How is this kind of method usually tested?

A: In the end, the following worked:
before do
   class ::TestApiController < ApiController
      def hello
         render nothing: true
      end
   end

   Rails.application.routes.draw do
      match 'hello', to: 'test_api#hello'
   end
   @controller = TestApiController.new
   @request.env['RAW_POST_DATA'] = my_awesome_json
   post :hello
 end


text:
Q: Avoiding coupling with Strategy pattern I am attempting to apply the Strategy pattern to a particular situation, but am having an issue with how to avoid coupling each concrete strategy to the context object providing data for it. The following is a simplified case of a pattern that occurs a few different ways, but should be handled in a similar way.
We have an object Acquisition that provides data relevant to a specific frame of time - basically a bunch of external data collected using different pieces of hardware. It's already too large because of the amount of data it contains, so I don't want to give it any further responsibility. We now need to take some of this data, and based on some configuration send a corresponding voltage to a piece of hardware.
So, imagine the following (much simplified) classes:
class Acquisition
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
}

interface IAnalogOutputter
{
    double getVoltage(Acquisition acq);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(Acquisition acq)
    {
        return acq.Battery;
    }
}

Now, every concrete strategy class has to be coupled to my Acquisition class, which is also one of the most likely classes to be modified since it's core to our application. This is still an improvement over the old design, which was a giant switch statement inside the Acquisition class. Each type of data may have a different conversion method (while Battery is a simple pass-through, others are not at all that simple), so I feel Strategy pattern or similar should be the way to go.
I will also note that in the final implementation, IAnalogOutputter would be an abstract class instead of an interface. These classes will be in a list that is configurable by the user and serialized to an XML file. The list must be editable at runtime and remembered, so Serializable must be part of our final solution. In case it makes a difference.
How can I ensure each implementation class gets the data it needs to work, without tying it to one of my most important classes? Or am I approaching this sort of problem in the completely wrong manner?

A: Strategy Pattern encapsulates a - usually complex - operation/calculation.
The voltage you want to return is dependent on

*

*pieces of configuration

*Some of the acquisition data

So I would put these into another class and pass it to strategy implementors.
Also in terms of serialisation, you do not have serialise the strategy classes, perhaps only their name or type name.

UPDATE
Well, it seems that your implementations need only one piece of the acquisition data. That is a bit unusual for a strategy pattern - but I do not believe it fits Visitor better so strategy is fine. I would create a class which has as property, acquisition data (perhaps inherits from it) in addition to configuration that implementors need.

A: One thing you could do is use factory methods to construct your Strategies. Your individual strategies can take in their constructor only the individual data elements they need, and the factory method is the only thing that needs to know how to fill in that data given an Acquisition object. Something like this:
public class OutputterFactory
{
    public static IAnalogOutputter CreateBatteryAnalogOutputter(Acquisition acq)
    {
        return new BatteryANalogOutputter(acq.Battery);
    }

}

A: Ok, I hate to not give someone else the credit here, but I found a hybrid solution that works very well for my purposes. It serializes perfectly, and greatly simplifies the addition of new output types. The key was a single interface, IOutputValueProvider. Also note how easily this pattern handles the retrieval of varying ways of storing the data (such as a Dictionary instead of a parameter).
interface IOutputValueProvider
{
    Double GetBattery();
    Double GetSignal();
    Int32 GetIntegrationTime();
    Double GetDictionaryValue(String key);
}

interface IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetBattery();
    }
}

class DictionaryValueOutputter : IAnalogOutputter
{
    public String DictionaryKey { get; set; }
    public double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetDictionaryValue(DictionaryKey);
    }
}

So then, I just need to ensure Acquisition implements the interface:
class Acquisition : IOutputValueProvider
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
    public Dictionary<String, Double> DictionaryValues;

    public double GetBattery() { return Battery;}
    public double GetSignal() { return Signal; }
    public int GetIntegrationTime() { return IntegrationTime; }
    public double GetDictionaryValue(String key)
    {
        Double d = 0.0;
        return DictionaryValues.TryGetValue(key, out d) ? d : 0.0;
    }
}

This isn't perfect, since now there's a gigantic interface that must be maintained and some duplicate code in Acquisition, but there's a heck of a lot less risk of something being changed affecting the other parts of my application. It also allows me to start subclassing Acquisition without having to change some of these external pieces. I hope this will help some others in similar situations.


text:
Q: Testng split dataProvider between parallel methods I have a dataProvider which is reading the data from a text file.
@DataProvider (name = "dynamicDP", parallel = true)
    public Iterator<Object> matchIDs() throws IOException {
      final List<Object> list = new ArrayList<>();

        for (final String line: Files.readAllLines(Paths.get("C:\\mypath"),
            StandardCharsets.UTF_8))
            list.add(new Object[]{ line});

        return list.iterator();
}

My text file is really simple it only contains these data below (each pair of letters on a separate line):

AA BB CC DD EE FF GG HH II KK

Here is my test class:
public class dataProviderParallelTest {

 @Test (dataProvider="dynamicDP")
 public void verifyDPdata(String comingFromDP){
 System.out.printf("%nDP#1..: "+comingFromDP);
 }

 @Test (dataProvider="dynamicDP")
 public void verifyDPdata2(String comingFromDP){
 System.out.printf("%nDP#2..: "+comingFromDP);
 }
}

Here is the output:
[TestNG] Running:
  C:\projects\test\currentTest.xml

DP#1..: AA
DP#2..: BB
DP#1..: BB
DP#2..: AA
DP#1..: CC
DP#2..: CC
DP#1..: DD
DP#1..: EE
DP#2..: EE
DP#2..: DD
DP#1..: FF
DP#2..: FF
DP#1..: GG
DP#1..: HH
DP#2..: HH
DP#2..: GG
DP#1..: II
DP#2..: II
DP#1..: KK
DP#2..: KK
===============================================
Regression
Total tests run: 20, Failures: 0, Skips: 0
===============================================

And here is my XML file that I'm using to start my test:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Regression" parallel="methods" thread-count="2" data-provider-thread-count="2">

    <test name="smokeTest11">
        <classes>
        <class name="regression.bo.dataProviderParallelTest"/>
        </classes>
    </test>

</suite>

What I have tried:
I've read this article: cedricBlog
and this stackoverflow post:stackOverFlow
What am I trying to achieve:
I am trying to share the data between the two threads. At the moment I just achieved both of the threads to execute the same data provided by the DP. My aim is to split the data between the two methods and have an output like this (DP data shared between the 2 methods):
DP#1..: AA
DP#2..: BB
DP#1..: DD
DP#2..: EE
DP#1..: CC
DP#2..: GG
DP#1..: KK
DP#1..: HH
DP#2..: II
DP#2..: FF

Is this even possible or am I missing something? Thanks in advance for your help!

A: Take the method as parameter to your dataprovider.  Divide your data in two lists, whichever way you like.  Based on method name, return one list to each.
eg.
For example, the following code prints the name of the test method inside its @DataProvider:
@DataProvider(name = "dynamicDP", parallel = true)
public Object[][] dynamicDP(Method m) {
  System.out.println(m.getName());
  //Divide list in two lists
  if (m.getName().equals("Met1")
     return list1
  else
     return list2
}

@Test(dataProvider="dynamicDP")
public void test1(String s) {
}

@Test(dataProvider="dynamicDP")
public void test2(String s) {
}

HTH

A: Okay, posting and my solution for reference. In short it is this. Count the lines in the file, and start reading 1 line at a time (from 10 different threads) until you reach the EOF. Here it is:
  public volatile int currentLine=0;
  public static Object writeLock = new Object();
  public static Object readLock = new Object();
  public long currentThread =  Thread.currentThread().getId();

 @Test(invocationCount = 50)
  public void readOneLineGetID() throws IOException{

  countLines();
  if(currentLine==noOfLines){throw new SkipException("%nSkipping this test method as we got all the records we need.");}
  long threadID = Thread.currentThread().getId();

    synchronized(readLock){
         if(currentLine<noOfLines){
        System.out.printf("%nCurrent thread is..: "+ threadID);
         readASpecificLineFromATextFile(currentLine);
         System.out.printf("%n----------------------------------------------------------");
         }
     }

     synchronized(writeLock){
     currentLine++;
     }

  }

So I have 10 of these methods and I am pushing my tests concurrently onto a grid hub which then uses 10 different data providers to feed the nodes.
Only, minor point is the invocationCount (ideally i should divide by 10 and then set the invocation count on every single method accordingly; but as I don't have time to re-invent the wheel and this runs very very fast (only dealing with 200 line files normally, I decided to skip the rest of methods after the line number reaches EOF ;) )
Here is the output (10 methods, with 50 invocation count finding 10 mockup lines from my file and skipping the rest):

After some tinkering with the sync, beatiful!!! :)


text:
Q: Wix v3.5 install instances of Windows service I've been trying to write a Wix installer which is capable of installing multiple instances of a Windows Service side by side. I am using WIX v3.5 (can't upgrade due to other issues).
The following Product.wxs works to install either the default instance or Instance1. When attempting to install one of the instances when the other is already installed, the installer runs and exists without giving any errors but nothing is installed.
Does anybody have any advice?
Thank you!
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <?if $(var.Platform) = x64 ?>
    <?define ProductId = "FC66F94F-A3B8-4435-8F7F-B9A19D773871" ?>
    <?define ProductName = "MCSS FTP Notification Worker (64 bit)" ?>
    <?define Win64 = "yes" ?>
    <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
    <?define PlatformPath = "x64"?>
  <?elseif $(var.Platform) = ia64 ?>
    <?define ProductId = "4068DAB4-8480-41BA-B0BB-7CBE4B5C2320" ?>
    <?define ProductName = "MCSS FTP Notification Worker (64 bit)" ?>
    <?define Win64 = "yes" ?>
    <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
    <?define PlatformPath = "ia64"?>
  <?else ?>
    <?define ProductId = "38F55942-579B-4617-9352-4A8FBEF3E491" ?>
    <?define ProductName = "MCSS FTP Notification Worker" ?>
    <?define Win64 = "no" ?>
    <?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
    <?define PlatformPath = "x86"?>
  <?endif ?>

  <Product Id="$(var.ProductId)"
       Name="$(var.ProductName)"
       Language="1033"
       Version="!(bind.FileVersion.NotificationWorkerExe)"
       Manufacturer="Company"
       UpgradeCode="54982507-16ae-4f38-b887-605576b58c09">
    <Package InstallerVersion="200"
         Compressed="yes"
         Manufacturer="Company"
         Description="$(var.ProductName)"
         Keywords="SSO,MasterCustomer,NotificationWorker,MSI"
         Comments="(c) 2013 Company"
         Platform="$(var.PlatformPath)"/>

    <Condition Message='.NET Framework 4.0 must be installed prior to installation of this product.'>
  MsiNetAssemblySupport >= "4"
    </Condition>

    <Property Id="INSTANCENAME" Value="Instance0" />

    <Property Id="ARPCOMMENTS" Value="Company" />
    <Property Id="ARPCONTACT" Value="Contact" />

    <!-- No repair or modify in Add/Remove Programs-->
    <Property Id="ARPNOMODIFY" Value="0" />
    <Property Id="ARPNOREPAIR" Value="0" />

    <InstanceTransforms Property="INSTANCENAME">
      <Instance Id="Instance1" ProductCode="773476D9-6A5D-49DA-9762-3FDF3822E9B6" ProductName="Inst1 Worker"/>
    </InstanceTransforms>

<Media Id="1" Cabinet="media1.cab" EmbedCab="yes" />

    <Directory Id="TARGETDIR" Name="SourceDir">
  <Directory Id="$(var.PlatformProgramFilesFolder)">
        <Directory Id="BaseDir" Name="Base">
          <Directory Id="INSTALLLOCATION">
            <Component Id="CreateEventSource64BitFullNet4" Guid="82A6A90A-E889-4C9A-ADF2-07C539198800" Win64="$(var.Win64)">
              <CreateFolder/>
              <!-- Create an Event Source -->
              <Util:EventSource
                    xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension"
                    Name="MasterCustomer"
                    Log="LogName"
                EventMessageFile="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll" />
            </Component>
            <Component Id="RemoveFiles" Guid="BFF360CF-3625-49C8-98E3-DE9632489A80" Win64="$(var.Win64)">
              <RemoveFile Id="PurgeFolder" Name="*.*" On="uninstall" />
            </Component>
            <!-- Registry keys -->
            <Component Id="RegistryEntries" Guid="*">
              <RegistryKey Root="HKLM"
                       Key="Software\Company\MC\[INSTANCENAME]NotificationWorker"
                       Action="createAndRemoveOnUninstall">
                <RegistryValue Type="string" Name="Version" Value="!(bind.FileVersion.NotificationWorkerExe)"/>
                <RegistryValue Type="string" Name="InstallLocation" Value="[INSTALLLOCATION]"/>
              </RegistryKey>
            </Component>

            <!-- Assemblies -->
            <Component Id="NLog" Guid="HJHFAA3B-4F47-46DD-9DF3-B2A61E888E87" Win64="$(var.Win64)">
              <File Id="NLog" Name="NLog.dll" Vital="yes" Source="..\packages\NLog.2.0.1.2\lib\net40\NLog.dll"/>
              <CreateFolder />
            </Component>

            <Component Id="Microsoft.Practices.TransientFaultHandling.Core" Guid="C5A67C33-B1BB-481B-9C1E-8F47676CB41E"
                   Win64="$(var.Win64)">
              <File Id="Microsoft.Practices.TransientFaultHandling.Core" Name="Microsoft.Practices.TransientFaultHandling.Core.dll"
                Vital="yes" Source="..\packages\TransientFaultHandling.Core.5.1.1209.1\lib\NET4\Microsoft.Practices.TransientFaultHandling.Core.dll"/>
              <CreateFolder />
            </Component>
            <Component Id="EntityFramework" Guid="3CD35D63-16AE-432A-BA6D-B769804B680B"
                   Win64="$(var.Win64)">
              <File Id="EntityFramework" Name="EntityFramework.dll"
                Vital="yes" Source="..\packages\EntityFramework.5.0.0\lib\net40\EntityFramework.dll"/>
              <CreateFolder />
            </Component>

            <Component Id="EntityFramework.Extended" Guid="C656CF9D-FCD3-495A-B08F-5D5BBBBA52DA"
                   Win64="$(var.Win64)">
              <File Id="EntityFrameworkExtended" Name="EntityFramework.Extended.dll"
                Vital="yes" Source="..\packages\EntityFramework.Extended.5.0.0.71\lib\net40\EntityFramework.Extended.dll"/>
              <CreateFolder />
            </Component>

            <Component Id="Ninject" Guid="93D6ACFB-45BF-4DAF-87B3-D10B450123BE"
                   Win64="$(var.Win64)">
              <File Id="Ninject" Name="Ninject.dll"
                Vital="yes" Source="..\packages\Ninject.3.0.1.10\lib\net40\Ninject.dll"/>
              <CreateFolder />
            </Component>

            <Component Id="Ploeh.AutoFixture" Guid="605611B1-349A-4E58-A321-22F059E27CB2"
                   Win64="$(var.Win64)">
              <File Id="Ploeh.AutoFixture" Name="Ploeh.AutoFixture.dll"
                Vital="yes" Source="..\packages\AutoFixture.2.16.2\lib\net35\Ploeh.AutoFixture.dll"/>
            </Component>

            <Component Id="Newtonsoft.Json" Guid="8D699222-D357-49B2-BCED-BD070E06E3C1"
                   Win64="$(var.Win64)">
              <File Id="NewtonsoftJson" Name="Newtonsoft.Json.dll" Vital="yes"
                Source="..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll"/>
            </Component>

            <Component Id="Logger"
                   Guid="F0CC2705-1AE5-4092-8648-3B32F3ADD7D6"
                   Win64="$(var.Win64)">
              <File Id="LoggerDll"
                Name="Logger.dll"
                Source="$(var.Logger.TargetDir)Logger.dll"
                KeyPath="yes" />
              <CreateFolder />
            </Component>

            <Component Id="Services.Common"
                   Guid="E2507B7D-6160-43C1-6C49-158943C75938"
                   Win64="$(var.Win64)">
              <File Id="ServicesCommonDll"
                Name="Services.Common.dll"
                Source="$(var.Services.Common.TargetDir)Services.Common.dll"
                KeyPath="yes" />
            </Component>

            <!-- For the actual service -->
            <Component Id="NotificationWorkerComponent" Guid="13E74C65-429A-490E-974D-5D3D656EB3E8" Win64="$(var.Win64)">
              <File Id="NotificationWorkerExe"
                Name="Customer.Change.NotificationWorker.exe"
                KeyPath="yes"
                Source="$(var.Customer.Change.NotificationWorker.TargetDir)Customer.Change.NotificationWorker.exe"/>
              <ServiceInstall Id="NotificationWorkerService"
                          Name="Customer.Change.[INSTANCENAME].NotificationWorker.exe"
                          DisplayName="MCSS [INSTANCENAME] Notification Worker"
                          Type="ownProcess"
                          Start="auto"
                          ErrorControl="normal"
                          Description="Notifies external systems of customer changes"
                          Vital="yes">
                <ServiceConfig DelayedAutoStart="yes" OnInstall="yes" />
              </ServiceInstall>
              <CreateFolder />
              <ServiceControl Id="StartMCSSNotificationWorker"
                          Remove="uninstall"
                          Stop="both"
                          Name="Customer.Change.[INSTANCENAME].NotificationWorker.exe"
                          Start="install"/>
            </Component>
            <Component Id="NotificationWorkerConfigComponent"
                   Guid="43474C5A-AB13-49B4-8C21-7266F74C0F44"
                   Win64="$(var.Win64)">

              <File Id="NotificationWorkerConfig"
                Name="Customer.Change.NotificationWorker.exe.config"
                Source="$(var.Customer.Change.NotificationWorker.TargetDir)Customer.Change.NotificationWorker.exe.config"
                KeyPath="yes" />
              <Util:XmlFile Id="DebugOff"
                        xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension"
                        ElementPath="//configuration/appSettings/add[\[]@key='Debug'[\]]/@value"
                        Action="setValue"
                        Value="false"
                        File="[#NotificationWorkerConfig]"/>
              <Util:XmlFile Id="SetSystem"
                        xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension"
                        ElementPath="//configuration/appSettings/add[\[]@key='SystemToNotify'[\]]/@value"
                        Action="setValue"
                        Value="[INSTANCENAME]"
                        File="[#NotificationWorkerConfig]"/>
            </Component>
          </Directory>
        </Directory>
  </Directory>
</Directory>

    <Feature Id="ProductFeature" Title="MasterCustomer" Level="1">
        <!-- TODO: Remove the comments around this ComponentRef element and the Component above in order to add resources to this installer. -->
        <!-- <ComponentRef Id="ProductComponent" /> -->

        <!-- Note: The following ComponentGroupRef is required to pull in generated authoring from project references. -->
  <Feature Id="NotificationWorkerFeature"
           Title="MCSS Notification Worker"
           Description="Installs the MCSS Notification Worker Service"
           Level="1">
    <ComponentRef Id="CreateEventSource64BitFullNet4"/>
    <ComponentRef Id="RegistryEntries"/>
    <ComponentRef Id="NLog"/>
    <ComponentRef Id="Microsoft.Practices.TransientFaultHandling.Core"/>
    <ComponentRef Id="EntityFramework"/>
    <ComponentRef Id="EntityFramework.Extended"/>
    <ComponentRef Id="Ninject"/>
    <ComponentRef Id="Newtonsoft.Json"/>
    <ComponentRef Id="Logger"/>
    <ComponentRef Id="Services.Common"/>
    <ComponentRef Id="NotificationWorkerComponent"/>
    <ComponentRef Id="NotificationWorkerConfigComponent"/>
    <ComponentRef Id="RemoveFiles"/>
  </Feature>
  <ComponentGroupRef Id="Product.Generated" />
    </Feature>
</Product>
</Wix>

A: MSI does not install your NotificationWorkerComponent because it is already installed. The decision whether to override the old version (you could not possible expect it to have same file side by side, only one version of the same component may persist), is made based on file information. In your case, it is the same component with the same GUID, and probably the same file, so nothing is installed.
I suggest using different components for each version of each file you want to have side by side.