text:
Q: Passing Enums as parameter from abstract class I have an abstract base class, TestFactory which looks like:
    public abstract class TestFactory
    {
        //static method that can create concrete factories
        public static TestFactory CreateTestFactory(FactoryType factoryType)
        {
            TestFactory factory = null;
            switch (factoryType)
            {
                case FactoryType.Blood:
                    factory = new BloodTestFactory();
                    break;
                case FactoryType.Urine:
                    factory = new UrineTestFactory();
                    break;
                default:
                    break;
            }
            return factory;
        }
        //BloodTestFactory and UrineTestFactory are concrete types
        //that will need to create their own tests
        //this enum parameter needs to 'switch' between
        //BloodTestType and UrineTestType
        public abstract LabTest CreateTest(Enum e);
    }
    public enum FactoryType
    {
        Blood,Urine
    }

So this class creates a concrete factory like:
    public class BloodTestFactory :TestFactory
    {

        //both BloodTestFactory and UrineTestFactory will create a LabTest object
        //I would like to have a BloodTestType and UrineTestType enum, what do I need
        //to do to pass a generic Enum as a parameter and then switch on BloodTestType

        public override LabTest CreateTest(Enum e)
        {
            BloodTest bt = null;
            //switch (e)
            //{
            //    default:
            //        break;
            //}
            //creation logic here
        }
    }
    public enum BloodTestType
    {
        H1AC,Glucose
    }

A BloodTest itself is an abstract class which will return a concrete BloodTest object based on the Enum value.  For clarity's sake I would like to have a BloodTestType and a UrineTestType (not shown) enum.  Since the CreateTest method is abstract, how can I make sure that I can pass it a BloodTestType when I want to create BloodTests and a UrineTestType enum when I want to create UrineTest?

A: I'm not sure if this is the best approach to take for this requirement, I'll leave the design pattern discussion for comments / other answers.
I wouldn't necessarily do it this way, however, to make the code you have work, I would introduce a class level generic parameter on TestFactory for the enum.
public abstract class TestFactory<TTestType>
{
    public abstract LabTest CreateTest(TTestType testType);
}

Derived classes then simply specify the generic argument:
public class BloodTestFactory : TestFactory<BloodTestType>
{
    public override LabTest CreateTest(BloodTestType e)
    {
    }
}

Note that unless you use something like Unconstrained Melody you don't get much support for generic type constraints on enum.
Also note that this now makes it difficult to reference the shared base class because you need to close the generic argument:
TestFactory baseReference = myBloodTestFactory; // Not possible.

TestFactory<BloodTestType> baseReference = myBloodTestFactory;

Personally I'd likely decompose these two factories into separated classes without a base, or look into using an interface. Dealing with specific parameters in what you would like to have as "common" methods is difficult.

A: There is a nice way of doing this, and it results in code such as:
var client = new LabTestClient();
client.Run<BloodTestFactory,BloodTestType>(BloodTestType.H1AC);
client.Run<BloodTestFactory,BloodTestType>(BloodTestType.Glucose);
// outputs
//   BloodTest: H1AC
//   BloodTest: Glucose

Here is the rest of the code, hopefully its quite self explanatory how to use it/extend it to your needs - there are concrete classes for each type of lab test.
First the client and the abstract classes
public class LabTestClient
{
    public void Run<TFactory, TInput>(TInput input) where TFactory : LabTestFactory, new()
    {
        LabTestFactory factory = new TFactory();;
        LabTest labTest = factory.CreateLabTest();
        labTest.Run(input);
    }

}

public abstract class LabTest
{
    public abstract void Run<TInput>(TInput input);
}

public abstract class LabTestFactory
{
    public abstract LabTest CreateLabTest();
}

Then the concrete implementation:
public enum BloodTestType{ H1AC,Glucose }

public class BloodTest: LabTest
{
    public override void Run<TInput>(TInput input)
    {
        Console.WriteLine("BloodTest: {0}",input);
    }
}

public class BloodTestFactory : LabTestFactory
{
    public override LabTest CreateLabTest()
    {
        return new BloodTest();
    }
}

public enum UrineTestType{ A,B }

public class UrineTest: LabTest
{
    public override void Run<TInput>(TInput input)
    {
        Console.WriteLine("UrineTest: {0}",input);
    }
}

public class UrineTestFactory : LabTestFactory
{
    public override LabTest CreateLabTest()
    {
        return new UrineTest();
    }
}

A live example: http://rextester.com/MUV89315
However, this is still not ideal, as the individual tests still don't enforce their input - and in fact when you come to do anything complex within the test you'll find you don't know what the actual type of TInput is unless you cast it to the right enum:
public class UrineTest: LabTest
{
    public override void Run<TInput>(TInput input)
    {
        var urineTestType = (UrineTestType)input;
        // do something useful.
    }
}

A: Just test for type safety in your overriden method:
        public override LabTest CreateTest(Enum e)
        {
            BloodTest bt = null;
            if(!e.GetType.Equals(typeof(BloodTestType)))
            {
               // throw type exception of your choice
            }
        }

A: Just add an argument check to your base class:
public abstract class TestFactory
{
    //static method that can create concrete factories
    public static TestFactory CreateTestFactory(FactoryType factoryType)
    {
        if (!Enum.IsDefined(typeof(FactoryType), factoryType)
        {
             throw InvalidEnumArgumentException(...);
        }

        TestFactory factory = null;
        switch (factoryType)
        {
            case FactoryType.Blood:
                factory = new BloodTestFactory();
                break;
            case FactoryType.Urine:
                factory = new UrineTestFactory();
                break;
            default:
                break;
        }
        return factory;
    }
    //...
}


text:
Q: Parse error: syntax error, unexpected T_GOTO, expecting T_STRING or '(' in a/b/c/function.php on line 406
Possible Duplicate:
syntax error, unexpected T_GOTO, expecting T_STRING

I've uploaded this but it shows error:
<?
    function goto($url="") {
        echo"<meta http-equiv=\"refresh\" content=\"1;url=$url\">";
    }
?>

Parse error: syntax error, unexpected T_GOTO, expecting T_STRING or
  '(' in /a/b/p/function.php on line 406.

How can I fix this error?

A: goto is a php keyword, you can't use it as function name. Just change name of your function e.g.:
<?php
    function meta_refresh($url = "") {
        echo"<meta http-equiv=\"refresh\" content=\"1;url=$url\">";
    }
?>

A: The word goto is reserved in php, since it is the name of a builtin function. You just have to use another name for your function, that's all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xpath and images in php Trying to scrape images and data from a website using Xpath but keeps showing me an error.Could anybody help me out.
 <?php
$dom = new DOMDocument();
@$dom->loadHTMLFile('http://www.hassconsult.co.ke/index.php?option=com_content&view=article&id=22&Itemid=29');
$xpath = new DOMXPath($dom);

foreach($xpath->query("//div[@id='ad']/table") as $table) {
  echo $xpath->query(".//img[@align='centre']", $table)->item(0)->nodeValue . "\n";// should come in here don't know what to put
  echo $xpath->query(".//span[@class='style8']", $table)->item(0)->nodeValue."\n";
  echo $xpath->query(".//div[@class='style10']/div", $table)->item(0)->nodeValue."\n";

  echo $xpath->query("//div[@align='justify']", $table)->item(0)->nodeValue. "\n";
}

?>

This is the outline as given buy firebug

A: As I said in comment : attributes :
echo $xpath->query(".//img[@align='centre']", $table)->item(0)->getAttribute('src'). "\n";

A: the example you pointed to doesn't have any IMG tags with attribute align='centre' -- if you remove [@align='centre'] you'll be able to use getAttribute('src') as Shikiryu indicates, e.g.
echo $xpath->query(".//img", $table)->item(0)->getAttribute('src'). "\n";


text:
Q: NestJS - Get current user from request and validate query params I have a route /users to get user list, the controller method needs to get current user, also needs to validate input query params. So I write like this:
    @UseGuards(AuthGuard('jwt'), RolesGuard)
    @Roles(UserRole.GLOBAL, UserRole.ORG)
    @Get('users')
    findAll(@Request() req, @Query() query: FindAllUsersDto) {
      //code here.
    }

This works. I am wondering if this is a little duplication. Because I can use req.query to get query object. But if I don't write @Query() query: FindAllUsersDto, the validation pipe won't work. So is my code meaningful or is there a more simple way? Thanks.


text:
Q: Updating data from checkbox clicked My Code so far. The data gets pulled correctly
    if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Request");

echo "

First Name
Last Name
Prayer Request
Deactivate Request

";

while($row = mysqli_fetch_array($result))
  {
  echo "
";
  echo "" . $row['Reg_F_Name'] . "	";
  echo "" . $row['Reg_L_Name'] . "	";
  echo "" . $row['Reg_Request'] . "	";
  echo "<input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"".$rows['Reg_ID']. "\" />	";
  echo "
";
  }
echo "
";

echo
"<form action='' method='post'>
<input type='submit' name='use_button' value='Update' />
</form>";

if(isset($_POST['use_button']))
{
    echo "hey";
$del_id = $_POST['checkbox'];
$detectinglocations = 'your database table name';

foreach($del_id as $value){
   $sql = "Update Request  set Reg_Status=0 WHERE Reg_ID='".$value."'";
   $result = mysql_query($sql);
}

}

mysqli_close($con);

?>

Nothing Happens when I Click Submit. I am wanting it to Update the reg_Status to 0 for every check box that is click. So whats my problem. Thank you in advance for helping!

A: try adding an input hidden field with same name as the checkbox name before each checkbox and with value 0 .
The checkbox doesnt get posted when not checked.


text:
Q: Styling Points of Vector Grid in Leaflet I am using the Leaflet Vector Grid Plugin to load a geojson innto my Leaflet project. But I can't figure out how to implement a popup and style the data by attributes.
I load up the data with following command:
 L.vectorGrid.slicer(data).addTo(map);

How can I implement my functions for the style:
 function Kategorie(feature, latlng) {
        switch(feature.properties["categorie"]) {
            case "1":
                var Icon1 = new L.icon({
                    iconUrl: 'icons/1.png',
                    iconSize:     [15, 15],
                    iconAnchor:   [5, 5],
                    popupAnchor:  [10, 10] o
                });
                return L.marker(latlng, {icon: Icon1});

and the function of the pop up:
  function popupcontent(feature, layer) {

                var popUp = "
"+feature.properties.Name+"
"  ;

                layer.bindPopup(popUp);}

I already studied the documentation of the plugin but I just don't get it.

A: You need to define a style function, as you did named Kategorie, for vectorTileLayerStyles option, use the getFeatureId function to get the id of each feature, and set interactive : true. The code below will guide you through the steps. Good luck.
var Kategorie = function (properties, zoom) {
... // as you have done above
}

var style = {
          rendererFactory: L.svg.tile, // L.canvas.tile
          vectorTileLayerStyles: {
            sliced: Kategorie
          },
          interactive: true,
          getFeatureId: function (f) {
          return f.properties['EventID'] // look for a unique ID in your data
          }
        }

Then get a control name for the vectorlayer rather than only adding it.
vectorgrid = L.vectorGrid.slicer(data, style) // data is parsed GeoJSON

Then add an on click function:
      vectorgrid.on('click', function (e) {
      var properties = e.layer.properties
      var popUpText = Object.entries(properties)
        .map(function ([key, val]) {
          return `${key}: ${val}`
        })
        .join('
')
      L.popup()
        .setContent(popUpText)
        .setLatLng(e.latlng)
        .openOn(map)
    })
    vectorgrid.addTo(map)
  })


text:
Q: AWS X-ray with SQS fanout pattern I am trying to use x-ray to trace requests which use an SNS-SQS fanout pattern.
The request comes from API GW, lambda proxy integration, published to SNS and delivered to a subscribed SQS which has a lambda trigger which receives the messages for further processing.
However the trace stops at SNS.

A: Unfortunately we do not support this architecture today. The issue is that the trace information from the starting request (APIG in this case) is lost once the SNS message is invoked. There currently isn't a workaround for this behavior. We are working with SNS and SQS to provide a better user experience and support for these cases. Please stay tuned for more.


text:
Q: Mule datamapper DateTime conversion gives unparsable date for String 'yyyy-MM-dd'T'HH:mm:ss.SSSZ' I have a request xml having a dateTime string as '2014-09-23T00:00:00.000+01:00' and I am mapping it to an element of type xs:dateTime using Mule 3.5 datamapper.
The Datamapper internally applies str2Calendar(Str,Str) function or mapping.
So I edited the script to look like:
output.dateAndTimeString = str2calendar(input.dateAndTime, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");

The error in log is:
java.text.ParseException: Unparseable date "2014-09-23T00:00:00.000+01:00"

Is anything wrong with Mule data-mapper or with my conversion technique?

A: You can drop the 'Z' and use the overloaded str2calendar to set the default timezone. This example uses the MEL expression to get the servers timezone:
output.dateAndTimeString = str2calendar(input.dateAndTime, "yyyy-MM-dd'T'HH:mm:ss.SSS", server.timeZone);


text:
Q: Extend USB 3.0 cable I have a couple of new USB 3.0 devices which connect to my USB 3.0 ports via the new "Blue" USB 3.0 cables that end in what looks like a USB 2.0 Type A connector.  Indeed, the USB 3.0 devices will also work in the USB 2.0 ports.
So, I have some USB 2.0 extender cables.  While I obviously can run the USB 3.0 devices over the USB 2.0 cables, will I be able to get the USB 3.0 speeds or do I need to get the specific USB 3.0 cables - to get the maximum transfer speeds?
It's not the cost - you can get the cables cheap.  It's just understanding how the end-to-end system works (and the "in case of emergency - break glass" effect).

A: USB 3.0 is electrically different from USB 2.0 - it has extra connectors/wires designed in such a way as to gracefully plugged into a USB 2.0 connector - they're located on the 'tongue' where there's nothing on a USB 2.0 connector

As such connecting a USB 3.0 port to a USB 2.0 extension to a USB 3.0 cable will result in usb 2.0 speed, since the extra connectors will not be connected to anything in the USB 2.0 extension cord on either end.

A: Why you can't rely on extending a USB 3.0 cable at all.
USB 3.0 + USB 2.0 Cables
There are a number of existing answers that explain how the USB 3.0 cable contains additional wires specific to USB 3.0 high-speed communication, so you can't use a USB 2.0 cable to extend a USB 3.0 connection and retain the speed.
Full-length USB 3.0 cables + hub
Jcordeiro's answer goes farther to discuss the problem he experienced trying to use a hub to significantly extend the distance using USB 3.0 cables.
Multiple USB 3.0 cables to reach 3 meters
The limitation doesn't end there.  You can't even count on combining short USB 3.0 cables to reach the length limit.
As Jcordeiro's answer mentions, the USB 3.0 standard does not specify a maximum cable length, only that the cable has to meet all of the electrical specifications.  The 3 meter limit is based on maximum allowable losses using 26 AWG wire for the high-speed signal wires.
The spec is concerned with cable flexibility, so it includes a range of recommended wire gauges (there are four types of wires in the cable, each with a different recommended range).  For the high-speed signal wires, the recommended range is 26-34 AWG (26 being the largest diameter).  The 3 meter limit is based on the largest recommended wire size.  If smaller wire is used, the losses will be higher, so the maximum cable length is shorter.
So if you have several short USB 3.0 cables laying around, particularly if they're thin and flexible, chances are they were made with smaller gauge wire that is perfectly adequate for a short cable.  However, they may not support being strung together to make a 3 meter cable that handles USB 3.0 speed.

The full spec is available here.

A: Well, i have been experimenting with USB 3 and it just made me sad.
Do not expect to get any USB 3 device working at USB 3 speed with any type of extender.
As wikipedia says here:

Unlike previous standards, the USB 3.0 standard does not directly specify a maximum cable length, requiring only that all cables meet an electrical specification: for copper cabling with AWG 26 wires the maximum practical length is 3 meters (9.8 ft)."

Even a simple change of the usb cable from 50cm to 1.5m may disable the USB 3 speed.
And even if you put an usb hub, and it says USB 3, when you connect the device it will be connected on the 2.0 fallback hub.
So if you are considering, extending a single USB 3 from your computer to your desk, i would advise against it.
Use USB 2 for now, wait a while until decent cables and hubs arrive. (Or USB 3.1 or even USB 4.)

A: To get USB 3.0 speeds you need a USB 3.0 cable because of the extra connectors involved
Set USB3.0 controller to USB2.0 only

A: The maximum cable length USB 3.0 supports is reduced to approximately three meters, opposed to five meters with USB 2.0. However, using hubs, the maximum length can be extended to 18 meters.However the pin layout is different and using USB 2.0 Cables will allow maximum transfer of USB 2.0


text:
Q: Modify List.Contains behavior I have a List<MyObj> with the class MyObj : IComparable. I wrote the method CompareTo in the MyObj class per the IComparable interface, but when I use the List<MyObj>.Contains(myObjInstance) it returns false when it should be true.
I'm not sure I'm understanding how I need to proceed to make sure the List uses my custom comparison method when calling then Contains function.
Here is my compareTo implementation:
    #region IComparable Members

    public int CompareTo(object obj)
    {
        MyObj myObj = (MyObj)obj;
        return String.Compare(this.Symbol, myObj.Symbol, true);
    }

    #endregion

Note the Symbol property is a string.
To clarify I've put a stopping point in that compareTo method and it doesn't even go in there.
Anyone has ever tried that?
Thanks.

A: According to the documentation for List<T>.Contains, it uses either your implementation of IEquatable interface or object.Equals, that you can override as well.

A: The absolute easiest way to find out whether your CompareTo method is called is to set a breakpoint in it and hit F5 to run your program. But I believe that List<T>.Contains looks for the IEquatable<T> interface for making the comparison.

A: Did you try overriding the Equals method?
List<T>, according to reflector, uses EqualityComparer<T> to check for containment, and the default implementation (ObjectEqualityComparer) uses Equals for most normal objects.


text:
Q: How to get current network usage of app (or in total), even on Android N? As the title says. I wish to know how many bytes per second a specific app use at specific time.
Maybe I can use "netstat" command? But if so, how can I filter it to a specific app/process ?
Do I also need to have some permission to do it?
Currently people say to use TrafficStats.getUidRxBytes(packageInfo.uid) , but, from here: https://developer.android.com/reference/android/net/TrafficStats.html#getUidRxBytes(int) , it says it's not supported from N , and that I should use NetworkStatsManager instead. Is there any example to use it?
Maybe a merged solution?
EDIT: I tried to use NetworkStatsManager on Android N, but I failed. I can't find any sample of how to use it, and all stackOverflow questions about it were similar in term of not being able to use it well. Please, if anyone knows how to use it, write about it.

A: The usage of NetworkStats is not complicated.
The device API level must be at minimum 23. Here are some steps required prior to starting the usage of NetworkStatsManager

*

*Declare the required permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions"/>

*Ask for permission in Activity
android.permission.PACKAGE_USAGE_STATS is not a normal permission, therefore cannot be simply requested. In order to check, whether the permission has been granted, check:
AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
        android.os.Process.myUid(), getPackageName());
if (mode == AppOpsManager.MODE_ALLOWED) {
    return true;
}

To ask for this permission, simply call Intent:
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);

Another permmission is also needed: Manifest.permission.READ_PHONE_STATE. However, this is normal permission so can be requested as any other permission

*Use NetworkStatsManager:
To obtain it's reference, call:
NetworkStatsManager networkStatsManager = (NetworkStatsManager) getApplicationContext().getSystemService(Context.NETWORK_STATS_SERVICE);

Everything that is retrieved from NetworkStatsManager is packed into Buckets. This is just a simple POJO, that holds the data.
GLOBAL:
To get the overall usage for WiFi:
NetworkStats.Bucket bucket;
try {
    bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,
            "",
            0,
            System.currentTimeMillis());
} catch (RemoteException e) {
    return -1;
}

from NetworkStats.Bucket, two methods can be called to get the usage (in Bps):
bucket.getRxBytes();
bucket.getTxBytes();

Obtaining the data for mobile network is harder. In order to obtain the Bucket call:
public long getAllRxBytesMobile(Context context) {
    NetworkStats.Bucket bucket;
    try {
        bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
            getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
            0,
            System.currentTimeMillis());
    } catch (RemoteException e) {
        return -1;
    }
    return bucket.getRxBytes();
}

//Here Manifest.permission.READ_PHONE_STATS is needed
private String getSubscriberId(Context context, int networkType) {
    if (ConnectivityManager.TYPE_MOBILE == networkType) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSubscriberId();
    }
    return "";
}

APPLICATION:
For obtaining the data for specific application, read the documentation for queryDetailsForUID.
To get the package usage for WiFi:
NetworkStats networkStats = null;
try {
    networkStats = networkStatsManager.queryDetailsForUid(
            ConnectivityManager.TYPE_WIFI,
            "",
            0,
            System.currentTimeMillis(),
            packageUid);
} catch (RemoteException e) {
    return -1;
}
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);

To get the package usage for Mobile:
NetworkStats networkStats = null;
try {
    networkStats = networkStatsManager.queryDetailsForUid(
            ConnectivityManager.TYPE_MOBILE,
            getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
            0,
            System.currentTimeMillis(),
            packageUid);
} catch (RemoteException e) {
    return -1;
}
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);

Unfortunately, according to this piece of code getting statistics is only possible for ConnectivityManager.TYPE_MOBILE and ConnectivityManager.TYPE_WIFI.
Made a sample Github repo demostrating the usage.

A: Adding my simplified function to get overall network usage via /proc/net/dev.
No unique permission is needed.
public static long[] getNetworkUsageKb() {
    BufferedReader reader;
    String line;
    String[] values;
    long[] totalBytes = new long[2];//rx,tx
    try {
        reader = new BufferedReader(new FileReader("/proc/net/dev"));

        while ((line = reader.readLine()) != null) {
            if (line.contains("eth") || line.contains("wlan")){
                values = line.trim().split("\\s+");
                totalBytes[0] +=Long.parseLong(values[1]);//rx
                totalBytes[1] +=Long.parseLong(values[9]);//tx
            }
        }
        reader.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    //transfer to kb
    totalBytes[0] =  totalBytes[0] / 1024;
    totalBytes[1] =  totalBytes[1] / 1024;

    return totalBytes;
}

A: There is also a complicated way to get statistics, but this should work for all adapters: (but it is expensive, because you have to read files continously),

*

*Here you can see all your adapters and the sent/received data:

cat /proc/net/dev

*You can get statistics per adapter from these files:

cat /sys/class/net/**wlan0**/statistics/**rx**_bytes

wlan0 could be all of your adapters, but you need to maintain the value in your app, because if you switch off/on the adapter, the value will be 0 again. (You can have RX and TX values)

*You can get the active, currently sending/receiving app list

cat /proc/net/**tcp6**

This also can be done with tcp, tcp6, upd, upd6
Here you have the "uid" column, which is the UID of your installed apps.
(So that app is using the network right now)
From this file you can also see the connection endpoint.

*Check sent/received bytes per application (like the TrafficStats API calls)

cat /proc/uid_stat/**10348**/tcp_snd

The id here is the application UID.
You have the sent: tcp_snd and the received: tcp_rcv files too.

*You can also do some process and UID matching with:

cat /proc/**17621**/status

The id here is the process id what you can get from e.g. the top command.
In the status file you will have the UID, which is the installed/system app UID.
+1. You can take a look also on this file, TrafficStats API uses this:

cat /proc/net/xt_qtaguid/stats

Headers:
idx iface acct_tag_hex uid_tag_int cnt_set rx_bytes rx_packets tx_bytes tx_packets rx_tcp_bytes rx_tcp_packets rx_udp_bytes rx_udp_packets rx_other_bytes rx_other_packets tx_tcp_bytes tx_tcp_packets tx_udp_bytes tx_udp_packets tx_other_bytes tx_other_packets

Values:
6 eth0 0x0 10005 0 0 0 80 2 0 0 0 0 0 0 80 2 0 0 0 0
7 eth0 0x0 10005 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
8 eth0 0x0 10007 0 11133 25 4751 24 11133 25 0 0 0 0 4751 24 0 0 0 0
9 eth0 0x0 10007 1 5965514 4358 102028 2327 5965514 4358 0 0 0 0 102028 2327 0 0 0 0
10 eth0 0x0 10014 0 95 1 40 1 95 1 0 0 0 0 40 1 0 0 0 0

So maybe mixing the first answer with this knowledge, you can have more and better statistics.


text:
Q: Spark Structured streaming ForeachWriter unable to get sparkContext I'm reading JSON data from Kafka queue usingSpark structured streaming but I need to write the JSON data into Elasticsearch.
However, I can't get sparkContext inside the ForeachWriter to convert the JSON to RDD. It throws NPE.
How can I get SparkContext in the Writer to convert the JSON to RDD?

A: You cannot. The methods in ForeachWriter run in the executors. You can either write a Elasticsearch sink by yourself, or call Elasticsearch's raw APIs to write the data.


text:
Q: What is the purpose of metadata in xml file? I saw a program in which they use metadata. What is the purpose of this..?
"meta-data android:name="android.app.device_admin"
           android:resource="@xml/device_admin_sample" "

A: They "need this" because the documentation tells them they "need this". In this case, they are implementing a device admin app, and the documentation for such apps tells them that they need to create this metadata file, specifically to list the security policies they require.
More generally, <meta-data> is a way to add more information about a component, that might be used by frameworks utilizing that component.


text:
Q: crash when using EKEventEditViewController I have a weird crash that I don't know how to debug...
Here is the code:
-(void) addEventButtonPressed:(UIButton*)button{
DLog(@"Add new event");
// If event is nil, a new event is created and added to the specified event store. New events are
// added to the default calendar. An exception is raised if set to an event that is not in the
// specified event store.
// When add button is pushed, create an EKEventEditViewController to display the event.
EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];

// set the addController's event store to the current event store.
addController.eventStore = self.eventStore;
addController.editViewDelegate = self;

// present EventsAddViewController as a modal view controller
[self presentModalViewController:addController animated:YES];

}
My app crashes after a looong time at this line:
[self presentModalViewController:addController animated:YES];
I am using ARC.
Any clues?
Thanks!
My console says just EXC_BAD_ACCESS(code=2, address=0xbf7ffff4)
[EDIT] It seems eventStore needs to be initialized before passing it to addController or you get a crash. In my case it was nil.

A: Make sure that you are presenting the EKEventEditViewController from the main thread; it will crash (not always, but usually) if you present it from a secondary thread.


text:
Q: Crystal Reports: why is memo-type field truncated at 255 characters? I'm working in Crystal Reports XI (11.5.12.1838) running on a remote Windows system and accessed via Citrix. The data is coming from a Blackbaud Raiser's Edge export.
I have two different custom reports which need to display a Note (from Raiser's Edge) that can be of any length. In both cases, the database line was just dragged and dropped into a field in the report. It's set to grow with no maximum. In one report, it works; in the other, it does not, but truncates the text at 255 characters (or perhaps bytes: the RTF version was cut off earlier in the text).
The criteria for the reports are different (one is reporting on a single constituent, the other [which doesn't work] on constituents connected to a specific individual). However, I don't know well enough what might cause this problem to narrow down what aspects of the report configuration need adjustment.
Any ideas? I'll note that in the broken report the field grows correctly and is type 'memo' -- it just grows enough to hold 255 characters and then stops.
Edit: no, formula fields aren't involved. I can't really split the string in the database.
Edit 2: Thank you all for your suggestions. Database is up-to-date and field shows as Memo in Crystal Reports. Joins are the same in both reports (the one that works and the one that doesn't) and the memo field isn't involved in linking. CR annoyingly won't let you browse data on a memo field, but the Length() function is returning 255 for the field. Unless you all can think of a reason for CR to truncate the data, I may have a bug in Raiser's Edge causing this problem.
Edit 3: I pulled up the MDB in a hex editor and the full text (past 255 characters) is there, so I'm doing something wrong in Crystal Reports and can't blame Blackbaud for this one.
Edit 4: Finally fixed! Okay, I don't understand why this was the problem, but I discovered purely by accident that selecting and unselecting "Select Distinct Records" causes this problem. If it's on, the memo gets truncated. If it's off, it doesn't. Can any of you explain to this poor fool why that happens?

A: I have just resolved the same problem and discovered that a text formula value in the report was being truncated at 255 characters, due to an unmapped data field, revealed by the verify database option.
Once I had dealt with the unmapped data field, the truncated field immediately expanded its output beyond 255 characters.


text:
Q: Regex in JavaScript which allow maximum 10 digits, only one underscore in between the digits and prevent entering underscore after the first 5 digits I am looking for a regex that can be used to mask input field value. The conditions are following

*

*Only digits and underscore are allowed

*Only one underscore is allowed

*Maximum 10 digits are allowed

*Prevent entering underscore after the first 6 digits.

*After the first 5 digits(if there no underscore added) there should display an underscore automatically

*There should not be more than 5 digits after the underscore.
/^\d*\_?(?:\d{1,5})?$/

The above expression can address conditions 1 and 2.
A few examples :
12345_67890 - Valid
123456_7890 - Not valid
12345_678901 - Not valid
1234A -Not valid
12345 - Valid
12_45_56 - Not Valid
12_45 - Valid
_12 - Valid
12_ - Valid
-678901 - Not valid

A: You may use this regex:
^(?=(?:_?\d_?){1,10}$)\d{0,5}_?\d{0,5}$

RegEx Demo
RegEx Details:

*

*^: Start

*(?=(?:_?\d_?){1,10}$): Positive lookahead to allow between 1 to 10 digits

*\d{0,5}: Match 0 to 5 digits

*_?\d{0,5}: Match an optional underscore followed by 0 to 5 digits

*$: End

*After the first 5 digits(if there no underscore added) there should display an underscore automatically

Based on edited question. If you want to insert a _ after 5 digits if it is missing then use above regex for match then use this next one for replace:
var repl = str.replace(/^(\d{5})(\d*)$/, '$1_$2')

A: Try this one.
^(?<=\d{0,5})\d{0,5}_?\d{0,5}(?=\d{0,5})$

Here's how this regex works.

*

*\d{0,5}_?\d{0,5}
This matches the required condition. Total of 10 digits and, _ cannot appear after 5 of them. So there we go. We check if atmost 5 digits appear, before and after _ .

*(?<=\d{0,5})
Positive lookahead operator. Checks if there is atmost 5 digits or atleast no digits before _.

*(?=\d{0,5})
This is the positive lookbehind operator. This checks there is atleast none or atmost 5 digits behind _.

*^ ... $
This match the whole string from start to end of the line.
To know more about how lookaround operators work in regex, click here.
You can see the working regex here.
Note:
Regarding the point 5 of your question, there is no single way of doing what you want. For example, if you have an input box and you're checking the input dynamically on onChange event and want to insert _ after the first 5 inputted digits then depending on which framework (React/Angular/Vue) you're using, there can be different ways of achieving that.


text:
Q: How to add a vertical line at a specific datapoint in WPF Toolkit Chart I have created a multi series line chart but I need to add a vertical line marker at the beginning and at the end of a cycle. I have researched everywhere and can't find how to do it.  I need to do it from code behind because the value changes with every chart.
Any help is greatly appreciated.

A: The only way I found to add a vertical line was to add a datapoint at a specific x and y value.  Notice that the two datapoints have the same X value.  One starts at y value of 100 and the other one at 1200 thus making it a straight vertical line.
            //******************************************************
        //This is for plotting vertical lines
        //******************************************************
        lsStartCycle.IndependentValueBinding = new Binding("Key");
        lsStartCycle.DependentValueBinding = new Binding("Value");

        lsStartCycle.ItemsSource = new KeyValuePair<DateTime, int>[]
        {
        new KeyValuePair<DateTime,int>(MyFunctions.StartCycleTime, 100),
        new KeyValuePair<DateTime,int>(MyFunctions.StartCycleTime, 1200) };

In XAML I added a new series.
                <DVC:LineSeries Name="lsStartCycle" Title="Cycle Start"
                        ItemsSource="{Binding}"
                        DataPointStyle="{StaticResource myLineDataPointStyle}"
                        PolylineStyle="{StaticResource DashedPolyLine}"
                        LegendItemStyle="{StaticResource HideLegend}"
                        IsSelectionEnabled="True">
                </DVC:LineSeries>

Note:  My advice is to stay away from WPF Toolkit Chart.  Use the MS Chart control instead, it is way way better.  I ended up using that chart instead.


text:
Q: Worker getting null when retrieving shared property For some reason, when I try to receive a shared property from a Worker (in AS3), the result is always null. That is, I send a value to a Worker using setSharedProperty(), when I retrieve it using getSharedProperty(), it always returns undefined/null.
Here's a simple test I set up:
package
{
    import flash.display.Sprite;
    import flash.system.Worker;
    import flash.system.WorkerDomain;

    public class Main extends Sprite
    {
        private var _worker:Worker;

        public function Main():void
        {
            if (Worker.current.isPrimordial)
            {
                initMain();
            }
            else
            {
                initWorker();
            }
        }

        private function initMain():void
        {
            _worker = WorkerDomain.current.createWorker(this.loaderInfo.bytes);

            _worker.setSharedProperty("message", "test");
            _worker.start();
        }

        private function initWorker():void
        {
            _worker = Worker.current;

            var message:String = _worker.getSharedProperty("message");

            trace(message);
        }

    }

}

When I trace message, the result is null. Although my main goal is to make an AIR app, I get the same result whether I'm compiling for AIR (3.7) or Flash Player (11.6, for some reason 11.7 doesn't recognise flash.system.Worker as a valid class).
I'm compiling using the Flex SDK, through FlashDevelop. Does anybody know what's wrong, maybe I've missed something in my code?

A: FlashDevelop now seems to have complete support for debugging workers which really wasn't the case on older versions (you could neither break, or trace inside workers). AIR SDK workers support has also progressed (I remember things working in release would break in debug version)
I just recompiled your sample with AIR SDK 14 release (14.0.0.110)
air14_sdk_win/bin/mxmlc -swf-version=25 -debug=true Main.as

and debugged it with Shockwave Flash Debugger 14,0,0,125 and FlashDevelop 4.6.1.30 and got the expected result:
[Starting debug session with FDB]
Created Worker 2
test

Beware that any element not up-to-date in your debugging chain (sdk/player/debugger) could result in problems for debugging workers


text:
Q: How to format unordered list in collapsible content I'm having a little bit of an issue with an unordered list inside a collapsible content div.  While the div is collapsing, The list appears without any styling; But, after the div finishes collapsing all the way, my css takes over and it displays with styling.
I will add my entire code here.  If you click on "My Routes" you'll understand what I'm talking about.  It's kinda tricky to explain.
Thanks,
Richard.

* {
  font-family: 'Roboto', sans-serif;
}

/* Every CSS rule for the Sidebar and it's contents */

.sidebar {
  height: 100vh;
  background-color: #fff;
}

.collapse {
  font-size: 14px;
}

.collapse ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

.collapse ul li {
  padding: 7px;
  border-radius: 4px;
  border-bottom: 1px solid #E2E6EA;
}

.collapse ul li:hover {
  background-color: #e2e6ea;
}

.collapse i {
  cursor: pointer;
  margin-left: 10px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">

      <button type="button" class="btn btn-light btn-md btn-block" data-toggle="collapse" data-target="#myroutes">My Routes</button>

              10/29/19 - Montgomery & Butler County

              10/12/19 - Clinton & Highland County

              10/05/19 - Indiana

A: This is because you are applying your styles to the list based on the parent having the class collapse which it won't have during the collapsing event but only when completed. A better way would be to add a class to your list
 and then target that in your css with .my-styled-list { ... }

A: Try this 100% it will work..!
ul{
    list-style-type: none;
}

A: Your style for your unorder list, ul, is dependent on .collapse class being defined on the parent element.
The reason it isn't applying while the div is collapsing is because collapse is replaced with collapsing on the div during that scenario.
See Components Collapse - Bootstrap documentation.

There are several implementations you could do here, but the one that makes the most sense to me is to define and apply your styles that account for collapsing - accounting of that state change.
That is, everywhere you are declaring a style selector for collapse, you should also declare for collapsing (where it makes sense to do so).

* {
  font-family: 'Roboto', sans-serif;
}

/* Every CSS rule for the Sidebar and it's contents */

.sidebar {
  height: 100vh;
  background-color: #fff;
}

.collapse,
.collapsing {
  font-size: 14px;
}

.collapse ul,
.collapsing ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

.collapse ul li,
.collapsing ul li {
  padding: 7px;
  border-radius: 4px;
  border-bottom: 1px solid #E2E6EA;
}

.collapse ul li:hover,
.collapsing ul li:hover {
  background-color: #e2e6ea;
}

.collapse i,
.collapsing i {
  cursor: pointer;
  margin-left: 10px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">

      <button type="button" class="btn btn-light btn-md btn-block" data-toggle="collapse" data-target="#myroutes">My Routes</button>

              10/29/19 - Montgomery & Butler County

              10/12/19 - Clinton & Highland County

              10/05/19 - Indiana

Note:
some styles (like font-size) that are declared on div.collapse (and div.collapsing) are inherited by their child elements so that is also a consideration here as well.


text:
Q: What is the right way of passing a value that needs to be initialized in the inheriting class's constructor to a base class's constructor? I have a StateMachine class that needs to receive an initial State value in the constructor so that the the crntState and nextState would not be null at construction.
public class StateMachine {
    State crntState;
    State nextState;

    public StateMachine(State initialState) {
        crntState = initialState;
        nextState = crntState;
    }
}

Problem is that I need to first create the value in the inheriting class's constructor before passing it to the base, since the IdleState constructor requires a reference to MovementSM
class MovementSM : StateMachine {
    Player player;
    IdleState idleState;
    MovingState movingState;

    public MovementSM(Player player) : base(/*I want to pass idleState here*/) {
        this.player = player;

        idleState = new IdleState(this); //idleState can be declared only after the call to the base constructor
        movingState = new MovingState(this);
    }
}

I realize that I can initialize crntState and nextState in a seperate function and call it from MovementSM's constructor, but then the compiler gives a warning that the non-nullable fields of crntState and nextState must contain non-null value when exiting the constructor.
I could make them nullable, but they don't have any logical reason to be nullable in the program.
I could also assign them dummy values in the constructor before assigning them actual values in the separate function, but that just defeats the whole purpose of making sure the fields are being assigned at construction, plus this idea includes a pointless step of assignment to crntState and nextState just to keep the compiler quite...
So with all that considered, what is the best way of addressing that problem?
EDIT:
Some people suggested that if I removed the need to pass this to the state constructors, I could pass new IdleState() to the base, and get it back to idleState by doing idleState = crntState. Beside thinking that passing this is the correct solution in my case (explanation in the comments), I think passing the value first to the base could be really ugly.
For exmaple, I have this same problem with an Animation instance that I wanted to pass from a class to it's base, and it looks like that:
walk = new Animation(new[]{
    (new IntRect(16, 0, 16, 32), new Vector2i(0, 0), 0.2f),
    (new IntRect(32, 0, 16, 32), new Vector2i(0, 0), 0.2f),
    (new IntRect(16, 0, 16, 32), new Vector2i(0, 0), 0.2f),
    (new IntRect( 0, 0, 16, 32), new Vector2i(0, 0), 0.2f),
});

Putting all that in a the base call just to later do walk = crntAnimation is really ugly in my opinion.
Even more so, what if I wanted to generate that value using a for loop for example? Then passing it to base first would not only be ugly, but impossible.


text:
Q: Apply functions in different csv files in R with Already made some research about loops in R and found that most of them focus only on how to change file or variable name with loops like Change variable name in for loop using R could find a good solution from other articles of bloggers....
The following is what I want to do with my original data(s1P...s9P) to get new data(s1Pm...s9Pm) by calculate their means according to the Datum column in (s1P...s9P).
Running the following lines one by one is okay, however, it seems like there should be a possibility to use loops to make it tidy.
Any suggestions would be appreciated. Have a nice weekend!
s1Pm = aggregate(s1P, list(s1P$Datum), mean)
s2Pm = aggregate(s2P, list(s2P$Datum), mean)
s3Pm = aggregate(s3P, list(s3P$Datum), mean)
s4Pm = aggregate(s4P, list(s4P$Datum), mean)
s5Pm = aggregate(s5P, list(s5P$Datum), mean)
s6Pm = aggregate(s6P, list(s6P$Datum), mean)
s7Pm = aggregate(s7P, list(s7P$Datum), mean)
s8Pm = aggregate(s8P, list(s8P$Datum), mean)
s9Pm = aggregate(s9P, list(s9P$Datum), mean)

A: We can load all the objects in a list with mget and then apply the aggregate by looping through the list
outLst <- lapply(mget(paste0("s", 1:9, "P")),
             function(x) aggregate(x, list(x$Datum), mean))
names(outLst) <- paste0(names(outLst), "m")

It is better to keep the output in a list rather than creating multiple objects.  But, it can be done as well
list2env(outLst, envir = .GlobalEnv)

though not recommended


text:
Q: Which package is required to use $\rmint (R)$? Which package is required to use $\rmint (R)$? could anyone tell me please?
EDIT:
I am trying to symbolize the integral closure of $R$ in $S$ by $\int (R)$ that is what I am trying to type.

A: The question is impossible to understand but as clarified in comments it appears that you want

\documentclass{article}

\usepackage{amsmath}
\DeclareMathOperator\rmint{int}

\begin{document}

$\rmint(R)$

\end{document}


text:
Q: Extend dictionary when Value has associated type Consider the following:
struct Weak<Object: AnyObject> {

    weak var object: Object?
}

class ConcreteClass { }

extension Dictionary where Value == Weak<AnyObject> {

    func foo() {
        print("Success!")
    }
}

var dict: [String: Weak<ConcreteClass>] = [:]

Now, the next line won't compile
dict.foo()  //  Referencing instance method 'foo()' on 'Dictionary' requires the types 'Weak<ConcreteClass>' and 'Weak<AnyObject>' be equivalent

Is there a way to tell the extension that Weak.Object doesn't matter for foo() to do it's job?

A: The issue is that Weak<AnyObject> is a concrete type that you can create an instance of that is different than a Weak<ConcreteClass>. You need to express the relationship through an assoicatedtype on a protocol.
You can adjust your code like this to achieve the desired result:
protocol WeakProtocol {
    associatedtype Object: AnyObject
    var object: Object? { get } // Also add set if you decide it is appropriate
}

struct Weak<Object: AnyObject>: WeakProtocol {
    weak var object: Object?
}

class ConcreteClass { }

extension Dictionary where Value: WeakProtocol {
    func foo() {
        print("Success!")
    }
}

var dict: [String: Weak<ConcreteClass>] = [:]

dict.foo()

The downsides of this approach are that you must expose the protocol that essentially duplicates the struct.

A: Swift's generics are invariant, which states that just because a generic type wraps a subclass, it does not make it a subtype of a generic wrapping its superclass. You can't write like this:
struct Generic<T> {}
class Parent {}
class Child: Parent {}

func foo(generic: Generic<Parent>) {}

let childGeneric = Generic<Child>()
foo(generic: childGeneric) //Cannot convert value of type 'Generic<Child>' to expected argument type 'Generic<Parent>'

But Swift's built-in generic types are covariant, which means that generic types can be subtypes of other generic types. For example, this is correct:
class Parent {}
class Child: Parent {}

func foo(generic: Array<Parent>) {}

let childGeneric = Array<Child>()
foo(generic: childGeneric)

A: So after tinkering a bit, I found a solution that does the trick:
extension Dictionary {

    func foo<T: AnyObject>() where Value == Weak<T> {
        print("success")
    }
}

This does exactly what I needed without any protocols (as @bscothern suggested).


text:
Q: Merge .swiftmodule fails with segmentation fault xcodebuild fails with the following error:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: merge-module command failed due to signal (use -v to see invocation)
** BUILD FAILED **

The following build commands failed:
    MergeSwiftModule normal arm64 /Users/vmanot/Documents/Xcode/Projects/Frameworks/ExSwift/build/ExSwift.build/Release-iphoneos/ExSwift.build/Objects-normal/arm64/ExSwift.swiftmodule
    CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
(2 failures)

(The ExSwift mentioned above is not the the open-source ExSwift, but a private framework).
The stack trace:
0  swift                    0x0000000104229edb llvm::sys::PrintStackTrace(__sFILE*) + 43
1  swift                    0x000000010422a61b SignalHandler(int) + 379
2  libsystem_platform.dylib 0x00007fff8e88152a _sigtramp + 26
3  libsystem_platform.dylib 0x00007fff5d8c0070 _sigtramp + 3473140576
4  swift                    0x000000010268b19e swift::serialization::Serializer::writeSubstitutions(llvm::ArrayRef<swift::Substitution>, std::__1::array<unsigned int, 256ul> const&) + 350
5  swift                    0x000000010268a9dc swift::serialization::Serializer::writeNormalConformance(swift::NormalProtocolConformance const*) + 2684
6  swift                    0x000000010269597b swift::serialization::Serializer::writeAllDeclsAndTypes() + 8043
7  swift                    0x0000000102696949 swift::serialization::Serializer::writeAST(llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>) + 2505
8  swift                    0x0000000102698f47 swift::serialization::Serializer::writeToStream(llvm::raw_ostream&, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::SILModule const*, swift::SerializationOptions const&) + 135
9  swift                    0x0000000102699b82 withOutputFile(swift::ASTContext&, llvm::StringRef, llvm::function_ref<void (llvm::raw_ostream&)>) + 226
10 swift                    0x0000000102699a06 swift::serialize(llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::SerializationOptions const&, swift::SILModule const*) + 214
11 swift                    0x000000010233b54b performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&) + 12843
12 swift                    0x000000010233810a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 2682
13 swift                    0x0000000102334797 main + 2247
14 libdyld.dylib            0x00007fff9d9a35ad start + 1
15 libdyld.dylib            0x0000000000000108 start + 1650838364

How can I locate the faulty code?

A: I think the source of this error can vary wildly and depends on the Swift source you have written. I was receiving this error while trying to write extensions for a custom protocol that conforms to UIPickerViewDataSource. Specifically, I was was writing default implementations for numberOfComponentsInPickerView(_:) and pickerView(_:numberOfRowsInComponent:).
I haven't been able to confirm it, but I suspect the error we experienced has to do with Objective-C interoperability. All I know for sure is that moving those implementations from the protocol into the conforming class fixed the error for me.
edit: changing the optimization level as Bruno suggested did not help.


text:
Q: Origin of the word Mathematics and in which condition it did come of? From which word, Mathematics has come from? Just tried to know. Help me out to know that. Also let me know the literature-change of this term.

A: Mathematics comes from the Greek word  μάθημα (máthēma) which means "that which is learnt".


text:
Q: &rest in common lisp I am confused as to what &rest does in common lisp.
This could be an example to represent what I mean :
(defmacro switch (value &rest pairs)
             ....
)

What exactly does the &rest and pairs mean?

A: The last parameter in a function (or macro) definition can be preceded by &rest. In this case, when the function (or the macro) is called, all the arguments not bound to the previous parameters are collected into a list which is bound to that last parameter. This is a way of providing an unspecified number of arguments to a function or a macro.
For instance:
CL-USER> (defun f (a &rest b)
           (list a (mapcar #'1+ b)))
F
CL-USER> (f 1 2 3 4 5)
(1 (3 4 5 6))
CL-USER> (f 1)
(1 NIL)
CL-USER> (f 1 2 3)
(1 (3 4))
CL-USER> (defmacro m (f g &rest pairs)
           (let ((operations (mapcar (lambda (pair) (list g (first pair) (second pair))) pairs)))
             `(,f (list ,@operations))))
M
CL-USER> (macroexpand-1 '(m print + (1 2) (3 4) (5 6)))
(PRINT (LIST (+ 1 2) (+ 3 4) (+ 5 6)))
T
CL-USER> (m print + (1 2) (3 4) (5 6))
(3 7 11)

Note that, if the are no remaining arguments, the list passed to the last parameter is empty.


text:
Q: False SWING Component Placement in Java with 4K Monitor I have a component placement problem. First I'll try to give (possibly useful) information and then tell you about the main problem:
My System: Windows 8.1 64bit, Java 1.8.0_60 32bit
What I'm trying to do is: After I learn screen resolutions of all connected screens, I'm placing some swing components around the screen. This means that I need to know the resolutions of the screens.
I'm using multiple monitors.

*

*3840 x 2160 (main monitor)

*1920 x 1080 (secondary)
I use:
graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
devices = graphicsEnvironment.getScreenDevices();

And for the main screen device:
devices[i].getDefaultConfiguration().getBounds()

returns [0, 0, 2560, 1440]. Instead of the right values 3840 x 2160.
Interesting thing is;
devices[i].getDisplayMode().getWidth() and getHeight()

returns the right 3840 and 2160 values.
Note: This difference does not happen in any other resolution selection of the screen. For example, if I select 1920 x 1080 for the main screen, both "getDefaultConfiguration().getBounds()" and "getDisplayMode().getWidth()" returns the right values.
Now,
You can say that I'm already getting the right dimensions. So, what is the matter?
The thing is, when I try to position my SWING components, they are placed in wrong positions. For example, an element at [3750, 0, 10, 10] ends up inside the second monitor, while It should have been on the right upper corner of the first screen.
Another example: As you know, a fixed sized component would appear smaller in higher resolutions. Since its pixel percentage related to screen gets smaller, the component itself also looks smaller. For example; When I increase my screen's resolution from 1920x1080 to 2560x1440, my components gets smaller. But, when I increase the resolution from 2560x1440 to 3840x2160; they stay in the same size.
I hope I was clear about the problem.

A: I know of one Windows 8+ specific feature, which might manifest in that way: per-display DPI setting. The feature is supposed to keep application window at the same size physically, even when dragging them across displays with different density.
This is achieved by rendering the application's window into a intermediate buffer, which then is scaled by the DWM taking the target screen DPI into account.
This feature can be disabled, using following dialog:

It has to be done on the file containing the executable program, which displays any frames. In Java, it's somewhat convoluted, since it's a hosting application. Changing this on java(w).exe should alter the behavior globally.
Typically, this kind of flag adjustment is done by a software installer. It's possible to wrap the java jar into a exe with a thin wrapper. I like launch4j the most for this task. The wrapper exe and the jar file can be wrapped into a installer script, which sets the flag at installation time.


text:
Q: Apache environment variables for CGI not setting I am trying to set my environment variables for the Apache webserver as it is not the correct Perl package. I followed the recommendation of one of the answers on Server Fault for updating the httpd file and adding the environment variables and it still isn't working.  After I updated the httpd file I bounced the httpd process as well.  On the command line the correct PATH is being used for Perl.  Can anyone offer any guidance?
Error in apache error.log file:
[pid 29460] [client 10.199.106.141:57768] AH01215: install_driver(Informix) failed: Can't locate DBD/Informix.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 7)

The correct location of Perl where Apache should check for Perl Modules
/usr/bin/perl

Updated /etc/sysconfig/httpd file
#Configuration of variables for webserver

export INFORMIXDIR=/opt/informix

export    LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFORMIXDIR/lib:$INFORMIXDIR/lib/cli:$INFORMIXDIR/lib/esql:$INFORMIXDIR/lib/tools

export INFORMIXSQLHOSTS=$INFORMIXDIR/etc/sqlhosts

PATH=$PATH:$HOME/bin:$INFORMIXDIR/bin:$LD_LIBRARY_PATH

export PATH

Other environment variables
OS Package:  Apache/2.4.6 (Red Hat Enterprise Linux) PHP/5.4.16
CONTEXT_DOCUMENT_ROOT = /var/www/cgi-bin/

A: Your error

Can't locate DBD/Informix.pm in @INC

means that it is missing the Perl module DBD::Informix.  There are a variety of options for getting this module:

*

*on Red Hat, fedora or centos systems: yum install perl-DBD-Informix

*on Debian or Ubuntu: apt-get install libdbd-informix-perl

*using cpanminus to create a local library: cpanm DBD::Informix

*using CPAN.pm
If you've been installing things from your distribution generally it is good to continue to do that, but otherwise one of the more Perl-specific methods (cpanminus or CPAN.pm) will probably give you something that works.


text:
Q: AngularJs: disable anchor / ngif negated I have this directive (hidden some sensitive values):
modApp.directive("dir1", [
function () {
    return {
        scope: {
            "results": "=",
            "allowView": "@",
            "allowPrint": "@",
        },
        templateUrl: "myurl",
        compile: function (elem, attrs) {
            // some code
        },
    };
}]);

and the template snippet is:

So my issue is that I need to disable the anchor under certain security conditions.
Therefore when it is allowed, it is ok to show the anchor and the image.
But when it is not, it should only show the image.
The easy way would be to simply define something like:

The problem that two requests to the image are generated, where it should only be one.
The ideal would be to have something like:

I found a aDisabled directive here in SO, but it didn't work for me.
Also there is ng-if but I couldn't make it work with the negated value of allowView.
Any suggestions?
Plunker: http://plnkr.co/edit/UJgQsaDYaxErP5A2NZy2
This plunker does not still use the allowView scope variable.
Note that in html, I'm setting a hardcoded true/false, it seems that this also has an impact, but not sure why...


text:
Q: Composer error deploying laravel application on elasticbeanstalk I have a laravel app hosted on elastic beanstalk and it is also connected with code pipeline. When I deployed the application I got this error on ebs panel:
ERROR: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version.
I don't know if it is related but when I downloaded the logs I found this:
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Script @php artisan package:discover --ansi handling the post-autoload-dump event
returned with error code 1

Here is my composer.json
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.3",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

A: It seems that you have some typos. The special character "\" must be "\\" for folder separation.
try this composer.json:
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.3",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app /",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

Now composer must be able to run scripts. Composer install must finish installation or give you clear warning or error about files.

A: So I just find out what was going on! I tried to increase my instance and then when I downloaded the complete log there were new information:
021/05/25 18:00:11.083949 [INFO] Running command /bin/sh -c composer.phar install --no-ansi --no-interaction
2021/05/25 18:00:18.791014 [INFO]
   ParseError

  syntax error, unexpected character 0x1D, expecting "]"

  at app/Http/Controllers/MailController.php:28
     24▕             'nome' => $request->nome,
     25▕             'email' => $request->email,
     26▕             'assunto' => $request->assunto,
     27▕             'descricao' => $request->descricao,
  ➜  28▕             'local' => $request->localizacao,
     29▕             'pais' => $request->pais
     30▕         ]);
     31▕
     32▕         if($response->status() === 200)

      [2m+1 vendor frames [22m
  2   [internal]:0
      Composer\Autoload\ClassLoader::loadClass("App\Http\Controllers\MailController")

      [2m+9 vendor frames [22m
  12  routes/web.php:24
      Illuminate\Support\Facades\Facade::__callStatic("post")

2021/05/25 18:00:18.791081 [ERROR] An error occurred during execution of command [app-deploy] - [Install composer dependencies]. Stop running the command. Error: installing composer dependencies failed with error: Command /bin/sh -c composer.phar install --no-ansi --no-interaction  failed with error exit status 1. Stderr:Do not run Composer as root/super user! See https://getcomposer.org/root for details

I couldn't see those ascii on vscode but when I opened the project with sublime they were there! I guess my instance was running out of memory therefore It wasn't logging out much and when I changed tiers, more information was logged out. I just removed those ascii and now it is working just fine.


text:
Q: Button position in div I have a inspiration post style:

So when I'm trying to make one I face some problem such as:

*

*button not rounded when I change window size

*social icons doesn't show

*I can't click social icons

*not responsive

code on codepen (https://codepen.io/youssefelmajbri/pen/eRjKoj):

.media {
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  border-radius: 0.25rem;
  width: 550px;
  height: 151px;
}

.media-body {
  padding: 20px;
}

.thumb {
  height: 150px;
  width: 250px;
}

img {
  max-width: 100%;
  max-height: 100%;
}

#social-fb {
  color: white;
  padding-top: 50%;
  padding-left: 20%;
  font-size: 20px;
}

#social-tw {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-yt {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-rd {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#btn {
  border-radius: 50%;
  width: 8%;
  height: 7%;
  margin-top: -30;
  margin-left: -10;
  background-color: #E91E63;
  color: white;
}

.img {
  width: 20%;
  height: 10%;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />

THis a text

 that you'll remeber and don't forget if that you want to forget you'll not able to.

        <button class="btn" id="btn" ></button>

A:
button not rounded when I change window size

This is because you are using percentages to set button width/height. These percentages will be fractions of the parent element, so 8% of width and 7% of height will not necessarily be equal, and if the parent width/height changes, these sizes will as well. Use static values instead (px/em/rem, etc).

social icons doesn't show

I would suggest placing these using absolute positioning. Surround the icons width a div, set this in div style:
position: absolute;
width: 100%;
left: 0;
bottom: 0;
text-align: center;

And add position: relative to parent element.

I can't click social icons

Well there aren't any click events attached to them, you need to give them an onclick event or similar, or surround them with a styled, clickable component like a href="..." or button.
Additionally I would suggest using, width and height instead of max-width and max-height on the image, so as to remove that white space beneath it.


text:
Q: Cannot limit number of checkboxes selected (tried multiple snippets) I have a form that prints out a list of questions stored in the database. The user is supposed to select a maximum of 10 check boxes, but it seems my javascript is being ignored. Am I blanking out on something fundamental to get this to work? I am creating this in a virtual machine with LAMP. I've tried running the code inside Eclipse and in the browser, but nothing happens. Here is my code:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Question Selection</title>

        <?php echo "
"; ?>
        <form id="questions" name="questions" action="GenerateQuiz" method="post">

                        Questions
                        Include in Quiz

                    <?php
                        $count = 1;
                        // Print a row for each record in the returned query
                        foreach($questionList as $key => $row) {
                            echo "

                                    $row[questionText]
                                    <input type='checkbox' name='questions[]' onclick='chkcontrol($count)' value='$row[questionText]' />

";
                            $count++;
                        }
                    ?>

                <input type="submit" value="Take Quiz" />

        </form>

A: Ive tried this in jquery which will be much easier. I have statically created some questions and you might loop your questions from your database. Here I have restricted user to select only 2 questions $('.quesCheck:checked').length > 2 . You can change it to 10

What is thunder ?	<input type="checkbox" name='questions[]' class="quesCheck" />

What is lightning?	<input type="checkbox" name='questions[]' class="quesCheck" />

What is chain reaction?	<input type="checkbox" name='questions[]' class="quesCheck" />

A: chkcontrol = function(j) {
    var total = 0;
    var questions = document.getElementsByName('questions[]');
    for (var i = 0; i < questions.length; i++) {
        if (questions[i].checked) {
            total = total + 1;
        }
        if (total > 10) {
            alert("Please select only 10 questions");
            questions[i].checked = false;
            return false;
        }
    }
}

Is what your chkcontrol function should look like.  You do not need jQuery to do this, you were most of the way there!
See a working example here:
https://jsfiddle.net/wr58739c/4/

A: Try this with your script:

With that code you ensure you get the right checkboxes from the right form.


text:
Q: Parse HTTP Response with JS and pass its two values into a div I'm currently trying to process an HTTP Response from the Google Sheets API and pass two specific cell values into an HTML Div each. Unfortunately, I'm a beginner with Javascript and can't quite modify my code to parse the request into usable JS objects and pass them to a value so I can use functions to write the values into their respective Div.
My Code so far:
var url = "https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/B2%3AC2?dateTimeRenderOption=FORMATTED_STRING&key=API_KEY";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);

xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
console.log(xhr.status);
console.log(xhr.responseText);
}};

xhr.send();

Spreadsheet_ID and API_Key are placeholders.
The server returns an answer formatted like this:
{
"range": "Sheet1!B2:C2",
"majorDimension": "ROWS",
"values": [
[
  "Value 1",
  "Value 2"
]
]
}

My goal is to get Value 1 in a specific Div and Value 2 into a different one.
How do I process the HTTP response and at which point can I transfer the values into a variable?

A: I solved the problem by changing the way to get there.
Parsing wasn't necessary, I simply cut the HTTP string to the characters I needed and used the JS .substring and .slice to first remove 67 characters before, then defining the limiting character at the end.


text:
Q: Linq to SQL construct a custom object externally I want to achieve the following:
return  (from a in db.Tags
    select new TagItem
    {
        ID = a.Id,
        Name = a.Name
    });

..but i don't want to achieve it like that, because i need to use the exact same TagItem construction elsewhere (for a join)
So this is the intention, to call a method that constructs the TagItem for me:
return (from a in db.Tags
    select ConstructTagItem(a));

And the method constructs the object the same way:
private TagItem ConstructTagItem(Tag a)
{
    return new TagItem { ID = a.Id, Name = a.Name};
}

But this gives me the following error:

Method 'TagItem ConstructTagItem(Tag)' has no supported translation to
  SQL.

Is there any way to achieve this ?
Solution (thanks Daniel Hilgarth):
return db.Tags.Select(ConstructTagItem);

And the method:
private Expression<Func<Tag, TagItem>> ConstructTagItem
{
    get { return a => new TagItem {ID = a.Id Name = a.Name }; }
}

A: Yes, there is. You need to use an expression tree like this:
Expression<Func<Tag, TagItem>> constructTagItem = a => return new TagItem
                                                       { ID = a.Id,
                                                         Name = a.Name};

And then you can use that expression instead of your method:
return db.Tags.Select(constructTagItem);

According to this article you need to use the method chains way of defining your query.


text:
Q: ActiveAdmin - all types update action show no member in struct I am setting up ActiveAdmin and when I use the edit action to update any of my models when I submit it results in an error of the style 'no member '' in struct'. I of course can see that the model_name IS in the structure posted, so I am pretty confused. And I am not sure what I am doing wrong nor how to fix. I have not changed the update action. I am pretty much a Rails newbie, but the active admin is behaving well otherwise. The response for one of these is...
NameError in Manage::ProductGroupsController#update

no member 'product_group' in struct
Rails.root: /var/hosts/linode_staging/releases/20140218181435/aotv2
Application Trace | Framework Trace | Full Trace
/usr/local/rvm/gems/ruby-2.1.0/bundler/gems/inherited_resources-e4fb9fc80448/lib/inherited_resources/base_helpers.rb:322:in []'
/usr/local/rvm/gems/ruby-2.1.0/bundler/gems/inherited_resources-e4fb9fc80448/lib/inherited_resources/base_helpers.rb:322:inbuild_resource_params'
/usr/local/rvm/gems/ruby-2.1.0/bundler/gems/inherited_resources-e4fb9fc80448/lib/inherited_resources/base_helpers.rb:316:in resource_params'
/usr/local/rvm/gems/ruby-2.1.0/bundler/gems/inherited_resources-e4fb9fc80448/lib/inherited_resources/actions.rb:45:inupdate'
actionpack (4.0.1) lib/action_controller/metal/implicit_render.rb:4:in send_action'
actionpack (4.0.1) lib/abstract_controller/base.rb:189:inprocess_action'
actionpack (4.0.1) lib/action_controller/metal/rendering.rb:10:in process_action'
actionpack (4.0.1) lib/abstract_controller/callbacks.rb:18:inblock in process_action'
activesupport (4.0.1) lib/active_support/callbacks.rb:413:in _run__4471285646399910144__process_action__callbacks'
activesupport (4.0.1) lib/active_support/callbacks.rb:80:inrun_callbacks'
actionpack (4.0.1) lib/abstract_controller/callbacks.rb:17:in process_action'
actionpack (4.0.1) lib/action_controller/metal/rescue.rb:29:inprocess_action'
actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:31:in block in process_action'
activesupport (4.0.1) lib/active_support/notifications.rb:159:inblock in instrument'
activesupport (4.0.1) lib/active_support/notifications/instrumenter.rb:20:in instrument'
activesupport (4.0.1) lib/active_support/notifications.rb:159:ininstrument'
actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:30:in process_action'
actionpack (4.0.1) lib/action_controller/metal/params_wrapper.rb:245:inprocess_action'
activerecord (4.0.1) lib/active_record/railties/controller_runtime.rb:18:in process_action'
actionpack (4.0.1) lib/abstract_controller/base.rb:136:inprocess'
actionpack (4.0.1) lib/abstract_controller/rendering.rb:44:in process'
actionpack (4.0.1) lib/action_controller/metal.rb:195:indispatch'
actionpack (4.0.1) lib/action_controller/metal/rack_delegation.rb:13:in dispatch'
actionpack (4.0.1) lib/action_controller/metal.rb:231:inblock in action'
actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:80:in call'
actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:80:indispatch'
actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:48:in call'
actionpack (4.0.1) lib/action_dispatch/journey/router.rb:71:inblock in call'
actionpack (4.0.1) lib/action_dispatch/journey/router.rb:59:in each'
actionpack (4.0.1) lib/action_dispatch/journey/router.rb:59:incall'
actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:680:in call'
warden (1.2.3) lib/warden/manager.rb:35:inblock in call'
warden (1.2.3) lib/warden/manager.rb:34:in catch'
warden (1.2.3) lib/warden/manager.rb:34:incall'
rack (1.5.2) lib/rack/etag.rb:23:in call'
rack (1.5.2) lib/rack/conditionalget.rb:35:incall'
rack (1.5.2) lib/rack/head.rb:11:in call'
actionpack (4.0.1) lib/action_dispatch/middleware/params_parser.rb:27:incall'
actionpack (4.0.1) lib/action_dispatch/middleware/flash.rb:241:in call'
rack (1.5.2) lib/rack/session/abstract/id.rb:225:incontext'
rack (1.5.2) lib/rack/session/abstract/id.rb:220:in call'
actionpack (4.0.1) lib/action_dispatch/middleware/cookies.rb:486:incall'
activerecord (4.0.1) lib/active_record/query_cache.rb:36:in call'
activerecord (4.0.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:incall'
actionpack (4.0.1) lib/action_dispatch/middleware/callbacks.rb:29:in block in call'
activesupport (4.0.1) lib/active_support/callbacks.rb:373:inrun_4380831815421705085_call_callbacks'
activesupport (4.0.1) lib/active_support/callbacks.rb:80:in run_callbacks'
actionpack (4.0.1) lib/action_dispatch/middleware/callbacks.rb:27:incall'
actionpack (4.0.1) lib/action_dispatch/middleware/remote_ip.rb:76:in call'
actionpack (4.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:incall'
actionpack (4.0.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in call'
railties (4.0.1) lib/rails/rack/logger.rb:38:incall_app'
railties (4.0.1) lib/rails/rack/logger.rb:20:in block in call'
activesupport (4.0.1) lib/active_support/tagged_logging.rb:67:inblock in tagged'
activesupport (4.0.1) lib/active_support/tagged_logging.rb:25:in tagged'
activesupport (4.0.1) lib/active_support/tagged_logging.rb:67:intagged'
railties (4.0.1) lib/rails/rack/logger.rb:20:in call'
actionpack (4.0.1) lib/action_dispatch/middleware/request_id.rb:21:incall'
rack (1.5.2) lib/rack/methodoverride.rb:21:in call'
rack (1.5.2) lib/rack/runtime.rb:17:incall'
activesupport (4.0.1) lib/active_support/cache/strategy/local_cache.rb:83:in call'
actionpack (4.0.1) lib/action_dispatch/middleware/static.rb:64:incall'
rack (1.5.2) lib/rack/sendfile.rb:112:in call'
railties (4.0.1) lib/rails/engine.rb:511:incall'
railties (4.0.1) lib/rails/application.rb:97:in call'
railties (4.0.1) lib/rails/railtie/configurable.rb:30:inmethod_missing'
passenger (4.0.37) lib/phusion_passenger/rack/thread_handler_extension.rb:77:in process_request'
passenger (4.0.37) lib/phusion_passenger/request_handler/thread_handler.rb:142:inaccept_and_process_next_request'
passenger (4.0.37) lib/phusion_passenger/request_handler/thread_handler.rb:110:in main_loop'
passenger (4.0.37) lib/phusion_passenger/request_handler.rb:448:inblock (3 levels) in start_threads'
Request
Parameters:
{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"p0xsTbNLexYflBaGSCX4KAvp4AGjRNIFueTUoIwAClM=",
 "product_group"=>{"title"=>"REST API",
 "description"=>"The subscriptions for the API",
 "source"=>"tjchambers"},
 "commit"=>"Update Product group",
 "id"=>"9"}
Toggle session dump
Toggle env dump
Response
Headers:
None

A: It's very likely that you haven't included strong parameters in your product_group.rb
Have a look at this documentation https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
Should point you into the right direction.
Best,
Jeroen


text:
Q: How to make state immutable in React I am looking for the best way to make my handleSwitch + setState function immutable. The code I have currently works but is mutable and I am unsure how to make it immutable everything I have tried either doesn't work or gives me a syntax error.
This is my state being initialised
this.state = {
      contacts: [],
      filteredContacts: [],
      selected: [],
      contactsSelection: {},
      loading: false,
    };

I have a simple <Switch /> comp which triggers the below when a user toggles the switch.
handleSwitch = async (contact, added) => {
    if (added) {
      console.log('added', { contact, added });
      return this.setState(prevState => ({
        contactsSelection: {
          ...prevState.contactsSelection,
          [contact.id]: contact,
        },
      }));
    }

    console.log('removed', { contact, added });
    // const { contactsSelection } = this.state;
    return this.setState(prevState => {
      const existingSelection = { ...prevState.contactsSelection };
      delete existingSelection[contact.id]; // <-- make immutable
      return { contactsSelection: existingSelection };
    });
  };

A: just to clarify: your code is fine by now, it does not mutate state directly but mutates copy.
but if you'd like having that in different way, here is a pattern:
this.setState(prevState => {
      const { [contact.id]: unusedVariable, ...restContacts } =
          prevState.contactsSelection;
      return { contactsSelection: restContacts };
})

or with destructuring:
this.setState(
  ({ contactsSelection: {[contact.id]: unused, ...filteredContact} })) =>
      ({ contactsSelection: filteredContacts })
);

Anyway unfortunately there is no way to avoid introducing unusedVariable while destructuring. So it will need you to suppress ESLint warning "variable ... is not used".
To me, your way handling that is better readable.


text:
Q: Swift Package Manager dependency in a repository subdirectory I have a Swift package in a subdirectory of a git repository inside GitHub. The tree looks something like this:
.
├── swift-package
│   ├── Package.swift
│   └── Sources
│       └── SomeLibrary
│           └── Library.swift
└── some-other-files

I want to add swift-package as a dependency to another project.
But the only way of specifying a dependency using Swift Package Manager I know is when the package is at the top level of the repository:
dependencies: [
    .package(url: "http://github.com/Some/Repository", from: "1.2.3"),
],

What I would need would be something along the lines of .package(url: "http://github.com/Some/Repository, dir: "swift-package"...).
I have no way of moving out the package to a separate repository.
Is there any way to achieve something like this using Swift Package Manager? If not, what are my options? Also, what is the best way to submit a feature request to Swift Package Manger developers?

A: You can not have two Swift packages in the same git repository. The Swift Package manager defines a package as:

Packages are Git repositories, tagged with semantic versions, containing a Package.swift file at their root. Initializing the
package created a Package.swift file, but to make it a usable package
we need to initialize a Git repository with at least one version tag.

Your options are to either have separate repositories/packages for your dependencies, or use one repository and move the code in separate modules/targets.
If you need to submit a feature I would first start a discussion in the Swift forums describing your goals and requesting feedback from the community. The code for the Swift PM is hosted in github you can always submit a pull request with a new feature. More information about the process is described here.

A: Not exactly the proper answer, but I wonder if, as a workaround, we could add the corresponding repo as Git submodule, and then integrate the package as a local package from the corresponding subdirectory. We would lose the ability to update (or change the version of) the package via SPM, though. On the other hand, we would still be able to control the version of the package, by pinning the Git submodule to version tags (or branches/commits/whatever), that should be there in Git repository anyway for SPM, if I recall it correctly.


text:
Q: JavaScript function declaration, a colon in function declaration What is the difference between function declaration function test() and test: function() in JavaScript?
function test() {
    …
}

vs.
test: function() {
    …
}

In the question «var functionName = function() {} vs function functionName() {}» functions were declared like:
function test() {
    …
}

and
var test = function() {
    …
};

Which is a bit different from syntax perspective comparing to my question.

A: Consider this javascript object :
{ "name" : "Joe",
  "age" : "23"}

Javascript being weakly typed, you can replace "23" (string) with 23 (number) :
{ "name" : "Joe",
  "age" : 23}

No error, works perfectly.
Actually, you can replace 23 with anything else : a boolean
{ "name" : "Joe",
  "age" : true}

another object
{ "name" : "Joe",
  "age" : {"2014" : 22 , "2015": 23 } }

or even a function
{ "name" : "Joe",
  "age" : function(){ alert("23");} }

Sidenote : some people hate Javascript for being so lax. Other people (like me) love Javascript for this very same reason, because this flexibility is its power (that and being asynchrounous).
You can name that object "person" and ask for his name and age :
var person = { "name" : "Joe",
      "age" : function(){ alert("23");} }

console.log( person.name ); // will log "Joe"
person.age(); // "age" is a function, so you need to call it. It will alert 23.

Now you can create a function that will return that object :
function Person() {
    return{
      "name" : "Joe",

      "age" : function(){ alert("23");},

      sayHello : function() {
        alert("Hello");
      },

      sleep : function() {
        alert("I'm sleeping");
      }
    }
};

console.log( Person().name ); // logs "Joe"
Person().age(); // alerts "23"
Person().sayHello(); // alerts "Hello"
Person().sleep(); // alerts "I'm sleeping".

age, sayHello and sleep are functions, that are called methods of the Person function.
One usually avoids calling Person() multiple times, and create a new Person instead :
var person = new Person();
person.sayHello(); // alerts "Hello"
person.sleep(); // alerts "I'm sleeping".

This method allows to create many persons, by passing parameters :
function Person(name, age) {
    return{
        "name" : name,

        "age" : function(){ alert(age);},

        sayHello : function() { // sayHello or "sayHello", both work
          alert("Hello, my name is "+ this.name );
        },

        sleep : function() {
          alert("I'm sleeping");
        }
     }
};

var person = new Person("John", 25);
person.sayHello(); // alerts "Hello, my name is John"
person.age(); // alerts "25".

This method currently replace classes, that Javascript 5 (EcmaScript 5) lacks. But EcmaScript 6 will come soon, with proper classes.

A: function test() is normal function declaration which you can call directly using function name. While test: function() is the function defined inside some object, so it has to be called using object on which it is defined.
Example
Function Declaration
function test() {
    alert('In Test');
}

test(); // Calling test

Method
var myObj = {
    test: function() {
        alert('Inside test');
    }
};

myObj.test(); // Calling test

A: There are three differences in the test:function() and function test().
Calling:
test:function() will a function defined inside the object. So you will need it to call from that object.
function test() is a normal function you call call it using test().
Consider this example.

const obj = {
  insidefunc:function(){
    console.log("Inside");
  }
}
function test(){
  console.log("Outside");
}

obj.insidefunc(); //Inside
test(); //Outside

insidefunc(); //Uncaught ReferenceError: insidefunc is not defined

this Binding
In the test:function() this will refer to the the Object of which the function is property of.While in function test() this will refer to window object.

const obj = {
  value:"something",
  insidefunc:function(){
    console.log(this);
  }
}
function test(){
  console.log(this);
}
obj.insidefunc(); //will log 'obj'
test(); //window object

Hositing:
You can use test before the line its declared but obj.test will only be accessed after the line its declared. Actually function test() show hoisting

test(); //outer function  called

const obj = {}

obj.test() //"Uncaught TypeError: obj.test is not a function"

obj.test = function(){
  console.log("object method")
}

function test(){
   console.log("outer function  called");
}


text:
Q: Create a subquery with spring data MongoDB I have a collection for status update of an order service. Each document in this collection is a new update for this Order.
The Document is like this:
{
    "_id": "xxx",
    "orderNumber": 1,
    "notificationDate": ISODate("2019-06-01T20:25:43.280Z"),
    "description": "Something"
}

I must found every order with no update in this month, so I made this query:
db.notificationData.find({"$and": [
    {"orderNumber": {"$nin" :
        db.notificationData.find({notificationDate: {"$gt": ISODate("2019-06-01") }})
                .map(function(data) { return data.orderNumber})
    }},
    {notificationDate: {"$lt": ISODate("2019-06-01") }}
]});

There is a way to get the same result using Spring Data MongoDB??


text:
Q: how to read current from sense pins of UWS-5/10-Q48 muRata chip with arduino I have a muRata UWS-5/10-Q48 DC-DC converter chip which has sense pins and I hope to read the current draw of the load which is connected to the arduino and print out the current draw.  I am not sure how to read the current using the sense pins.  Attached is the data sheet: http://www.murata-ps.com/data/power/uws.pdf which refers to remote sensing around page 23.

A: The sense pins on those supplies allow the voltage regulator to sense the voltage at the load, and so compensate for any voltage drop in the wires between the supply and load.
As stated in the datasheet, if you are not using the remote voltage sensing feature, the sense pins should be connected to the power supply output pins.
You cannot use the sense pins to measure the power supply output current.


text:
Q: Find a string within a jQuery array that has multiple elements per object I've got an array of employee's and assigned to each employee are a few elements.
Sample of array below:
var employees = [
                   {"name":"Johhny Test","salary":"1","email":"abc@123.com"},
                   {"name":"Mike Milbury","salary":"10","email":"184895@hdsjhfs.com"}
                ];

I've got a means of gathering the employee's last name and I'm storing it in a variable. I'd like to be able to search for the indexOf the last name housed in this variable so that I know at which position within the array that match is made.
So for instance, this array could be 100 items in size. Ideally I want to know that someone with the last name of "johnson" is in position 50 of this array. That way, I can go in and get the salary and email associated with their record from position 50 in the array.
The code I've got so far is this:
var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);

This isn't working though - my console is logging -1, suggesting that it doesn't exist in the array. Is there a way that I can specify a element of that array to search against?
Almost like employees(name).indexOf(lname) where it is searching against the name element?
Or am I going about this all wrong and there is perhaps an easier less messy way to accomplish this?

A: You can use .findIndex:

const employees = [
  {"name":"Johhny Test","salary":"1","email":"abc@123.com"},
  {"name":"Mike Milbury","salary":"10","email":"184895@hdsjhfs.com"}
];
const lastName = "Test";

const index = employees.findIndex(employee => {
  const { name = '' } = employee;
  const nameParts = name.split(' ');
  const lname = nameParts[nameParts.length-1];
  return lastName === lname;
});

console.log(index);
console.log(employees[index]);


text:
Q: can't install bower package because there seems to be a duplicate I wanted to install the backbone.routefilter plugin via Bower. It looks like there are 2 projects with that same name. http://sindresorhus.com/bower-components/#!/search/routefilter.
When I try to bower install backbone.routefilter#0.2.0 it tries to install 0.2.0 version from wanderer I want the latest from boazsender. Is there anyway to tell bower which repo to use?

A: That one seems to be wrongly registered. Use the correct one instead:
bower install backbone.routefilter