Q: ASP.NET how to make slider for table? I have an ASP.NET table that gets lots of rows put into it. I want to have a slider to view more rows instead of making my page extremely long. This seemed like a basic task, but I cannot find any way to do this...
I would love to hear any ideas!
To be clear, my question is: how do I add a slider to my asp.net table?

A: Not sure if this will exactly fit the bill, but check out the ASP.NET Scrollable Table Server Control
Or were you asking for a slider pager control that will load more results for the user?

A: For future reference,
    .FixedHeightContainer
    {
      float:left;
      height: 350px;
      width:100%;
      padding:3px;
    }
    .Content
    {
      height:224px;
      overflow:auto;
    }

along with:

Results

        <asp:Table ID="Table1" runat="server" GridLines="Both" Height="350px" Width="80%">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell>

                </asp:TableHeaderCell>
            </asp:TableHeaderRow>
        </asp:Table>

Is what I used to create a table with a slider
Thanks for all the comments :)
Nikita Silverstruk, your comment helped so much :) thanks


Q: Difference between wic and hddimg format in yocto I have generated a core-image-minimal image for my Intel board in Yocto.
Looking into tmp/deploy/images folder they are many images.
I flashed *.wic image using dd command on USB and it created two partitions ( Boot and Platform ) and allowed only to perform a live booting without allowing it to install on the hard disk of the board.
I then flashed *.hddimg on the USB using dd command. It only created a "boot" partition which has rootfs.img, syslinux and EFI folder.
Booting using USB provided me an "Install" option, which installed on the board and when I rebooted after installing, it displays "No bootable media found"
Using bootable image there are two partitions in the hard disk. Why it is not booting..
Steps followed:

*

*Created an minimal yocto image using "bitbake core-image-minimal" command

*Flashed the USB using the dd command.

sudo dd if=tmp/deploy/images/intel-corei7-64/core-image-minimal-intel-corei7-64.hddimg of=/dev/sdb

*Clicked on install and typed “sda”

*The installation was successful and when I tried to restart by removing the USB Drive, it says “No boot options found. Please install bootable media and restart."

What is the mistake I am doing here.
Which image to choose and when..

A: There was not much info about online, so I asked this question in the intel community and here is the response of that:
Generally a .wic image is intended to be installed directly to its final destination, whereas an hddimg is for evaluation and installation elsewhere.
By default meta-intel .wic images only have an EFI bootloader, and will not boot via legacy BIOS.
An hddimg will have both an EFI bootloader and the syslinux binaries that let it boot from legacy BIOS.
On startup with your installer USB image do you get a light gray screen with four options? If so it is booting via legacy BIOS.


Q: How can I add cookies to Seaside responses without redirecting? I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?
I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.
Is there another way that already exist to add a cookie that will go out on the next response?

A: There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: http://code.google.com/p/seaside/issues/detail?id=48
This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not.
Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't so bad.
If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun.
Edited to add:
The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like:
self requestContext response addCookie: aCookie

This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.

A: I've just looked into this in depth, and the answer seems to be no.  Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's stream but not the response itself).  I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no.
That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)


Q: SymbolSource Nightmare So after hours of jumping through hoops, I have gotten SymbolSource running except I am unable to push any packages.  The error I am getting now is:
Response status code does not indicate success:
418 (Reading package metadata failed: The schema version of 'MyNugetPackage'
is incompatible with version 2.1.31002.9028 of NuGet. Please upgrade NuGet
to the latest version from See http://www.symbolsource.org/Public/Home/Help
for possible reasons. Fiddler may help diagnosing this error if your client
discards attached detailed information.).

First problem is that you can no longer download the command line version of v2.1.3 of Nuget.  I tried the the oldest version available: v2.8.6 but I get the same error.  Second problem is it looks like SymbolSource.Server.Basic hasn't been touched in 3 years.  Is this project dead?  Am I wasting my time?  I can't find any other alternative for debugging nuget packages without publishing to a third party service (which my company won't allow)?

A: The Symbol Server project master branch hasn't been touched for 4 years as of writing, and there is a queue of pull requests and issues left open for even longer.
There is an 'upgrade' branch which hasn't been touched since 2014, but that has updated NuGet version.
There is a slightly more recent fork at https://github.com/TrabacchinLuigi/SymbolSource.Community/tree/upgrade
which uses more recent versions of NuGet. Also have a look at the GitHub 'network' for other potential maintained forks: https://github.com/SymbolSource/SymbolSource.Community/network
And alternative hosting solutions include:

*

*https://inedo.com/proget

*https://github.com/GitTools/GitLink
Edit -- I got my own version running:
https://github.com/i-e-b/SymbolSourceSane


Q: Print 2 arrays into a CSV file with javascript I was following the mentioned question and this one:
JavaScript array to CSV
Trying to print 2 arrays in columns A and B which i can turn into a string separated by comas"," which ever is more easy to do but i just can´t get it to work with the examples available.
My arrays look like this:
var Test = ["John", "Ivar", "Peter", "Tony"];
var Addres = ["Canada", "Sweden", "England", "Chile"];

And in string format its the same only separated by comas
I thought it was going to be an easy task but it's more complicated than I expected
Hope anyone here can help me with this,
Thanks

A: You can accomplish it with one-liner reduce:
var Test = ["John", "Ivar", "Peter", "Tony"];
var Addres = ["Canada", "Sweden", "England", "Chile"];

var result = Test.reduce((str, name, i) => `${str}${name},${Address[i]}\n`, 'Test,Address\n');

console.log(result);


Q: Why is this C program returning correct value in VC++2008? We know that automatic variables are destroyed upon the return of the function.
Then, why is this C program returning correct value?
#include <stdio.h>
#include <process.h>

int * ReturningPointer()
{
    int myInteger = 99;

    int * ptrToMyInteger = &myInteger;

    return ptrToMyInteger;
}

main()
{
    int * pointerToInteger = ReturningPointer();

    printf("*pointerToInteger = %d\n", *pointerToInteger);

    system("PAUSE");
}

Output
*pointerToInteger = 99

Edit
Then why is this giving garbage values?
#include <stdio.h>
#include <process.h>

char * ReturningPointer()
{
    char array[13] = "Hello World!";

    return array;
}

main()
{
    printf("%s\n", ReturningPointer());

    system("PAUSE");
}

Output
x≈§

A: There is no answer to that question: your code exhibits undefined behavior. It could print "the right value" as you are seeing, it could print anything else, it could segfault, it could order pizza online with your credit card.
Dereferencing that pointer in main is illegal, it doesn't point to valid memory at that point. Don't do it.
There's a big difference between you two examples: in the first case, *pointer is evaluated before calling printf. So, given that there are no function calls between the line where you get the pointer value, and the printf, chances are high that the stack location pointer points to will not have been overwritten. So the value that was stored there prior to calling printf is likely to be output (that value will be passed on to printf's stack, not the pointer).
In the second case, you're passing a pointer to the stack to printf. The call to printf overwrites (a part of) that same stack region the pointer is pointing to, and printf ends up trying to print its own stack (more or less) which doesn't have a high chance of containing something readable.
Note that you can't rely on getting gibberish either. Your implementation is free to use a different stack for the printf call if it feels like it, as long as it follows the requirements laid out by the standard.

A: This is undefined behavior, and it could have launched a missile instead. But it just happened to give you the correct answer.
Think about it, it kind of make sense -- what else did you expect? Should it have given you zero? If so, then the compiler must insert special instructions at the scope end to erase the variable's content -- waste of resources. The most natural thing for the compiler to do is to leave the contents unchanged -- so you just got the correct output from undefined behavior by chance.
You could say this behavior is implementation defined. For example. Another compiler (or the same compiler in "Release" mode) may decide to allocate myInteger purely in register (not sure if it actually can do this when you take an address of it, but for the sake of argument...), in that case no memory would be allocated for 99 and you would get garbage output.
As a more illustrative (but totally untested) example -- if you insert some malloc and exercise some memory usage before printf you may find the garbage value you were looking for :P
Answer to "Edited" part
The "real" answer that you want needs to be answered in disassembly. A good place to start is gcc -S and gcc -O3 -S. I will leave the in-depth analysis for wizards that will come around. But I did a cursory peek using GCC and it turns out that printf("%s\n") gets translated to puts, so the calling convention is different. Since local variables are allocated on the stack, calling a function could "destroy" previously allocated local variables.

A: *

*Destroying is the wrong word imho. Locals reside on the stack, if the function returns the stack space may be reused again. Until then it is not overwritten and still accessible by pointers which you might not really want (because this might never point to something valid)

*Pointers are used to address space in memory, for local pointers the same as I described in 1 is valid. However the pointer seems to be passed to the main program.

*If it really is the address storing the former integer it will result in "99" up until that point in the execution of your program when the program overwrite this memory location. It may also be another 99 by coincidence. Any way: do not do this.
These kind of errors will lead to trouble some day, may be on other machines, other OS, other compiler or compiler options - imagine you upgrade your compiler which may change the behaviour the memory usage or even a build with optimization flags, e.g. release builds vs default debug builds, you name it.

A: In most C/C++ programs their local variables live on the stack, and destroyed means overwritten with something else. In this case that particular location had not been overwritten yet when it was passed as a parameter to printf().
Of course, having such code is asking for trouble because per the C and C++ standards it exhibits undefined behavior.

A: That is undefined behavior. That means that anything can happen, even what you would expect.
The tricky part of UB is when it gives you the result you expect, and so you think that you are doing it right. Then, any change in an unrelated part of the program changes that...
Answering your question more specifically, you are returning a pointer to an automatic variable, that no longer exists when the function returns, but since you call no other functions in the middle, it happens to keep the old value.
If you call, for example printf twice, the second time it will most likely print a different value.

A: The key idea is that a variable represents a name and type for value stored somewhere in memory. When it is "destroyed", it means that a) that value can no longer be accessed using that name, and b) the memory location is free to be overwritten.
The behavior is undefined because the implementation of the compiler is free to choose what time after "destruction" the location is actually overwritten.


Q: Code to define biological and technical replicate samples (brain twister) In my expression dataset I have various kinds or replicates, biological and technical. A biological replicate I consider if the same person was sampled at different dates. A technical replicate I consider if a sample was taken from the same person at the same date and measured either at the same or different dates.
I tried to define this by code but unfortunately im hitting a wall with trying to define technical and biological replicates.
Below is my code that defines replicates and first replicates (=index case) but for the rest it would be amazing if someone could help me. Its kind of a brain twister so kudos to anyone solving this!
Thanks a lot!
Sebastian
df<- data.frame(
  sample = c(1,2,3,4,5,6,7,8, 9, 10, 11, 12),
  individual = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "f", "d", "e"),
  date_collected = c(1.1, 1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.1, 1.1, 1.2, 1.1, 1.1),
  date_processed = c(2.1, 2.1, 2.1, 2.2, 2.1, 2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.1 ))

#differentiate biological and technical replicates
df$has_replicate <- FALSE #all that have a replicate
df$is_first_of_replicates <- FALSE #primary sample
df$is_technical_replicate_same_run <- FALSE #same sample, same date processed
df$is_technical_replicate_different_run <- FALSE #same sample,     different date processed
df$is_biological_replicate_same_run <- FALSE #same individual, different date collected, same day proc
df$is_biological_replicate_different_run <- FALSE #same individual, diff date col, dif day proc

#check all samples that have replicates = same individual (including first one)
replicates_index <- which(df$individual %in%         df$individual[which(duplicated(df$individual))])
#mark
df[replicates_index, ]$has_replicate <- TRUE

#define first samples (by checking which ones are not the first ones)
replicates_not_first_index <- duplicated(df$individual)
df[replicates_index, ]$sample #all that have replicates incl first
df[replicates_not_first_index, ]$sample #all replicates that are not first
#find replicates that are first = present in rep but not in not first
firstsIDs_ <- setdiff(df[replicates_index, ]$sample,     df[replicates_not_first_index, ]$sample)
#get index
firsts_index <- which(df$sample %in% firstsIDs_)
#mark
df[firsts_index, ]$is_first_of_replicates <- TRUE

expected output
df$is_technical_replicate_same_run # TRUE if is replicate & date.collected same & date processed is the same
df$is_technical_replicate_different_run # TRUE if is replicate & date.collected same & date processed is different
df$is_biological_replicate_same_run # TRUE if is replicate & date collected is different & date processed is the same
df$is_biological_replicate_different_run # TRUE if is replicate & date collected is different & date processed is different


Q: C# Tuple list inside class inside class not set to instance of object I'm trying to use a tuple list inside a custom class that wraps some methods from mutliple classes inside a game. I'm getting an 'object reference not set to instance of object error' just after the "ENTERED ADD METHOD A-1" is displayed in the cosole from the 1st Add method of the wrapper class. Clearly, Im not setting up the list correctly, but I can't see where the issue is. Any help would be appreciated as I'm new to working with 'classes'.
// wrappers & classes
KilledActorsWrapper KilledActors = new KilledActorsWrapper();

    public class KilledActorsWrapper
#region KilledActorsWrapper class
{
    public KilledActorsWrapper()
    {   // constructor
        if (Type.GetType("KilledActorsWrapper") == null)    // check to see if class has been initiated
        {   //class with the given name does not exist so instantiate it
            List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors =
                        new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();
            m_KilledActors.Clear();
            ConsoleWriteline("INITIALISED KILLEDACTORS LIST");
        }
        else
        {   // class with the given name exists so show an error, cannot initate the class twice
            ColoredConsoleWrite(ConsoleColor.DarkGreen, "INITIALISING KILLEDACTORS LIST FAILED");
            throw new Exception("KilledActorsWrapper class already exists. Are you typing to initiate a second instance of this class?");
        }
    }

    public void Add(AiActor killedActor, List<DamagerScore> damages)
    {
        ConsoleWriteline("ENTERED ADD METHOD A");
        Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes,
            List<DamagerScore>>(killedActor, null, NamedDamageTypes.AirbrakeDriveFailure, damages);
        ConsoleWriteline("ENTERED ADD METHOD A-1");
        m_KilledActors.Add(tuple);
        ConsoleWriteline("ENTERED ADD METHOD A-2");
    }

    public void Add(AiActor killedActor, AiDamageInitiator initiator, NamedDamageTypes damageType)
    {
        ConsoleWriteline("ENTERED ADD METHOD B");
        Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes,
            List<DamagerScore>>(killedActor, initiator, damageType, null);
        ConsoleWriteline("ENTERED ADD METHOD B-1");
        this.m_KilledActors.Add(tuple);
        ConsoleWriteline("ENTERED ADD METHOD B-2");
    }

    public int Count
    {
        get { return m_KilledActors.Count; }
    }

    public List<DamagerScore> GetDamagerScore(AiActor killedActor)
    {
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == killedActor)
            {
                return (List<DamagerScore>)m_KilledActors[i].Item1;
            }
        }
        return null;
    }

    public List<AiDamageInitiator> GetDamageInitiators(AiActor killedActor)
    {
        List<AiDamageInitiator> damageinitiators = null;
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == killedActor)
            {
                damageinitiators.Add((AiDamageInitiator)m_KilledActors[i].Item2);
            }
        }
        return damageinitiators;
    }

    public List<NamedDamageTypes> GetNamedDamageTypes(AiActor actor)
    {
        List<NamedDamageTypes> nameddamagetypes = null;
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == actor)
            {
                nameddamagetypes.Add((NamedDamageTypes)m_KilledActors[i].Item3);
            }
        }
        return nameddamagetypes;
    }

    public void Clear()
    {
        m_KilledActors.Clear();
    }
    private List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors { get; set; }
}
#endregion

public override void OnActorDead(int missionNumber, string shortName, AiActor actor, List<DamagerScore> damages)
#region process when an actor dies
{
    base.OnActorDead(missionNumber, shortName, actor, damages);
    KilledActors.Add(actor, damages); // call the wrapper class
}

public override void  OnActorDamaged(int missionNumber, string shortName, AiActor actor, AiDamageInitiator initiator, NamedDamageTypes damageType)
{
    base.OnActorDamaged(missionNumber, shortName, actor, initiator, damageType);
    KilledActors.Add(actor, initiator, damageType); // call the wrapper class

}

A: Either m_KilledActors or tuple is not defined.
In this case the bug is in your constructor
List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();

This causes a duplicate definition of m_KilledActors.. change it to just
m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();


Q: Live lock on Linux UNIX socket, what to do? We operate an Linux application that forks a large number (more than 1000) of child processes. These child processes communicate with master process over UNIX datagram socket (one shared among all child processes). The UNIX datagram socket is used besides other communications also for logging. The whole system works fine until the app has to react to a massive external error - let's say a crash of application database. We observed that in such a situation, child processes start to generate a huge amount of error log events, which is probably correct since each child is impacted by that crash. After few minutes, the load increases above 8000 with 80-100% CPU system (not user!) consumption. The state is recoverable only if the app is killed or more commonly, the box becomes unusable due to slow responses and has to be rebooted.
The investigation of core dumps shows that child processes are blocked in send() syscall on the UNIX socket, speaking to master process. The UNIX socket is configured as a non-blocking and the app implement proper handling of EAGAIN. More in-depth analysis indicates that there is a live lock condition in the kernel. Obviously, processes are competing for access to some resource related to UNIX socket.
Questions: Did you ever meet this or similar behavior before? Do we miss anything about UNIX socket parallelism?
Versions:
 - CentOS Linux release 7.3.1611 (Core).
 - Kernel Linux 3.10.0-514.16.1.el7.x86_64 x86_64.

A: There is clearly room for improvement on the kernel side here and chances are it's a reasonably low hanging fruit. I'm not going to speculate. Chances are the problem will be easily visible with flamegraphs.
However, considerations of the sort in this context are a red herring. For the sake of argument let's assume the kernel pushes all these error messages with 0 overhead. You have generated gigabytes of repetitive error messages adding no value.
Instead, when there is a major event just log it once and then log again that it is cleared (e.g. note the connection to the database died, note when it got back up, but don't log on each query that it is dead). Alternatively you can log this periodically or with ratelimit. Either way, just spamming is the wrong thing to do.
The sheer number of children (1000+?) seems extremely excessive and puts a question mark on the validity of the design of this project. Can you elaborate what's happening there?


Q: Combine Google_Org_Chart with Mysql Im all new at PHP..
i have a task to make an organizational chart (just like google chart) but it is rendered from mysql, just like as follows org chart
and this is my database: sql
here is code from google chart.. `

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <title>
              Google Visualization API Sample
            </title>

Anybody knows something?? Any help would be appreciated.. Thanks..
Regards,
Aryo

A: You can try something like this:
<?php
// set database connection parameters
$databaseName = '<name of database>';
$username = '<user>';
$password = '<password>';
try {
    $db = new PDO("mysql:dbname=$databaseName", $username, $password);
}
catch (PDOException $e) {
    echo $e->getMessage();
    exit();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->prepare('SELECT id, nama, parent_id FROM tbl_dummy');
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$flag = true;
$table = array();
$table['cols'] = array(
    array('label' => 'ID', 'type' => 'number'),
    array('label' => 'Name', 'type' => 'string'),
    array('label' => 'Parent ID', 'type' => 'number')
);
$table['rows'] = array();

foreach ($results as $row) {
    $temp = array();
    $temp[] = array('v' => (int) $row['id']);
    $temp[] = array('v' => $row['nama']);
    $temp[] = array('v' => (int) $row['parent_id']);
    $table['rows'][] = array('c' => $temp);
}
$jsonTable = json_encode($table);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>
        Google Visualization API Sample
        </title>


Q: Google Website Optimizer Validation Warning I have been using Google website optimizer(GWO) to run a multivariate test on my web page. When I either do offline or online validation, I receive a warning stating there is multiple occurrences of my page sections. For example, if one of my page sections was Description Changes, optimizer would say I have two or more occurrences of that script.
I have gone through and checked through my code and have no duplicated any of the page section scripts. Even though GWO states that are multiple occurrences I can still create the experiment.
Does anyone know how to fix multiple occurrences from happening or if there are multiple occurrences if it affects the results.

A: Might be a bit late, but the issue might be that you have a latin-1 character set:

See the following post in the google forums:
http://www.google.com/support/forum/p/websiteoptimizer/thread?tid=70b4938cf4de24f2&hl=en


Q: Batch API, inviting friends I'm trying to invite all fans of a page to a facebook event using the batch API. It's the first time I'm using this API, and at this time I have nothing to test this part of code... can someone tell me how to test without using a real page, with real fans... or tell me if it looks correct ?
 //Getting all the likers of the page
 $result = $facebookObj->api(array(
     'method' => 'fql.query',
     'query' => 'select uid,name from user where uid in ( select uid from page_fan where uid in (select uid2 from friend where uid1 = me()) and page_id = '.$fbPage.')'
 ));

//If liker are more than 50 we use batch request
if($numLikers >50){

    // split array into several part of 50 users accounts
    $splitLikers = array_chunk($result, 50);
    // count how many arrays are generated by the array_chunk
    $countSplit = count($splitLikers);

    //Start a loop through the numbers of groups of 50 users  (or less if last group contains less than 50 users
    for($a=0; $a<$countSplit; $a++){
       //Second loop to go through the 50 likers in one group
       for($b=0; $b<count($splitLikers[$a]); $b++){
           // construct an array containing the whole group
           $queries[$a] = array('method' => 'POST', 'relative_url' => $event_fbID . "/invited/" . $splitLikers[$a][$b]['uid']);

       }
       //Send POST batch request with the array above
       $ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST');
    }

}else{

    foreach ($result as $value) {
        $ret_val = $facebookObj->api($event_fbID . "/invited/" . $value['uid'],'POST');
        if($ret_val) {
            // Success
            $numInvited++;
       }
   }
}

A: Your code seems ok, but dont forget you may need to add the access token to the batch request
like:
$params['access_token']=[USER_ACCESS_TOKEN];

$ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST', $params);

And for testing you may want to create a new page with a couple of friends added and test it.
Also remember you need to handle the response, the batch request will response with an array with the same length that the batch array, and each object may be a diferent code, true if it was send.
Also you can try your FQL code in the Graph Explorer (clic here)
Seems ok, but it shows a extrange result.


Q: How do I stop my program from jumping to a different if-Statement after receiving an invalid input? I´m new to Stackoverflow and to Python. As my first own program I wrote a text game where you enter (a) or (b) and decide this way which decision your character makes. Its working out quite well, but I have one problem. If the user enters, for example, "a" on the first decision, "b" on the second decision, but something invalid on the third, the next valid input will trigger the first decision again instead of the third. I tried to make a short version which portrays my problem. Any help is appreciated.
def test():
    while True:
        input_zero = input("1. > ")
        if input_zero == "a":
            print("a")
            input_a = input("2. > ")
            if input_a == "a":
                print("a, a")
                break
            elif input_a == "b":
                print("a, b")
                break
            else:
                print("Invalid input.")
        elif input_zero == "b":
            print("b")
            input_b = input("2. > ")
            if input_b == "a":
                print("b, a")
                break
            elif input_b == "b":
                print("b, b")
                break
            else:
                print("Invalid input.")
        else:
            print("Invalid input.")

test()

A: So, packaging your choices into a dictionary, similar to that shown below, should make it slightly easier to manage the choices here, I think (there's almost certainly a better way than this). Then add to the empty string each time a choice is made and try to access the dictionary. If the choice is in the dictionary then it will recover a text string and an end-state, which will enable us to end the game when we need to.
This approach also makes testing easier by using itertools to generate all possible combinations of states so you can work out which are missing. If an end_state is found (a value of 1 in the second position of the tuple), then you get the game over message and it closes the loop. If the element isn't in the dictionary, then the last selection was removed and the invalid_input function is called.
def test():

    choice_dict = {"a": (dP_lvl1.path_a, 0),
                   "b": (dP_lvl1.path_b, 0),
                   "c": (dP_lvl1.path_c, 1)
                   "bb": (dP_lvl2.path_bb, 0),
                   "aa": (dP_lvl2.path_aa, 0),
                   "ba": (dP_lvl2.path_ba, 0),
                   "ab": (dP_lvl2.path_ab, 0),
                   "aaa": (dP_lvl3.path_aaa, 0),
                   "aab": (dP_lvl3.path_aab 0),
                   "aba": (dP_lvl3.path_aba, 0),
                   "abb": (dP_lvl3.path_abb, 0),
                   "bab": (dP_lvl3.path_bab, 0),
                   "bba": (dP_lvl3.path_bba} 0),
                   "bbb": (dP_lvl3.path_bbb, 0),
                   "aaaa": (dP_lvl4.path_aaaa, 0),
                   "abaa": (dP_lvl4.path_abaa, 0),
                   "aaba": (dP_lvl4.path_aaba, 0),
                   "aaab": (dP_lvl4.path_aaab, 1),
                   "bbba": (dP_lvl4.path_bbba, 0),
                   "bbab": (dP_lvl4.path_bbab, 0),
                   "babb": (dP_lvl4.path_babb, 0),
                   "abbb": (dP_lvl4.path_abbb, 0),
                   "abba": (dP_lvl4.path_abba, 1),
                   "abab": (dP_lvl4.path_abab, 0),
                   "aabb": (dP_lvl4.path_aabb, 0),
                   "baab": (dP_lvl4.path_baab, 0),
                   "bbaa": (dP_lvl4.path_bbaa, 1),
                   "baba": (dP_lvl4.path_baba, 0),
                   "baaa": (dP_lvl4.path_baaa, 0),
               "bbbb": (dP_lvl4.path_bbbb, 0),}
    # etc. you get the idea

    decisions = ""
    playing = True
    while playing:
        decision = input("choose an option 'a' or 'b':")
        decisions += decision

        try:
            data, end_state = choice_dict[decisions]
            print(data)
            if end_state:
                playing = False
                print("Game over")
            else:
                continue
        except KeyError:
            decisions = decisions[:-1]
            invalid_input()


Q: why the kill function does not work in linux
Possible Duplicate:
Child process receives parent’s SIGINT

the is my code in below
The function is
after the father receive the signal of CTRL-C.
the father process send signal to son1 and son2;
after the son1 and son2 exit, the father process exit;
but the result does not like that;
this is the answer
son1
son2
^Cheeell
the son1 id 5963
the son2 id 5964
Parent process is killed !!

who can help me, thank you before!!
#include <stdio.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define SIGNAL_TO_SON1 10
#define SIGNAL_TO_SON2 12

#define FLAG_MSG_NO 0
#define FLAG_MSG_YES 1

int parent_msg = FLAG_MSG_NO;
void signal_sendToParent( int sig )
{
    printf("heeell\n");
    parent_msg = FLAG_MSG_YES;
}

int son1_flag = FLAG_MSG_NO;
void signal_handle_son1( int sig )
{
    printf("handle_son1\n");
    son1_flag = FLAG_MSG_YES;
}

int son2_flag = FLAG_MSG_NO;
void signal_handle_son2( int sig )
{
    printf("handle_son2\n");
    son2_flag = FLAG_MSG_YES;
}

int main( void )
{
    int pid1, pid2;
    if ( ( pid1 = fork() ) < 0 )
    {
        printf("erro!!!!");
        return -1;
    }

    if ( pid1  > 0 )
    {
        // in the parent
        while( ( pid2 = fork() ) == -1);
        if ( pid2 == 0 )
        {
            signal( SIGNAL_TO_SON2, signal_handle_son2 );
            printf("son2\n");
            // in the son2;
            while ( son2_flag != FLAG_MSG_YES );
            {
                printf("Child process 2 is killed by parent !!\n");
                exit(0);
            }
        }else{
            // setup the signal
            signal( SIGINT, signal_sendToParent );
            while ( parent_msg != FLAG_MSG_YES );
            {
                kill( pid1, SIGNAL_TO_SON1 );
                kill( pid2, SIGNAL_TO_SON2 );
                wait(0);
                printf("the son1 id %d\n", pid1 );
                printf("the son2 id %d\n", pid2 );

                wait(0);
                int status , pid ;
                while( ( pid = waitpid( -1, &status, 0 ) )  > 0 )
                {
                    printf("child %d \n", pid );
                }
                printf("Parent process is killed !!\n");
                exit(0);
            }
        }
    }else{
        // in the son1;
        printf("son1\n");
        signal( SIGNAL_TO_SON1, signal_handle_son1 );
        while ( son1_flag != FLAG_MSG_YES );
        {
            printf("Child process 1 is killed by parent !!\n");
            exit(0);
        }
    }

    return 0;
}

A: to get what you want you must ignore SIGINT in the childs.
see this What happens to a SIGINT (^C) when sent to a perl script containing children?
In short Ctrl-C is send to all processes in the foreground group.
That means your child processes get SIGINT too, they do not have a handler and get killed.
signal( SIGINT, SIG_IGN );

add in the child code, near setting the other signal handler.


Q: Hybris Backoffice update with ant updatesystem I want to update backoffice with ant updatesystem, I'm doing it this way:
ant updatesystem -DconfigFile=configWithBackofficeExt.json

For example - I have "Administration" and "MyWidget" widgets, I want to remove "Product Cockpit", so I remove config from *extension-backoffice-widgets.xml.
And now, If I run my ant command - dropdownlist with widgets not updated.
If I run an update from HAC or in backoffice with F4, all works fine.
As far as I understand, there is no web-context when I running ant command, so there are no beans responsible for update/rebuild of widgets.xml(composed widget config, which we can see in orchestrator).
Is there any way to attach backoffice web context, so that beans would be available when ant command called. Or maybe there is a more elegant way to do it?
Ps: I know about config properties to update backoffice on startup/login, but still prefer to do it with ant.

A: Finally, after research, I haven't find appropriate way to update backoffice with ant updatesystem.
To update backoffice upon application start or/and login to backoffice we can use these properties:
backoffice.cockpitng.reset.triggers=start,login
backoffice.cockpitng.reset.scope=widgets,cockpitConfig

When the application starts, configuration files will be reassembled and saved. This won't take much time(I didn't notice any impact on application startup time, with all OOTB backoffice extensions enabled, sometimes app took 10 sec longer to start, sometimes 10 sec faster).


Q: google tag manager v2 basic configuration I'm not getting hits on google analytics I'm working on a cordova/phonegap project. I'm using a plugin for GTM that allows me to track events.
The problem is that I'm not getting hits on google analytics.
According with the developer it's working fine, and from my testing, everything seems ok, no errors at all on Javascript console, and all events are firing correctly.
Since I'm new with GTM, I believe that I'm missing something on configureting it.
These are my confs:
First, the GA tag:

I used the built-in trigger "Any event" so it triggers every time an event is registered.
This is the config I set for the GA tag, I want it to trigger on every event, that's why I left empty the fields

And the GTM container type I'm using is "mobile".
For I what haver been reading so far is far different from GTM V1 where I had to create macros, and another tag to be able to track this same information.
I tried manual triggers such as, "Event matches RegEx .*" (which I believe it's the same as the built-in "Any event" trigger)

A: You have to fill in the Category and Action field at the very least for GA to register a hit. (Categoira, Accion, I guess)
Those aren't filter fields, they are the fields sent in an event hit.  You will need to use something like the macros {{element text}} or something you want to record to see hits in GA.
Check out the Event Tracking Guide by Google for more details.


Q: What should be the lucene indexing and searching strategy for providing search capabilities to end user over set of unrelated business objects? I want to provide ability to end user to do a free form search over all business objects. The user will provide Lucene search expression. The business objects are completely unrelated and have nothing in common.
Each business object comprises of there own specific attributes. For the sake of this question, the following are the business objects:
Blog
{
    Title;
    Body;
}
User
{
    FirstName;
    LastName;
    Country;
    EmailAddress;
    Gender(M/F);
}
How could I create an index which can serve the following use-cases:

*

*Free form text search in both - Blog and User. For e.g. Search those users and blog entries where the word 'India' appears. End user should not be required to specify ORing between all Lucene document fields.

*Free form text search for only users. For e.g. Search for those users where the word 'yahoo' appears. End user should not be required to specify ORing between all Lucene document fields related to User.

*Free form text search for only blog entries. For e.g. Search for those blog entries where either of the word 'Skeet Async' appears. End user should not be required to specify ORing between all Lucene document fields related to Blog.

*Free form text search by attributes for blog entries. For e.g. Search those blog entries where 'asynchronous' appears in the 'Title' attribute.

*Free form text search by attributes for users. For e.g. Search those users where 'Skeet' appears in the 'LastName' attribute.
How to define the index strategy - single index or multiple index, analyzer to use, how to provide context in the search query, etc.
Thanks.

A: For the given business objects, simplest way is to have lucene documents with the following fields:
title, body, firstName, lastName, country, emailAddress, gender

You might want to have title and user-related fields as STORED.
Choice of analyzers depends on your search requirements (like do you want to support partial matches, suffix queries, stemming etc).
Queries for the given use-cases:
1) title:india OR body:india OR country:india
2) title:yahoo OR body:yahoo OR emailAddress:yahoo
3) title:(Skeet OR Async) OR body:(Skeet OR Async)
4) title:asynchronous
5) lastName:skeet


Q: SetInterval several elements at the same time Jquery I have this code, It appends comments after clicking on comment button. (the php processes via other function)....
I want to simulate that every comment was posted at certain time, and the set interval after a while work independently with each li appendend.
PROBLEM
In the snippet it is shown that if I post a  comment set interval works with it to show how long time ago it was posted (need format but it has the idea).
The problem is that anytime I post a new comment, set intervals reloads all the previous times and shows the same results for all the comments.

$('.comment').on('click', function(){
        timeIni=$.now();

          comment=$(".textarea").val();
            $("#comments").append("
"+comment+" 1s"+"
");

            $(".textarea").val("");

      //adding the time to looks like
       /* */ setInterval(function(){
            time=$.now();
          tempo="time: "+time;
             $("#comments span").text(tempo);
                           }, 2000);

        });
textarea{
height:30px;
width:200px;
border:1px solid red;
display:block;
}

      <textarea class=textarea></textarea>
       <input type=submit class="comment" value='comment' />

I want every comments shows its own time interval, according with the time it was posted.
Other try using .each()
https://jsfiddle.net/s8650s18/16/

A: You need to declare your variables with a keyword such as var, let, const otherwise the variable becomes global. All boils down to a scoping issue.
let timeIni = Number($.now());

Here is the fiddle working: https://jsfiddle.net/s8650s18/22/


Q: Objective c UIlabel is hang for a while when API is called As title, when users click a button as many times as they want, the uilabel will be updated to the number and the app will call an api to post the number to the server. Everything works fine except when the api is being called, the uilabel will hang for 2 - 5 seconds and will not update even the user is pressing the button. I have tried calling api in the background and update the ui in the main queue, it works but still will hang for a little while like 1 - 3 seconds. The reason I need to post the count to server is because there will be many users pressing the button simultaneously thus the label will be updated to total of all users.
The flow: Users press button, as many as they want, uilabel will be updated to how many times the users have pressed the button, every 5 seconds an api will be called to post the count, uilabel will update the number again.
Any suggestion to fix or enhance this issue? Thank you
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error)
 {
     dispatch_async(dispatch_get_main_queue(), ^{
         [self setUpCount];
     });

     if ([self checkError:error])
         return;
 }];
});

A: You need to add loader (activityIndicator) while your process start and hide while process complete .
And you need to manage that while process is working user not interact any thing in the current view
// Start here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error)
 {
     dispatch_async(dispatch_get_main_queue(), ^{
         [self setUpCount];
         // stop here
     });

     if ([self checkError:error])
          // stop here
         return;

 }];
});


Q: Animation in iOS 14 widget I can't find solution to implement kind of ProgressBar in Widget. I see, that Text component should be changed if has type .timer for example. I see default widget Clock, with nice animation of moving arrow. But am I able to implement custom animation in widget?

A: According to a Frameworks Engineer on Developer Apple Forum:

Animations and pan/zoom gesture do not work in widgets built with WidgetKits. Checkout https://developer.apple.com/videos/play/wwdc2020/10028/, where what works and doesn't.

Throughout the WWDC20 Meet WidgetKit video mentioned above, Apple stresses that Widgets are not mini-apps, so they don't support gesture based views (like scroll views) or animations. Widgets are meant to only have glanceable information. From WWDC20 Meet WidgetKit Video Transcript:

These widgets are not mini-apps. We do not support scrolling within the widget, interactive elements like switches and other system controls, nor videos or animated images.


Q: scope of variable in nodejs inside a function How to scope datat ?
Here datat is empty.
And i would like to put data in a var so i can use it outside the function.
var datat;
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

// and output to the console:

datat =  data;

});
sys.puts(sys.inspect(datat));

Regards
Bussiere

A: 'datat' is scoped outside your function. twit.search is async and therefore may not return 'data' before you check 'datat' with sys.inspect.
This should let you see datat:
var datat;
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

    // and output to the console:
    datat =  data;
    sys.puts(sys.inspect(datat));

});

But ideally you'd use a callback like this...
var datat;
var callback = function(d){
    sys.puts(sys.inspect(d));

    datat = d;
    // do something more with datat

};

twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

    callback(data);

});

EDIT - simplified as per comment...
var datat;
var callback = function(d){
  sys.puts(sys.inspect(d));
  datat = d;
  // do something more with datat
};
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt},callback(data));


Q: Create mutation between related types in GraphQL I'm using GraphQL to try to create a record that has a relation to another type.  The types are Task and Day
datamodel.graphql:
type Task {
  id: ID! @unique
  content: String!
  completed: Boolean!
  dateToDo: Day!
}

type Day {
  id: ID! @unique
  content: String!
  tasks: [Task]
}

I want to create a task so that it has a reference of the date it should be completed (from the Day type)
schema.graphql
type Mutation {
  createTask(content: String!, completed: Boolean!, dateToDo: ID! ): Task!
}

my mutation resolver looks like this:
const Mutations = {
  async createTask(parent, args, ctx, info) {

    const task = await ctx.db.mutation.createTask(
      {
        data: {
          dateToDo: {
            connect: {
              id: args.dateToDo
            }
          },
          ...args
        }
      },
      info
    );

    return task;
  },

when I run this mutation to create the task:
mutation CREATE_ONE_TASK  {
  createTask(
    content: "a new task",
    completed: false,
    dateToDo: "cjqycv9dtjklr09179y9zfntq")
  {
    id
  }
}

I get this error:

"message": "Variable \"$_v0_data\" got invalid value
  {\"dateToDo\":\"cjqycv9dtjklr09179y9zfntq\",\"content\":\"a new
  task\",\"completed\":false}; Expected type
  DayCreateOneWithoutTasksInput to be an object at value.dateToDo.",

My questions are: Am I using connect correctly in the mutation resolver? And what the heck is DayCreateOneWithoutTasksInput (I see its been automagically added in prisma.graphql) and how do I use it to create a Task that has a relation to a Day's ID?

A: The mutation to create the task has the following shape:
mutation b {
  createTask(
    data: {
      content: "Task1"
      completed: false
      dateToDo: { connect: { id: "cjqzjvk6w000e0999a75mzwpx" } }
    }
  ) {
    id
  }
}

The type DayCreateOneWithoutTasksInput Prisma is asking for is autogenerated and is the one expected for the field dataToDo. The name means that Prisma would accept a type that creates one Day node but does not have the field tasks or a type that specifies a connection. The WithoutTasksInput part states is there because the type can only be used nested in a mutation where you start from a task, Prisma therefore already has the value to fill in for the tasks field on the nested Day node and you do not need to specify it if you create the day instead of connecting an existing one.
If you use the Playground you can explore the schema that contains all the types on the right side.
schema explorer in the playground
Hope that helps!


Q: why doesn't std::remove_copy_if() actually remove? Could this be the worst named function in the STL? (rhetorical question)
std::remove_copy_if() doesn't actually appear to do any removing. As best I can tell, it behaves more like copy_if_not.
The negation is a bit confusing, but can be worked around with std::not1(), however I might be misunderstanding something as I cannot fathom what this function has to do with removing - am I missing something?
If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?
Editing to add an example so readers are less confused.
The following program appears to leave the input range (V1) untouched:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

using std::cout;
using std::endl;

int main (void)
{
    std::vector<int> V1, V2;
    V1.push_back(-2);
    V1.push_back(0);
    V1.push_back(-1);
    V1.push_back(0);
    V1.push_back(1);
    V1.push_back(2);

    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;

    std::remove_copy_if(
        V1.begin(),
        V1.end(),
        std::back_inserter(V2),
        std::bind2nd(std::less<int>(), 0));

    std::copy(V2.begin(), V2.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
}

It outputs:
-2 0 -1 0 1 2
0 0 1 2
-2 0 -1 0 1 2

I was expecting so see something like:
-2 0 -1 0 1 2
0 0 1 2
0 0 1 2 ? ? ?

Where ? could be any value. But I was surprised to see that the input range was untouched, & that the return value is not able to be used with (in this case) std::vector::erase(). (The return value is an output iterator.)

A:
is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

The closest thing I can think of is std::stable_partition:
std::vector<int> v;
// ...
auto it = std::stable_partition(v.begin(), v.end(), pick_the_good_elements);
std::vector<int> w(std::make_move_iter(it), std::make_move_iter(v.end()));
v.erase(it, v.end());

Now v will contain the "good" elements, and w will contain the "bad" elements.

A:
Could this be the worst named function in the STL?

A bit of background information: in the standard library (or the original STL), there are three concepts, the containers, the iterators into those containers and algorithms that are applied to the iterators. Iterators serve as a cursor and accessor into the elements of a range but do not have a reference to the container (as mentioned before, there might not even be an underlying container).
This separation has the nice feature that you can apply algorithms to ranges of elements that do not belong to a container (consider iterator adaptors like std::istream_iterator or std::ostream_iterator) or that, belonging to a container do not consider all elements (std::sort( v.begin(), v.begin()+v.size()/2 ) to short the first half of the container).
The negative side is that, because the algorithm (and the iterator) don't really know of the container, they cannot really modify it, they can only modify the stored elements (which is what they can access). Mutating algorithms, like std::remove or std::remove_if work on this premise: they overwrite elements that don't match the condition effectively removing them from the container, but they do not modify the container, only the contained values, that is up to the caller in a second step of the erase-remove idiom:
v.erase( std::remove_if( v.begin(), v.end(), pred ),
         v.end() );

Further more, for mutating algorithms (those that perform changes), like std::remove there is a non-mutating version named by adding copy to the name: std::remove_copy_if. None of the XXXcopyYYY algorithms are considered to change the input sequence (although they can if you use aliasing iterators).
While this is really no excuse for the naming of std::remove_copy_if, I hope that it helps understanding what an algorithm does given its name: remove_if will modify contents of the range and yield a range for which all elements that match the predicate have been removed (the returned range is that formed by the first argument to the algorithm to the returned iterator). std::remove_copy_if does the same, but rather than modifying the underlying sequence, it creates a copy of the sequence in which those elements matching the predicate have been removed. That is, all *copy* algorithms are equivalent to copy and then apply the original algorithm (note that the equivalence is logical, std::remove_copy_if only requires an OutputIterator, which means that it could not possibly copy and then walk the copied range applying std::remove_if.
The same line of reasoning can be applied to other mutating algorithms: reverse reverses the values (remember, iterators don't access the container) in the range, reverse_copy copies the elements in the range to separate range in the reverse order.

If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

There is no such algorithm in the STL, but it could be easily implementable:
template <typename FIterator, typename OIterator, typename Pred>
FIterator splice_if( FIterator first, FIterator last, OIterator out, Pred p )
{
   FIterator result = first;
   for ( ; first != last; ++first ) {
      if ( p( *first ) ) {
         *result++ = *first;
      } else {
         *out++ = *first;
      }
   }
   return result;
}

A:
If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

Not really. The idea is that the modifying algorithms are allowed to "move" (not in the C++ sense of the word) elements in a container around but cannot change the length of the container. So the remove algorithms could be called prepare_for_removal.
By the way, C++11 provides std::copy_if, which allows you to copy selected elements from one container to another without playing funny logic games with remove_copy_if.

A: You are right, that is what it does... std::remove_copy_if copies the vector, removing anything that matches the pred.
std::remove_if ... removes on condition (or rather, shuffles things around).

A: I agree that remove is not the best name for this family of functions.
But as Luc said, there's a reason for it working the way it does, and the GoTW item that he mentions explains how it works. remove_if works exactly the same way as remove - which is what you would expect.
You might also want to read this Wikibooks article.


Q: Retrieve correct data from Core Data? I have a REST API and I want to save the responses with Core Data. I was trying to implement DATAStack and Sync but I can't understand how they work. I know I can save an object into Core Data and retrieve them. But I don't find how to retrieve the objects related to an specific URL that I requested before
e.g:
GET my_url.com/home_page

{
  "posts":[
       {
         "id": 1,
         "title": "Example Post",
       },
       {
         "id": 2,
         "title": "Another example",
       }
      ]
}

and
GET my_url.com/another_page

{
  "posts":[
       {
         "id": 4,
         "title": "This is another post",
       },
       {
         "id": 5,
         "title": "Last Post",
       }
      ]
}

How do I get data from Core Data related to an URL request?


Q: Load data from SQL file to Realm Is it possible to have a SQL file inside Swift project where Realm database will import data as soon as project will be executed? I want to use a 30MB+ file of data... and don't want to download it all from a JSON API.

A: Why not bundle a prebuilt Realm file as part of your application instead? To do this you'll need to:

*

*Create the prebuilt Realm file, either using Realm Browser or a simple Mac app of your own creation.

*Add the prebuilt Realm file to your app target in your Xcode project, ensuring that it appears in the Copy Bundle Resources build phase.

*Add code similar to that found in the above link to your app to have it open the prebuilt Realm file as read-only. Alternatively, you could copy the file out of your app bundle into the user's documents or cache directory and open it read-write.


Q: Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels "month" and "year" Say I have a table of data with monthly datetime indices (the following code gives two years, january through december):
import pandas as pd
import numpy as np
from datetime import datetime
N = 12*2
c = [datetime(1970 + i//12, (i%12)+1, 1) for i in range(N)]
d = pd.DataFrame(np.random.rand(N), index=c)
print(d)

What is the best way to convert the DateTimeIndex into a MultiIndex with the separate levels month and year? Perhaps there is a way to do this with groupby, but I'm not sure.

A: You can construct a MultiIndex object from the year and month and assign it to the data frame's index:
import pandas as pd
d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month])

d.index
# MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
#            labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

d.head()

#                  0
#1970   1   0.657130
#       2   0.047241
#       3   0.984799
#       4   0.868508
#       5   0.678536

A: d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\
                                    apply(lambda x:(x.year,x.month)))


Q: MediaPlayer audio doesn't stop immediately when stop() is called A button has onClickMethod openTheLock() which makes an ImageView visible and starts an audio. On tapping on the ImageView it disappears and the audio stops. Audio is initialized in onCreate(). The problem is the audio doesn't stop immediately when the ImageView is tapped. What could be the reason?
MediaPlayer jokerAudio;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earth_room);
        jokerAudio= MediaPlayer.create(EarthRoomActivity.this, R.raw.joker_laugh);
    }
public void openTheLock(View v){
    if(selectedItem == R.id.key_er_item || keyUsed == true){
    jokerAudio.start();
    ImageView joker = (ImageView)parentLayout.findViewById(R.id.joker);
    joker.setVisibility(View.VISIBLE);
    joker.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            jokerAudio.stop();
            view.setVisibility(View.INVISIBLE);
        }
    });
    }

A: If you are not using the MediaPlayer again then you can try releasing the MediaPlayer.
joker.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            jokerAudio.stop();
            jokerAudio.reset();
            jokerAudio.release();
            view.setVisibility(View.INVISIBLE);
        }
    });

However if you are using MediaPlayer again later in your code don't forget to reinitialize it again.


Q: Contact form using nodemailer is not working I have created a contact form and trying to use nodemailer to send the message to my email, but not sure where is the issue.
I created a server.js and put it in the main folder while Mailer.js that contain the form in components
I am not sure how the server know that I want to use the form
this is my first project on React and I think I still don't understand some basics of React
const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const nodemailer = require('nodemailer');

const app = express();

// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.render('contact');
});

app.post('/send', (req, res) => {
  const output = `

You have a new contact request

Contact Details

Name: ${req.body.name}

Email: ${req.body.email}

Message

${req.body.message}

  `;

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.EMAIL, // generated ethereal user
        pass: process.env.PASSWORD  // generated ethereal password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

  // setup email data with unicode symbols
  let mailOptions = {
      from: process.env.EMAIL, // sender address
      to: email, // list of receivers
      subject: 'Node Contact Request', // Subject line
      text: 'Hello world?', // plain text body
      html: output // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      res.render('contact', {msg:'Email has been sent'});
  });
  });

app.listen(3000, () => console.log('Server started...'));

This is the form
import React from 'react';
import "./Mailer.scss";
const Mailer = () =>{

    return (

Contact Us

            <form method="POST" className="form" action="send">

                Name
                <input type="text" name="name" className="input"/>

                Email
                <input type="email" name="email" className="input"/>

                Message
                <textarea name="message" rows='4' className="input"/>
                <input type="submit" value="Send"/>

            </form>

    );
};

export default Mailer;

this is what I get when I click on SEND

A: From what I could gather, you're posting to the wrong URL.
In your server app, you create a post handler for /send
However, in your React App, you post to /xxxxx/send (You obscured the xxxxx part)
I advise that you replace your
<form method="POST" className="form" action="send">

With
<form method="POST" className="form" action="http://127.0.0.1:3000/send">

And try again


Q: c# html - hide kendo grid when empty I have the following Kendo grid in my html code and am trying to hide it if there is no data. I am confused on how to do this since I am using a datasource and not iterating through something to add data.
 @(Html.Kendo().Grid<CustomerQuickHistory>()
                  .Name("TransactionDetails")
                  .Columns(cols => {
                      cols.Bound(c => c.DateOfItem).Format("{0:MM/dd/yyyy}");
                      cols.Bound(c => c.ProductName);
                      cols.Bound(c => c.Price);
                  })
                  .DataSource(ds => ds
                      .Ajax()
                      //.Group(g => g.Add(d => d.CustomerName))
                      .Sort(s => s.Add(ad => ad.DateOfItem).Descending())
                      .Read(r => r.Action("TransactionHistory_Read", "Customers", new { customerId = Model.CustomerId }))
                  )
                  )

A: What about using the DataBound event handler to define check the dataSource binded and show or hide the grid.
Here is an example of something similar, but in this case it shows a message when the grid is empty.
http://blog.falafel.com/displaying-message-kendo-ui-grid-empty/
code example:

 @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductName).Title("Product Name");
            columns.Bound(p => p.UnitPrice).Title("Unit Price");
            columns.Bound(p => p.UnitsInStock).Title("Units In Stock");
        })
        .Events(events => events.DataBound("onGridDataBound"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("Products_Read", "Grid"))
         )
    )

<script>

  function onGridDataBound(e){
    var grid = e.sender;

    if (grid.dataSource.total() == 0 ){
    //Hide grid
      $(grid).hide();
    }
    else{
      //Show grid
      $(grid).show();
    }
  }

</script>


Q: How to download receipt and invoice from stripe through my site I am using stripe from payment. After payment using invoice id how can i download receipt and invoice from my site


Q: Not able to install J2OBJC using terminal I have download the J2OBJC version and while running the command on terminal
A:j2objc-master $ make dist
I am getting below error
building j2objc jar
javac: invalid source release: 1.8
Usage: javac
use -help for a list of possible options
make[1]: * [/Users/Downloads/j2objc-master/translator/build_result/j2objc.jar] Error 2
make: * [translator] Error 2
Please suggest

A: That's a javac error, stating that the version of javac on your system (which is part of the JDK you have installed) does not support the j2objc project's Java 8 minimum version. Upgrade your system to JDK 8 from Oracle to support this minimum.


Q: 503 Error After Microsoft Request Routing Is Installed - 32 bit 64 bit madness I have a requirement to install the Microsoft Request Routing component for IIS 7.5 running on a Windows 2008 R2 SP1 64Bit machine.
After installing Microsoft Request Routing via the Web Platform installer our ASP.NET 4.0 application gets a "HTTP Error 503. The service is unavailable."
The Windows event log error details says:
The Module DLL 'C:\Program Files\IIS\Application Request Routing\requestRouter.dll' could not be loaded due to a configuration problem. The current configuration only supports loading images built for a AMD64 processor architecture. The data field contains the error number. To learn more about this issue, including how to troubleshooting this kind of processor architecture mismatch error, see http://go.microsoft.com/fwlink/?LinkId=29349.

I can make this error go away by changing the application pool to run in 32 bit mode by changing the "Enable 32-Bit Applications" setting to true.
However I would prefer not to have to do that to resolve the issue.
My questions are:

*

*Why is the Microsoft Request Routing feature trying to load a 32 bit version, isn't there a 64 bit version for it?

*How do I resolve this issue without having to change my application pool to a 32 bit mode?

A: having done some research into this I can inform you that there are currently two version of Microsoft's Application Request Routing one for 32-bit architecture and the other for 64-bit.
Although it does not say, I would presume that the Web Platform Installer version is only for 32-bit, in order to get a 64-bit specific version you are going to have to download from one these two locations:
http://blogs.iis.net/wonyoo/archive/2011/04/20/how-to-install-application-request-routing-arr-2-5-without-web-platform-installer-webpi.aspx
or
http://www.microsoft.com/en-us/download/details.aspx?id=7173
the blog (first URL) gives details on how to install into IIS once you have downloaded.
hope this proves useful.

A: What processor architecture are you using?
The error seems to suggest that only 64bit AMD processors are currently supported, perhaps it might be worth looking into a solution more specific to your processor.
I'm guessing your using an Intel CPU?
I'm aware that there are certain scenarios where running IIS in 32 bit mode on a 64 bit system is required.

A: it might be worth looking at these installation guidelines on the IIS site found at this address:
http://www.iis.net/learn/extensions/installing-application-request-routing-%28arr%29/install-application-request-routing
if these don't solve the issue it might well be worth either posting on the IIS forum:
http://forums.iis.net/
or posting on technet forum:
http://social.technet.microsoft.com/Forums/en-gb/categories/


Q: find common files between two directories - exclude file extension I have two directories with files that end in two different extensions:
Folder A called profile (1204 FILES)
file.fasta.profile
file1.fasta.profile
file2.fasta.profile

Folder B called dssp (1348 FILES)

file.dssp
file1.dssp
file2.dssp
file3.dssp #<-- odd one out

I have some files in folder B that are not found in folder A and should be removed for example file3.profile would be deleted as it is not found in folder A. I just want to retain those that are common in their filename, but excluding extension to end up with 1204 files in both
I saw some bash lines using diff but it does not consider this case, where the ones I want to remove are those that are not found in the corresponding other file.

A: Here is a way to do it:

*

*for both A and B directories, list the files under each directory, without the extension.

*compare both lists, show only the file that does not appear in both.

Code:
#!/bin/bash

>a.list
>b.list

for file in A/*
do
    basename "${file%.*}" >>a.list
done

for file in B/*
do
    basename "${file%.*}" >>b.list
done

comm -23 <(sort a.list) <(sort b.list) >delete.list

while IFS= read -r line; do
    rm -v A/"$line"\.*
done < "delete.list"

# cleanup
rm -f a.list b.list delete.list

*

*"${file%.*}" removes the extension

*basename removes the path

*comm -23 ... shows only the lines that appear only in a.list

EDIT May 10th: my initial code listed the file, but did not delete it.  Now it does.

A: Try this Shellcheck-clean Bash program:
#! /bin/bash -p

folder_a=PATH_TO_FOLDER_A
folder_b=PATH_TO_FOLDER_B

shopt -s nullglob
for ppath in "$folder_a"/*.profile; do
    pfile=${ppath##*/}
    dfile=${pfile%.profile}.dssp
    dpath=$folder_b/$dfile
    [[ -f $dpath ]] || echo rm -v -- "$ppath"
done

*

*It currently just prints what it would do.  Remove the echo once you are sure that it will do what you want.

*shopt -s nullglob makes globs expand to nothing when nothing matches (otherwise they expand to the glob pattern itself, which is almost never useful in programs).

*See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for information about the string manipulation mechanisms used (e.g. ${ppath##*/}).

A: With find:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'! [ -f "folder B/$(basename -s .fasta.profile "$1").dssp" ]' _ {} \; -print

Replace -print by -delete when you will be convinced that it does what you want.
Or, maybe a bit faster:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'for f in "$@"; do [ -f "folder B/$(basename -s .fasta.profile "$f").dssp" ] || echo rm "$f"; done' _ {} +

Remove echo when you will be convinced that it does what you want.

A: Python version:
EDIT: now suports multiple extensions
#!/usr/bin/python3

import glob, os

def removeext(filename):
    index = filename.find(".")
    return(filename[:index])

setA = set(map(removeext,os.listdir('A')))
print("Files in directory A: " + str(setA))

setB = set(map(removeext,os.listdir('B')))
print("Files in directory B: " + str(setB))

setDiff = setA.difference(setB)
print("Files only in directory A: " + str(setDiff))

for filename in setDiff:
    file_path = "A/" + filename + ".*"
    for file in glob.glob(file_path):
        print("file=" + file)
        os.remove(file)

Does pretty much the same as my bash version above.

*

*list files in A

*list files in B

*get the list of differences

*delete the differences from A

Test output, done on Linux Mint, bash 4.4.20
mint:~/SO$ l
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 A/
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 B/

mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:36 file4.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile
mint:~/SO$ l B
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file1.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file3.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file.dssp

mint:~/SO$ ./so.py
Files in directory A: {'file1', 'file', 'file3', 'file2', 'file4'}
Files in directory B: {'file1', 'file', 'file3', 'file2'}
Files only in directory A: {'file4'}
file=A/file4.fasta.profile

mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile


Q: Should I prevent branching if there will be perfect pattern so prediction should be good? My question is very much related to this question but something remained unclear for me after reading that question and very good answer.
So as I understand it, the processor executing the code makes a branch prediction such that it already does the processing towards one branch in the hope that branch will be the one that needs to be executed. If it is wrong it will have to reroll some instructions which takes time.
As I understand it the prediction is based on the pattern in the past.
So now my question would be: if I know for sure there will be a pattern in what the if statement will evaluate to, is that just as fast when the decision would have been made at compile time?
More specific for my case, I have a template function and I could do template specialization such that the decision is made on compile time, but in my opinion the code will be more clear if I use std:is_same inside my function. But speed is also highly important for my application so if speed might be compromised I would still rather go for template specialization although that will be less readable/maintainable in my specific case. (I could make the template specialization more readable as well, but it's a big code (not fully written by me) and I rather not go through the whole code and change many things to make it nice again. Yes basically I'm lazy.)
(I think the question can go without MWE but if not I'll add some)


Q: Rust serde deserialize dynamic trait I have a recursive data structure in my pet-project:
(this is a simplified example)
pub trait Condition {
        fn validate(&self, s: &str) -> bool;
}

pub struct Equal {
    ref_val: String,
}
impl Condition for Equal {
    fn validate(&self, s: &str) -> bool { self.ref_val == s }
}

pub struct And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized {
    left: Box<A>,
    right: Box<B>,
}

impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized {
    fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) }
}

and i want to serialize and de-serialize the condition trait (using serde) eg.:
fn main() {

    let c = And {
        left: Box::new(Equal{ ref_val: "goofy".to_string() }),
        right: Box::new(Equal{ ref_val: "goofy".to_string() }),
    };

    let s = serde_json::to_string(&c).unwrap();

    let d: Box<dyn Condition> = serde_json::from_string(&s).unwrap();
}

Because serde cannot deserialize dyn traits out-of-the box, i tagged the serialized markup, eg:
#[derive(PartialEq, Debug, Serialize)]
#[serde(tag="type")]
pub struct Equal {
    ref_val: String,
}

and try to implement a Deserializer and a Vistor for Box<dyn Condition>
Since i am new to Rust and because the implementation of a  Deserializer and a Visitor is not that straightforward with the given documentation, i wonder if someone has an idea how to solve my issue with an easier approach?
I went through the serde documentation and searched for solution on tech sites/forums.
i tried out typetag but it does not support generic types
UPDATE:
To be more precise: the serialization works fine, ie. serde can serialize any concrete object of the Condition trait, but in order to deserialize a Condition the concrete type information needs to be provided. But this type info is not available at compile time. I am writing a web service where customers can upload rules for context matching (ie. Conditions) so the controller of the web service does not know the type when the condition needs to be deserialized.
eg. a Customer can post:
{"type":"Equal","ref_val":"goofy"}

or
{"type":"Greater","ref_val":"Pluto"}

or more complex with any combinator ('and', 'or', 'not')
{"type":"And","left":{"type":"Greater","ref_val":"Gamma"},"right":{"type":"Equal","ref_val":"Delta"}}

and therefore i need to deserialze to a trait (dyn Condition) using the type tags in the serialized markup...

A: I would say the “classic” way to solve this problem is by deserializing into an enum with one variant per potential “real” type you're going to deserialize into. Unfortunately, And is generic, which means those generic parameters have to exist on the enum as well, so you have to specify them where you deserialize.
use serde::{Deserialize, Serialize};
use serde_json; // 1.0.91 // 1.0.152

pub trait Condition {
    fn validate(&self, s: &str) -> bool;
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct Equal {
    ref_val: String,
}
impl Condition for Equal {
    fn validate(&self, s: &str) -> bool {
        self.ref_val == s
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct And<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    left: Box<A>,
    right: Box<B>,
}

impl<A, B> Condition for And<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    fn validate(&self, s: &str) -> bool {
        self.left.validate(s) && self.right.validate(s)
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Expr<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    Equal(Equal),
    And(And<A, B>),
}

fn main() {
    let c = And {
        left: Box::new(Equal {
            ref_val: "goofy".to_string(),
        }),
        right: Box::new(Equal {
            ref_val: "goofy".to_string(),
        }),
    };

    let s = serde_json::to_string(&c).unwrap();

    let d: Expr<Equal, Equal> = serde_json::from_str(&s).unwrap();
    println!("{d:?}");
}

Prints And(And { left: Equal { ref_val: "goofy" }, right: Equal { ref_val: "goofy" } })

A: I removed the generics from the combinator conditions, so i can now use typetag like @EvilTak suggested:
#[derive(Serialize, Deserialize)]
#[serde(tag="type")]
pub struct And {
    left: Box<dyn Condition>,
    right: Box<dyn Condition>,
}
#[typetag::serde]
impl Condition for And {
    fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) }
}

(on the downside, i had to remove the derive macros PartialEq, and Debug)
Interesting side fact: i have to keep the #[serde(tag="type")] on the And Struct because otherwise the typetag will be omitted in the serialization (for the primitive consitions it is not needed)
UPDATE: typetag adds the type tag only for trait objects so the #[serde(tag="type")] is not needed...


Q: Does dependency injection (in NestJS, for example) depends on TypeScript features? When applying the dependency injection pattern in NestJS, like in this example from the documentation:
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  // Some other methods...
}

How does this work? As far as I understand, TypeScript will be compiled to plain JavaScript, and then the class type (CatsService) will disappear. How does NestJS know what class to inject in this case?

A: Dependency injection does not depend on the typescript. Whenever we boot up the nest app, a Dependency Injection (DI) container gets created for us. DI is just an object.
Nest will look at the all different classes that we created except controllers. It will register all those different classes with the DI container. The container will check all the dependencies that are required for each class and map this class to its dependencies:
   class1 ---> dependencies
   class2 ---> dependencies
   class3 ---> it might now have any dependency

Then eventually we want to create the controller. we tell DI to create the controller with the required dependencies. DI will look at the constructor argument and see all the dependencies that are required. the container will see that it needs to create a service and service needs to create some dependencies.
So DI container will create the instances of required dependencies and store each instance internally so if in the future another class needs to those instances it can use them. Now dependencies are already created and DI container will use those to create the Controller and return it.
As you see we do not worry about creating all those services ourselves. DI container will take care of it for us.
Dependency injection is used for reusing the code and test the app easier.

A: Take a look at the example. This:
@Injectable()
export default class RequestService {
  constructor(
    @InjectRepository(RequestEntity)
    private requestEntityRepository: Repository<RequestEntity>,
  ) {}

Is being transpiled to this:
let RequestService = class RequestService {
    constructor(requestEntityRepository) {
        this.requestEntityRepository = requestEntityRepository;
    }
...

RequestService = __decorate([
    common_1.Injectable(),
    __param(0, typeorm_1.InjectRepository(RequestEntity_1.default)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], RequestService);
exports.default = RequestService;

A: Dependency injection in general does not depend on typescript, and even in NestJS it can be done in (mostly) plain JavaScript by using Babel as a transpiler. I've gone into a bit of detail here about how the decorators work with typescript, and Semyon Volkov has shown how the decorators transpile as well. So inherently, no, it doesn't depend on Typescript, the way Nest wants you to do it (being opinionated and all) does.
In your example, Nest will read the type of design:paramtypes and see that there is a CatsService class, so it knows to match up the class names and inject a CatsService here. There's a lot more going on under the hood, when it comes to keeping track of what modules have access to what, but that's the general idea.


Q: Assigning to a quosure in R / dplyr / rlang Within a function, I want to update-in-place the values of columns specified by the user, where the user specified column names are captured via enquo(). So, here's a simplified example:
f1 <- function(df, x, y) {
    x <- enquo(x)
    y <- enquo(y)

    df %>%
        mutate((!! x) := (!! x)^2,
               (!! y) := (!! y)+1)
}

dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)

This fails with an error: "The LHS of := must be a string or a symbol".
I've also tried replacing, for example, (!! x) with quo_get_expr(x) and f_text(x), but get the same error. For example:
f1 <- function(df, x, y) {
    x <- enquo(x)
    y <- enquo(y)

    df %>%
        mutate(quo_get_expr(x) := (!! x)^2,
               quo_get_expr(y) := (!! y)+1)
}

Can anyone point out what I'm doing wrong?
I'm using R 4.1, dplyr 0.7.4, and rlang 0.2.0
Thanks in advance.

A: You need to use quo_name.  This works:
f1 <- function(df, x, y) {
  x <- enquo(x)
  y <- enquo(y)

  df %>%
    mutate(
     !!quo_name(x) := (!!x)^2,
     !!quo_name(y) := (!!y)+1)
}

dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)


Q: Why my key commands are not working My issue is that my javascript is not seeing when i push my key down to move the object on the screen.
So here is my java script code:
var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500,
  height = 400,
  speed = 3;

var player = {
  x: 10,
  y: 10,
  width: 20,
  height: 20
};

window.addEventListener("keydown", function (e) {
  keys[e.keycode] = true;
}, false);
window.addEventListener("keyup", function (e) {
  delete keys[e.keycode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game() {
  update();
  render();
}

function update() {
  if (keys[38]) player.y -= speed;
  if (keys[40]) player.y += speed;
  if (keys[37]) player.x -= speed;
  if (keys[39]) player.x += speed;
}

function render() {
  context.clearRect(0, 0, 100, 100)

  context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function () {
  game();
}, 1000 / 30);

if you can not tell i am very new to this and just learning the basics.

A: The value you want out of the event object is called keyCode, not keycode:

var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500,
  height = 400,
  speed = 3;

var player = {
  x: 10,
  y: 10,
  width: 20,
  height: 20
};

window.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
  delete keys[e.keyCode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game() {
  update();
  render();
}

function update() {
  if (keys[38]) player.y -= speed;
  if (keys[40]) player.y += speed;
  if (keys[37]) player.x -= speed;
  if (keys[39]) player.x += speed;
}

function render() {
  context.clearRect(0, 0, 100, 100)

  context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function() {
  game();
}, 1000 / 30);
<canvas id="maincanvas"></canvas>

A: Another issue you might be running into is that keys is an array and you are treating it like an object. keys[38] is looking for a key at index 38 NOT a key with a value of 38. Set keys = {};
Edit Never mind, I see you are just setting the index at 38. I would say it's a little bit of a weird approach, consider using an object rather than an array.


Q: How React rerenders tree, if both parent and child components are dependent from one Redux store prop? I have Layout component, which checks if a user is logged in. It simply examines user prop in Redux store. If it is, it renders children, otherwise Login.

*

*Layout.jsx
const Layout = ({ user, children }) => {
  if (user) return children;
  return <Login />;
};

export default connect(state => ({ user: state.user }))(Layout);

*

*Profile.jsx
const Profile = ({ user }) => <div>{user.name}</div>;

export default connect(state => ({ user: state.user }))(Profile);

*

*App itself

<Layout>
  <Profile />
</Layout>

The issue is when Profile component is rendered and I log out, I get can not read property name of undefined.
I expect Profile component not to be rendered at all, because it is how Layout works. But looks like React first tries updating Profile component and fails.
For now I ended up returning null from Profile if there is no user, but it's not ideal.
So if both parent and child components are dependent on one Redux store prop, React rerenders them from down to the top, from top to down, or simultaneously? Is there a canonical or best practice way to avoid it?


Q: Error MSB3073 when creating a Monogame C# project in Visual Studio 2019 So I'm trying to simply create a new Monogame project in Visual Studio 2019 with C#, and every time I create a new project, the following error appears:
Error MSB3073 - The command "dotnet C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\\..\tools\netcoreapp3.1\any\mgcb.dll /quiet /@:"E:\Programming\Locally-stored projects\C Family\C#\Monogame -OxygOS\Game1\Game1\Content\Content.mgcb" /platform:DesktopGL /outputDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/bin/DesktopGL/Content" /intermediateDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/obj/DesktopGL/Content" /workingDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/"" exited with code 1. Game1   C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\MonoGame.Content.Builder.Task.targets    138

The only files in the projects are ones that are automatically created as part of the Monogame Cross-platform template.
I've already looked on Google and Stack Overflow, and, while there are answers, I haven't found any that have helped me.
Apologies if I messed up while creating the post, this is my first Stack Overflow question :D I may have messed up the formatting somewhere so sorry in advance if  I have.

A: It is a better approach that you would use the terminal to create your project (and then open them in Visual Studio). It is far more convenient for the Monogame community to release NuGet templates of the projects rather than releasing plugins for Visual Studio, and therefore it is safe to assume that Monogame won't be releasing such plugins for Visual Studio anytime soon.
Make sure you have dotnet-sdk installed and the Monogame tools are installed by doing all the steps mentioned here, Including the last two scripts
dotnet tool install --global dotnet-mgcb-editor
mgcb-editor --register

and
dotnet new --install MonoGame.Templates.CSharp

Now use the command dotnet new to view all the templates. You will probably see an output such as

Templates                                                   Short Name               Language          Tags
------------------------------------------------------      -------------------      ------------      ----------------------
...
...
MonoGame Android Application                                mgandroid                [C#]              MonoGame
MonoGame Cross-Platform Desktop Application (OpenGL)        mgdesktopgl              [C#]              MonoGame
MonoGame iPhone/iPad Application                            mgios                    [C#]              MonoGame
MonoGame Windows Universal Application (CoreApp)            mguwpcore                [C#]              MonoGame
MonoGame Windows Universal Application (XAML)               mguwpxaml                [C#]              MonoGame
MonoGame Windows Desktop Application (Windows DirectX)      mgwindowsdx              [C#]              MonoGame
MonoGame NetStandard Library                                mgnetstandard            [C#]              MonoGame
MonoGame Pipeline Extension                                 mgpipeline               [C#]              MonoGame
MonoGame Shared Library Project                             mgshared                 [C#]              MonoGame
...
...

Select the project you want to create, for example
dotnet new mgwindowsdx -o MyGame

This will create a folder "MyGame" and put the code for your game. You can open the .csproj file using Visual Studio.


Q: webpack -- how to include nodejs module for js/jsx in non-current directory Trying to include a npm module in my jsx.
My dir structure is something like:
   app/
     node_modules/
     webpack.config.json
     package.json
     main.js

   react/
     myreact1.jsx
     myreact2.jsx

Note: purposely do not want a package.json & node_modules in react/
I've figured out that I have to do this for webpack2 config:
   resolve: {
     modules: ["node_modules", path.resolve(__dirname, "node_modules")
   }

This forces webpack to first always try ./node_modules, then default to app/node_modules
However, for the module I'm trying to include in myreact.jsx (npm: "request"), this module uses alot of native node libraries like "fs" and "tls", etc.
webpack now gives me this error:
Abbreviated error:
ERROR in ./~/request/lib/har.js
Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib'
 @ ./~/request/lib/har.js 3:9-22
 @ ./~/request/request.js
 @ ./~/request/index.js
 @ ../react/myreact1.jsx
 @ ./app.jsx
 @ ./main.js

Display-error-details version of the error:
ERROR in ./~/request/lib/har.js
Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib'
resolve 'fs' in '/myproj/app/node_modules/request/lib'

How do I get webpack to correctly find the native node modules 'fs', 'tls', 'net' etc for 'request' module and the other 3rd party modules it uses inside it's own node_modules?
Thanks for any help


Q: JsnLog error posting in angular 4 with elmah at server side We are using Asp.net Web API 2 - Server side
Angular 4 in client side (angular-cli)
We have integrated Elmah on the server side for error handling.
We have integrated Jsnlog in the client side.
Our angular released version is hosted in http://ng.local.com and API released version is hotsed in http://api.local.com/. Now, We have gone through the docs of Jsnlog configuration. But, facing issue in error posting to the server (to our api released http://api.local.com/) i.e missing some configuration.
Can anyone know the configuration for Jsnlog to have the URL of the API server.

A: There is information found here to configure the endpoint for JSNLog.  Take a look at the "Configuring JSNLog" Section of this page (http://jsnlog.com/Documentation/HowTo/Angular2Logging and http://jsnlog.com/Documentation/JSNLogJs/AjaxAppender/SetOptions).
But to summarize, just add this line to your app.module.ts before the @NgModule({...
// Set the endpoint for JSNLog.

JL().setOptions({ 'appenders': [JL.createAjaxAppender('example appender').setOptions({'url': [Your Desired Endpoint Address] + '/jsnlog.logger'})] });

@NgModule({
...


Q: Freeing map of struct I am working with a very large map of pointer to struct. It is growing over the lifetime of the program (I use it as a buffer) and I wrote a function that is supposed to reduce it size when it is called.
type S struct {
 a uint32
 b []uint32
}

s := make(map[uint32]*S)

for k, v := range s {
  delete(s, k)
  s[k] = &S{a: v.a}
}

I remove b from every element of the map, so I expected the size of the map in memory to shrink (b is a slice of length > 10). However the memory is not freed, why?

A: The size of the map value &S, a pointer, is the same irrespective of the capacity of slice b.
package main

import (
    "fmt"
    "unsafe"
)

type S struct {
    a uint32
    b []uint32
}

func main() {
    size := unsafe.Sizeof(&S{})
    fmt.Println(size)

    size = unsafe.Sizeof(&S{b: make([]uint32, 10)})
    fmt.Println(size)

    s := make(map[uint32]*S)

    for k, v := range s {
        delete(s, k)
        s[k] = &S{a: v.a}
    }
}

Output:
8
8

A slice is represented internally by
type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

When you set &S{a: v.a} you set b to initial values: array to nil and len and cap to zero. The memory formerly occupied by the underlying array is returned to the garbage collector for reuse.

A: The map size is bounded to the maximum size it had at any point. Because you store pointers (map[uint32]*S) and not values the deleted objects will get garbage collected eventually but usually not immediately and that why you don’t see it in top/htop like monitors.
The runtime is clever enough and reserves memory for future use if the system is not under pressure or low on resources.
See https://stackoverflow.com/a/49963553/1199408 to understand more about memory.
In your example you don't need to call delete. You will achieve what you want just by clearing the slice in the struct.
type S struct {
 a uint32
 b []uint32
}

s := make(map[uint32]*S)

for k, v := range s {
  v.b = []uint32{}
}