text:
Q: Why do I receive a SIGSEGV signal while using the Aria robotics API? I am using the Aria C++ programming libs for mobile robots (http://robots.mobilerobots.com/wiki/ARIA). I am new to this API so I wanted to start with a simple action class derived from ArAction. Now I tried to develop a small test program (an ArAction) in order to
control a simulated p3dx robot via MobileSim. Development takes place under Ubuntu 10.10, using gcc 4.4.5. Making (compiling) my code works fine, without errors. I can also set the desired speed for example in my ArAction's fire() method, and the simulation is also working as desired.
But, unfortunately, I can't use the ArRobot object attached to the ArAction I am overriding. The problem is that none of the member functions of the ArRobot object seems to work. For example, calling getVel() or getCompass() always returns a zero value. And when I call the hasFrontBumpers() method the program even crashes with the error message "Aria: Received signal 'SIGSEGV'. Exiting.". As soon as I remove this method call and recompile the error is also gone again...
Here is the relevant code that leads to the crash:
ArActionDesired * forward::fire(ArActionDesired d)
{
  desiredState.reset();

  ArRobot *r = getRobot();
  if(r == NULL)
  {
    printf("ArRobot = NULL\n");
    deactivate();
    return &desiredState;
  }

  printf("ok, ArRobot is not NULL, check for bumpers...\n");
  r->hasFrontBumpers(); // <-- this leads to the SIGSEV-based "crash"

  return &desiredState;
}

Any ideas what I am missing here -- is it a problem with my coding, or with the simulation environment? Thanks in advance for your help!
Kind regards, Matthias

A: ok, found it out now -- for the records: the Aria libs in version 2.7.2 are based on gcc-3 and libstdc++ 5, but Ubuntu 10.10 (which I am using) is shipped with gcc-4 and libstdc++ 6 per default. So I had to manually install the older versions of both packages, now my code is running fine...
cheers!

A: Calling hasFrontBumpers() for a p3dx from the fire() works fine for me on a similar Linux platform. If something is wrong, it is not in this method but in the initialization of the system. A reason for the non-moving robot could be that robot.enableMotors() hasn't been called.


text:
Q: MySQL - Count if generic value between This is my MySQL table:
+----+---------------------+---------------------+
| id | startDate           | endDate             |
+----+---------------------+---------------------+
| 1  | 2018-03-20 10:10:10 | 2018-10-02 21:44:00 |
+----+---------------------+---------------------+
| 2  | 2017-08-02 21:44:00 | 2017-08-03 11:00:00 |
+----+---------------------+---------------------+
| 3  | 2018-10-25 12:12:12 | 2018-11-25 12:22:33 |
+----+---------------------+---------------------+
| 4  | 2015-01-01 23:43:27 | 2018-12-29 22:12:35 |
+----+---------------------+---------------------

What I like to do is to take last 12 months starting of current month and check for first day of each month how many rows has this day between startDate and endDate
Expected result (for 18-07-2018):
+---------------------+-------+
| date                | count |
+---------------------+-------+
| 2017-08-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2017-09-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2017-10-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2017-11-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2017-12-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2018-01-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2018-02-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2018-03-01 00:00:00 | 1     | (id 4)
+---------------------+-------+
| 2018-04-01 00:00:00 | 2     | (id 1 and 4)
+---------------------+-------+
| 2018-05-01 00:00:00 | 2     | (id 1 and 4)
+---------------------+-------+
| 2018-06-01 00:00:00 | 2     | (id 1 and 4)
+---------------------+-------+
| 2018-07-01 00:00:00 | 2     | (id 1 and 4)
+---------------------+-------+

Is it possible in MySQL?

A: The trickiest part is generating the numbers.  The rest is just JOIN and GROUP BY:
select d.dte, count(t.startdate)
from (select date('2017-08-01') as dte union all
      select date('2017-09-01') as dte union all
      . . .
      select date('2018-07-01') as dte
     ) d left join
     mysql_table t
     on d.dte >= t.startdate and d.dte <= t.enddate
group by d.dte
order by d.dte;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typhoon - How to inject parameter which conforms to PROTOCOL instead of CLASS I have class which represents logged user
public class User: NSObject {
    init(authenticator: Authenticator) {
        self.authenticator = authenticator
    }
    ...
}

Its only initial arguments is object which conforms to Authenticator protocol
protocol Authenticator
{
    func authenticate(login:String , password:String , handler: (result:AuthenticationResult)->()  )
}

In my case the Auth object is instance of class BackendService
My typhoon assembly definition is:
public dynamic func user() -> AnyObject {
    return TyphoonDefinition.withClass(User.self) {
        (definition) in

        definition.useInitializer("initWithAuthenticator") {
            (initializer) in

            initializer.injectParameterWith( self.backendService() )
        }
    }
}

Application cause runtime-error
'Method 'initWithAuthenticator' has 0 parameters, but 1 was injected. Do you mean 'initWithAuthenticator:'?'

If i change init method to 'initWithAuthenticator:' it crashes with
'Method 'initWithAuthenticator:' not found on 'PersonalMessages.User'. Did you include the required ':' characters to signify arguments?'

A: At the present time, it is necessary to add the '@objc' directive to Swift protocols to have them be available for dependency injection with Typhoon. Without it the objective-c runtime's introspection and dynamic dispatch features arent available and these are required.
Similarly, in the case of a class it must extend from NSObject or have the '@objc' directive, otherwise it will also use C++ style vtable dispatch and have (essentially) no reflection. In the case of private vars or methods, they must also have the 'dynamic' modifier.
While vtable dispatch is faster, it prevents runtime method interception which many of Cocoa's most powerful features, such as KVO rely on. So both paradigms are important and its impressive that Swift can switch between them. In the case of protocols though, using the '@objc' directive is a little unfortunate as it implies a 'legacy' behavior. Perhaps 'dynamic' would've been better?
dynamic protocol Authenticator //Not supported but would've been a nicer than '@objc'?

Or perhaps another way to imply that dynamic behavior is required would be to have the protocol extend the NSObject protocol, however this does not work. So using '@objc' is the only choice.
Meanwhile, for classes the requirement to extend NSObject isn't really noticible as far as working with Cocoa/Touch apps goes.


text:
Q: Block thread while uploading picture to Amazon S3 on Android Is there a way to block the current thread and wait while the picture is uploaded to S3?
My code for uploading to the S3 is already running in a Android service in its doInBackground() method (with other network calls that have to be in specific order), so it's off the main UI thread. I just want to know when the uploading is done, so I can dismiss notification and show to user that everything is uploaded/done.
I'm using SDK v2, like this:
TransferUtility transferUtility = new TransferUtility(s3, ctx);
TransferObserver obs = transferUtility.upload(
            S3BucketNamePhotoTEST,
            imageId + ".jpg",
            file, new ObjectMetadata());
obs.setTransferListener(new UploadListener(dbHandler, ctx, imageId));

Where UploadListener is a class implementing TransferListener, where in onStateChanged() method we can detect when the upload is finished:
public void onStateChanged(int id, TransferState state) {
        if (state == TransferState.COMPLETED) {
        //do something here!
        }
}

That's not what I need, because my service call will be long done when that onStateChange() callback fires.
But looking at SDK v1 (that's now mostly deprecated), there was a way to block it, with:
TransferManager tx = new TransferManager(
           credentialProviderChain.getCredentials());
Upload myUpload = tx.upload(myBucket, myFile.getName(), myFile);
...
// Or you can block the current thread and wait for your transfer to
// to complete. If the transfer fails, this method will throw an
// AmazonClientException or AmazonServiceException detailing the reason.
myUpload.waitForCompletion();

This waitForCompletion() method is just what I need, but can't get to it with the newer API.
Any solutions?

A: Finally, I got the answer from Amazon developer here ->
https://github.com/aws/aws-sdk-android/issues/91

A: EDIT
If your service is ending before you are able to utilize any callbacks, then you need to keep your service open, so this doesn't happen.  If you're using an IntentService, these are designed as kind of a "fire-and-forget" feature.
You should look at implementing a normal Service so you can start a task and end it when you need to via stopSelf().
Check out http://developer.android.com/guide/components/services.html#ExtendingService
This will give you more control of when the service stops. You can stop the service when the Upload is complete.
Or, if you want to "hack" it, you could add a boolean member variable and block the execution using a loop, that will poll the boolean until it is true.  You can set it to True in your UploadListener method, and it should cause the service to stay open.
boolean mUploadComplete = false;

// Start upload.

Then after obs.setTransferListener(new UploadListener(dbHandler, ctx, imageid));
do {
    Thread.sleep(1000);
} while (!mUploadComplete);

In:
public void onStateChanged(int id, TransferState state) {
    if (state == TransferState.COMPLETED) {
        mUploadComplete = true;
    }
}

/////////////////////////////// ** Previous revision below **
This looks like it will solve your problem.
UploadResult waitForUploadResult()
                        throws AmazonClientException,
                                    AmazonServiceException,
                                    InterruptedException

Waits for this upload to complete and returns the result of this upload. This is a blocking call. Be prepared to handle errors when calling this method. Any errors that occurred during the asynchronous transfer will be re-thrown through this method.

so call:
UploadResult myResult = myUpload.waitForUploadResult();

That should block the thread until the upload is finished.


text:
Q: Tags using JOINs Ok, I've run into the situation.  3 tables, tags, books, and the intersection table*.  How do you deal with this again?
tags
  -id    int
  -name  varchar

books
  -id    int
  -name  varchar

taggings
  -tagId_fk   int
  -bookId_fk  int

Sample data

tags
  id   name
   1   good
   2   really good
   3   bad
   4   long
   5   exciting

books
  id      name
   1      Pumpkin Man
   2      O-castic Bastard

taggings
  bookId_fk     tagId_fk
  1             1
  1             4
  2             4
  2             5

So here Pumpkin Man has been tagged as good and long while O-castic Bastard has been tagged as long and exciting.
I want to write a single query that retrieves:

books.id   books.name      taggings.tagId_fk as tags.name (know what I mean?)
1          Pumpkin Man        good
1          Pumpkin Man        long
2          O-castic Bastard   long
2          O-castic Bastard   exciting

Not exactly what I want

SELECT DISTINCT taggings.bookId_fk, tags.name FROM tags
  INNER JOIN taggings ON taggings.tagId_fk=tags.tagId
  ORDER BY taggings.bookId_fk;

The question I really have is, is it even possible to display the above result in MySQL without:

*

*Breaking it into more than one query,

*Using a subquery at all?

*PS I know that some people don't use an intersection table

A:     SELECT b.*,
           t.name
      FROM books b
INNER JOIN taggings t_b ON t_b.bookId_fk = b.id
INNER JOIN tags t ON t.id = t_b.tagId_fk
  ORDER BY b.id

So, yes, it is possible.
Note: if you have the books without tags at all - change INNER to LEFT in both cases and you'll get the NULL value instead of tag for that books.


text:
Q: os.platform() returns darwin instead of OSX os.platform();

The above JS instruction returns the name of OS .

*

*When it is runned on Ubuntu , it returns
'linux'

*When it is runned on Macbook, it returns
'darwin'

I am wondered why does not return osx ,unix or bsd.. ?
Does darwinis a fork of osx ?
How to get the type of OS under MAC using Node.js ?

A: Darwin is the underlying platform for OS X.
To get the OS X version instead, you can do this via the command line (or child process) with: defaults read loginwindow SystemVersionStampAsString or sw_vers -productVersion
To get the version via C/C++ (which you could write a binding for to access from node):
// compile with: g++ osx_ver.cc -I/Developer/Headers/FlatCarbon -framework CoreServices
#include <Gestalt.h>
#include <stdio.h>

int main() {
  SInt32 majorVersion, minorVersion, bugFixVersion;

  Gestalt(gestaltSystemVersionMajor, &majorVersion);
  Gestalt(gestaltSystemVersionMinor, &minorVersion);
  Gestalt(gestaltSystemVersionBugFix, &bugFixVersion);

  printf("%d.%d.%d", majorVersion, minorVersion, bugFixVersion);

  return 0;
}

Note: The Gestalt() usage shown above is deprecated since OS X 10.8, but its replacement seemingly isn't available until OS X 10.10, so you may need to use Objective-C instead ([processInfo operatingSystemVersion]) and branch on API availability like what is done here in Chromium.

A: Darwin is not OSX, OSX is Darwin.
Darwin is the core of OSX, in the same way, Linux is the core of Debian, Ubuntu, and every other Linux distributions.
So while you can be 100% sure that any Apple product (macOS, OSX, iOS, watchOS, tvOS) will return Darwin, it is technically not correct to assume that darwin will only ever be thoses OSs, since some low profile open source projects exists, like PureDarwin, and thoses would also return darwin.
However, I do not know of any (officials) port of node.js for any other Darwin-based OSs than OSX, so  in practice, yes, if you get darwin, you can be confident it is OSX.

A: Darwin was the original name given to OS X by apple. It was named as such because it was the NeXT step in the evolution of operating systems.


text:
Q: Possible "Transparent Film" effect in jQuery? I'm stumped OK, I'm in a real pickle here friends, and I need some help.
I have a website I am working on for a client of our company, but at the top of the page it involves a jQuery slideshow/infinite carousel mix that shows the CURRENT image in-between a 19-ish pixel white border on both sides and the other pieces of the carousel are supposed to be hidden under and behind a blue overlay.
When the client clicks the previous/next arrow (currently base text links that I'm going to re-position after I get this POS taken care of), the current image that is shown in the middle of the carousel on the page is supposed to slide to the left UNDER the white border and INTO the blue overlay (kind of like a transparent film effect, if you will).
Well, I'm STUMPED as to how I can get the image to slide under the border and overlay a color on top of it, ALL DYNAMICALLY without fading the entire image at once while moving to the left. It's supposed to be a super-smooth transition.
This is ULTIMATELY what it's SUPPOSED to look like:
http://www.powellcreative.com/clients/StansellHealth/images/help.png
This is what it looks like right now:
http://www.powellcreative.com/clients/StansellHealth/
Mind the crudeness of the current look and feel, it's still in the base development stages from the PSD, but this stumps me. Please help

A: I created a very quick, non-functioning example to show you a technique you could use:
http://jsfiddle.net/gdgKQ/1/
Basically, you want to use two absolutely-positioned, partially transparent divs to create the film effect in the comp you're working from. If I have time and it'd be useful, I can add some JavaScript to show you the effect in action.


text:
Q: I am stuck at "The Shipped item's tracking number is required" I have a model
const FormDataSchema = new mongoose.Schema({...})

// the Shipping schema
const ShippingSchema = new mongoose.Schema({
    itemstrackno : {
        type: String,
        minlength: [3, "Minimum characters for this field is 3"],
        maxlength: [100, "Maximum characters for this field is 100"],
        required: [true, "The Shipped item's tracking number is required"],
        trim: true,
        unique: true
    },
    formData: [FormDataSchema]
}, {timestamps: true})

const Shipping = mongoose.model("Shipping", ShippingSchema)
module.exports = Shipping

my post controller
// post a shipment
exports.postShipment = async (req, res, next) => {
const {itemstrackno, formdata} = req.body

try {
    const trackedItem = await Shipping.findOne({itemstrackno})

    if(trackedItem){
        return next(new ErrorResponse("An Item with this track number exists", 400))
    }

    const shipment = await Shipping.create({itemstrackno, formdata})

    res.status(200).json({
        success: true,
        data: shipment
    })
} catch (error) {
    next(error)
}

}
when i send a post request with postman i get "The Shipped item's tracking number is required" Error. What am i doing wrong?
THE POSTMAN IMAGE

A: Seems like you have a typo in the request. You have marked itemstrackno as required but you are sending itemtrackno


text:
Q: Android mediaplayer stop sound when another item is clicked I'm building a list view soundboard and I need a code for play a sound when I click on a item and stop it when another is clicked, then start the new sound. I have tried many code but the app crashes.

A: private MediaPlayer mMediaPlayer = null;

Call playAudio() when an item clicked. it will stop the previous playing audio and play the new.
public void playAudio(int audioId)
{
    // stop the previous playing audio
    if(mMediaPlayer != null && mMediaPlayer.isPlaying())
    {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    mMediaPlayer = MediaPlayer.create(this, audioId);
    mMediaPlayer.start();
}

call this method on item click
 playAudio(R.raw.sound); // change this sound depends on your item

A: Put your media file in your raw folder
and then
 MediaPlayer song = MediaPlayer.create(this, R.raw.song1);

and when you click on an item in your listView
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
     song.release();
     song = MediaPlayer.create(this, R.raw.song2);
     song.start();
}


text:
Q: jQuery Slide not Looping Back I found this simple Slideshow on the Internet, but the problem is that it doesn't repeat itself.
What I mean, is that it goes from 1 to 2, but doesn't go back to 1. What do I have to modify in the jQuery? Thanks, this is my first post.
JavaScript Code:
function slideSwitch() {
var mylenght = 5;
var $active = $('#slideshow IMG.active');

if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
if ($active.length == mylenght) $active = $("#slideshow IMG:first")
// use this to pull the images in the order they appear in the markup
var $next =  $active.next().length ? $active.next()
    : $('#slideshow IMG:first');

// uncomment the 3 lines below to pull the images in random order

// var $sibs  = $active.siblings();
// var rndNum = Math.floor(Math.random() * $sibs.length );
// var $next  = $( $sibs[ rndNum ] );

$active.addClass('last-active');

$next.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 1000, function() {
        $active.removeClass('active last-active');
    });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

A: Try this,
function slideSwitch() {
    var mylenght = 4;
    var $active = $('#slideshow IMG.active');

    if ($('#slideshow IMG').index($active) == mylenght - 1)
        $next = $("#slideshow IMG:first")
    else
        $next = $active.next();

    $next.addClass('active').css({opacity: 0.0}).animate({opacity: 1.0}, 1000);
    $active.removeClass('active').css({opacity: 1.0}).animate({opacity: 0}, 1000);
}

Have a look here http://jsfiddle.net/iamrmin/K62DX/


text:
Q: problems copying an image and overwriting the existing one c# wpf I have an image control that I charge an image via a path saved in a bdd, but if I want to change the image, first I look for the new image with an openfiledialogsends me the error, [the process cannot access the file]
this is my code
OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        openFileDialog.Filter = "Image files (*.;*.jpg)|*.jpg;*.png|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
        openFileDialog.RestoreDirectory = true;
        bool? checarOK = openFileDialog.ShowDialog();
        if (checarOK == true)
        {
            try
            {
                string archivo = openFileDialog.FileName;  //nombre archivo seleccionado
                rtjpg.Text = archivo; //ruta de archivo seleccionado en un textbox
                imgfoto.Source = new BitmapImage(new Uri(openFileDialog.FileName)); //coloca la imagen en un control image
            }
            catch
            {
            }
            try
            {
                string origPath = rtjpg.Text; //guarda la ruta original de la imagen
                string filename = "mdk_fr_" + nid + "_" + idpac.Text + ".jpg"; //nombre que se le dara a la copia
                string target_path = @"c:\medikfile\imagenes\"; // carpeta destino de la imagen
                string dest_file = Path.Combine(target_path + filename); //ruta completa de la copia
                string destPath = dest_file;
                destruta.Text = destPath;
                if (!File.Exists(destPath))
                {
                    File.Delete(destPath);
                    MessageBox.Show("borrado" + destPath);
                }
                else
                {
                    //                /////
                    int bufferSize = 1024 * 1024;
                    using (FileStream fileStream = new FileStream(destPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileStream fs = new FileStream(origPath, FileMode.CreateNew, FileAccess.ReadWrite);
                        fileStream.SetLength(fs.Length);
                        int bytesRead = -1;
                        byte[] bytes = new byte[bufferSize];

                        while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, bytesRead);
                        }
                    }
                }
            }
            catch (Exception im)
            {
                MessageBox.Show("error " + im);
            }
        }

A: It looks like there is a problem with your delete logic.
if (!File.Exists(destPath)) // <-- RIGHT HERE
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}

You're essentially saying that if the file doesn't exist, delete it.
Maybe it should be this instead:
if (File.Exists(destPath))
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}


text:
Q: Pods not getting scheduled to node with matching labels I'm getting this error when exec'ing into my pod. Error from server (BadRequest): pod es-master-5cb49c68cc-w6dxv does not have a host assigned
It seemed to be related to my nodeAffinity but I don't see anything immediately wrong with it. I can't seem to get my deployment to attach its pod to any of my nodes. I don't have any taints or tolerations setup on the node or pod. I've tried switching to labels that are automatically generated that are on every node, but nothing seems to work. I've even tried removing my affinity section entirely, and also tried adding nodeSelector to spec by itself.
Here is my deployment config and output from kubectl describe pod  -n elasticsearch

---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    component: elasticsearch
    role: master
  name: es-master
  namespace: elasticsearch
spec:
  replicas: 3
  selector:
    matchLabels:
      component: elasticsearch
      role: master
  template:
    metadata:
      labels:
        component: elasticsearch
        role: master
      annotations:
        iam.amazonaws.com/role: {REDACTED}
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - topologyKey: "kubernetes.io/hostname"
            labelSelector:
              matchLabels:
                component: elasticsearch
                role: master
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: topology.kubernetes.io/region
                operator: In
                values:
                - us-east-2

Name:           es-master-866f7fb558-298ht
Namespace:      elasticsearch
Priority:       0
Node:           <none>
Labels:         component=elasticsearch
                pod-template-hash=866f7fb558
                role=master
Annotations:    iam.amazonaws.com/role: {REDACTED}
                kubernetes.io/psp: eks.privileged
Status:         Pending
IP:
Controlled By:  ReplicaSet/es-master-866f7fb558
Init Containers:
  init-sysctl:
    Image:      busybox:1.27.2
    Port:       <none>
    Host Port:  <none>
    Command:
      sysctl
      -w
      vm.max_map_count=262144
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-xflv6 (ro)
Containers:
  elasticsearch:
    Image:       amazon/opendistro-for-elasticsearch:0.9.0
    Ports:       9300/TCP, 9200/TCP, 9600/TCP
    Host Ports:  0/TCP, 0/TCP, 0/TCP
    Limits:
      cpu:     2
      memory:  12Gi
    Requests:
      cpu:     2
      memory:  12Gi
    Liveness:  tcp-socket :transport delay=60s timeout=1s period=10s #success=1 #failure=3
    Environment:
      CLUSTER_NAME:            logs
      NUMBER_OF_MASTERS:       3
      NODE_MASTER:             true
      NODE_INGEST:             false
      NODE_DATA:               false
      NETWORK_HOST:            0.0.0.0
      TRANSPORT_TLS_PEM_PASS:
      HTTP_TLS_PEM_PASS:
      NODE_NAME:               es-master-866f7fb558-298ht (v1:metadata.name)
      DISCOVERY_SERVICE:       elasticsearch-discovery
      KUBERNETES_NAMESPACE:    elasticsearch (v1:metadata.namespace)
      PROCESSORS:              2 (limits.cpu)
      ES_JAVA_OPTS:            -Xms6g -Xmx6g
    Mounts:
      /usr/share/elasticsearch/config/admin-crt.pem from certs (ro,path="admin-crt.pem")
      /usr/share/elasticsearch/config/admin-key.pem from certs (ro,path="admin-key.pem")
      /usr/share/elasticsearch/config/admin-root-ca.pem from certs (ro,path="admin-root-ca.pem")
      /usr/share/elasticsearch/config/elasticsearch.yml from config (rw,path="elasticsearch.yml")
      /usr/share/elasticsearch/config/elk-crt.pem from certs (ro,path="elk-crt.pem")
      /usr/share/elasticsearch/config/elk-key.pem from certs (ro,path="elk-key.pem")
      /usr/share/elasticsearch/config/elk-root-ca.pem from certs (ro,path="elk-root-ca.pem")
      /usr/share/elasticsearch/config/logging.yml from config (rw,path="logging.yml")
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-xflv6 (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      elasticsearch
    Optional:  false
  certs:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  elasticsearch-tls-data
    Optional:    false
  default-token-xflv6:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-xflv6
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                  From               Message
  ----     ------            ----                 ----               -------
  Warning  FailedScheduling  59s (x3 over 3m44s)  default-scheduler  0/8 nodes are available: 8 Insufficient cpu.

All nodes are m5a.large ec2 instances.

A: The error is pretty clear 0/8 nodes are available: 8 Insufficient cpu which means nodes don't have 2 cpu cores free as specified in requests. Solution is to either provision nodes with more cpu or reduce the cpu requests in pod spec.


text:
Q: Can not decode base64 string properly with javascript atob function I'm working with other company to sending and receiving data in real time.
They give me a websocket URL like this: ws://domain.com/socket.io/?EIO=4&transport=websocket and I need to connect to it for transfer data.
The problem is they said that data is encoded with base64 string, and when I received data, I couldn't completely decode it. When I decode data by atob() function it show readable string but it had some special characters which I couldn't understand.
For example, here is one of the response messages in websocket:
h6d1c2VyS2V50Rqdom5v0wAAAYSBGgjtp3ZlcnNpb26mMS4xMy4wqXNlc3Npb25JZLAxNjY4NjEzMDI0NDM0NDM0o3NpZ6Cmc3luY0lkAKRib2R5gad1c2VyS2V50Rqd
When I decode base64 string, the result is:
\x87§userKeyÑ\x1A\x9D¢noÓ\x00\x00\x01\x84\x81\x1A\bí§version¦1.13.0©sessionId°1668613024434434£sig ¦syncId\x00¤body\x81§userKeyÑ\x1A\x9D
I simply decode it by atob(encodedData), and get back result like this. I don't know what problem is. How should I fix this?

A: Using the atob function is deprecated and I suggest you this little snippet to decode base64 encoded strings:
const encoded = "SOME_BASE64_STRING"
const decoded = new Buffer(encoded , "base64").toString()

Edit:
For client-side usage without the browserify module I recommend you to use this package.


text:
Q: Как в C# правильно обработать повторно выброшенное исключение? Вот код:
class ExceptionsDemo
{
    public static void Divide(int x, int y)
    {
        try
        {
            var z = x / y;
        }
        catch (DivideByZeroException ex)
        {
            throw new ArgumentException("y равен 0", ex);
        }
    }

    public static void Execute(int x, int y)
    {
        try
        {
            Divide(x, y);
        }
        catch (Exception ex)
        {
            var inner = ex.InnerException;
            Console.WriteLine(inner.Message);
        }
    }
}

Вызываю вот так:
static void Main(string[] args)
{
   ExceptionsDemo.Divide(5, 0);
}

Ожидаю, что повторно выброшенное исключение поймается в Execute, но этого не происходит - программа вылетает, если запустить отладку. Если запустить без режима отладки, то выполняется, а в консоли пишет "Unhandled exception. System.ArgumentException: y равен 0". Почему оно unhandled, если я его ловлю?
Если изменить вызов вот так:
static void Main(string[] args)
{
    try
    {
        ExceptionsDemo.Divide(5, 0);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Catch в main");
    }
}

тогда повторное исключение ловится в catch мейна.

A: Как правильно написали в комментариях, вы не вызываете метод Execute, поэтому исключение не ловится. Если вызывать Execute вместо Divide, то должно пойматься:
static void Main(string[] args)
{
   ExceptionsDemo.Execute(5, 0);
}


text:
Q: AWS erroring about time difference I am calling aws with async call and I'm getting this. <![CDATA["Signature expired: 20171114T190104Z is now earlier than 20180323T213705Z (20180323T214205Z - 5 min.)"]]>.
sI know that this is most likely caused by my machine having the clock off, but how do I fix it? The time is set to be determine automatically like so.

I'm using Fedora.
This answer suggested that the AWS keys might be timing out(?) (I don't fully understand this one). If that's the case how do I fix this? I tried manually changing my clock both -5min and +5min, as suggested by the error, but it didn't do anything.
Edit: The same error appears when using a live heroku server.
Edit2: I'm using Node Express and making the call like this:
function(callback) {
  // third call
  var results = '';
  var options = {
    host: urlObject.host,
    protocol: urlObject.protocol,
    path: urlObject.path,
    headers: {
      Authorization: `AWS4-HMAC-SHA256 Credential=key/20171114/us-west-1/awis/aws4_request, SignedHeaders=host;x-amz-date, Signature=key`,
      'Content-Type': 'application/xml',
      'X-Amz-Date': '20171114T190104Z',
      Accept: 'application/xml',
    },
  };
  https.get(options, resource => {
    resource.setEncoding('utf8');
    resource.on('data', function(data) {
      // results += JSON.parse(data);
      results += data;
    });
    resource.on('end', function() {
      callback(null, results);
    });
    resource.on('error', function(err) {
      callback(err);
    });
  });
},

A: You'll need to provide the current date using the X-Amz-Date header, not the date from the example code. This blog post has an example of how to do that in Node.js to follow the format that the AWS API expects:
// get the various date formats needed to form our request
var amzDate = getAmzDate(new Date().toISOString());

// this function converts the generic JS ISO8601 date format to the specific format the AWS API wants
function getAmzDate(dateStr) {
  var chars = [":","-"];
  for (var i=0;i<chars.length;i++) {
    while (dateStr.indexOf(chars[i]) != -1) {
      dateStr = dateStr.replace(chars[i],"");
    }
  }
  dateStr = dateStr.split(".")[0] + "Z";
  return dateStr;
}

Then, of course, you'll want to assign that amzDate variable to the X-Amz-Date header in your request.
Long term, I think you'll find it is more useful to use the official Node.js AWS SDK instead of trying to custom-make these queries to the format that AWS expects, so you may want to explore that!


text:
Q: Point Cloud Segmentation I have the point cloud of propeller.
The problem is I want to separate/segment the wing of propeller from the main body of propeller, because I just need to focus on the points on the wing
I also have the normals on every point.
Do you have any suggestion to separate it?
Thank you guys.

A: Here are my ideas.
Try cylinder fitting from PCL (Point Cloud Library). That might  give you the right segmentation results.
http://vml.sakura.ne.jp/koeda/PCL/tutorials/html/cylinder_segmentation.html
Another way is to Apply PCA to normals and see if you can retrieve meaningful dimensions.
Or Simple k-means clustering on normals.
If any of these don't work, using tSNE to visualize those normals might give you some clues to figure out the way to separate them based on some thresholds as well.


text:
Q: Can't find an option to turn off cellular data for an application on iPhone (iOS 14) I'm trying to turn off cellular data for an application on iPhone running iOS 14, I know that you can go to Cellular section in Settings and there will be a list of applications including the options to turn the cellular data on or off, but I can't find my application in that list to turn it off. Can someone help me with this? Thanks for your help!

A: I can't stand this iPhone "feature", but for an app to appear in the list where you can turn cellular data on or off:

*

*the app must be launched once with cellular data on;

*sometimes it is not enough - you must not only launch the app, you must do something with it actively.

Though, it may be that for newer iPhones this is not longer the case.


text:
Q: Process.Start fails and claims "The directory name is invalid." We have a .NET application starting Microsoft Word explicitly with System.Diagnostics.Process.Start, e.g. "C:\PROGRA~2\MICROS~1\Office14\WINWORD.EXE" - the value is retrieved from the registry beforehand (see GetWordExePathFromWindowsRegistry method in the code below). Since we moved from .NET Framework 4.x to .NET Core 3.1, a runtime error in the Process.Start line is thrown: Win32Exception: "The directory name is invalid." (in our case the German message "Der Verzeichnisname ist ungültig.") We log the error, and when we open the logged directory in the file explorer, everything is fine; so as far as we can see the error message is not correct.
This error occurs not always, but often. Sometimes, it helped restarting the application, sometimes restarting the computer. Sometimes nothing helps. Some users get the error more often than others. Users on another site don't have the problem at all. Yet we have no idea what the cause could be.
Please note that this has been productive code for several years without an issue, and we get the error reports since we moved from .NET Framework to .NET Core 3.1 without this code being changed.
Here is the code of how we get the path to winword.exe:
public static string GetWordExePathFromWindowsRegistry()
{
    Regex exePathRegex = new Regex(
        @".*\\winword.exe",
        RegexOptions.IgnoreCase);
    foreach ( string wowNodeName in new[] { "", @"Wow6432Node\" })
    {
        foreach (string theKeyFormat in
            new[]
            {
            @"SOFTWARE\{0}Microsoft\Windows\CurrentVersion\App Paths\Winword.exe",
            @"SOFTWARE\{0}Classes\WordDocument\protocol\StdFileEditing\server",
            @"SOFTWARE\{0}Classes\Word.Document.14\protocol\StdFileEditing\server"
            })
        {
            RegistryKey rootNode = Registry.LocalMachine;
            string keyPath = string.Format(theKeyFormat, wowNodeName);

            // Get default registry Value:
            using RegistryKey key = rootNode.OpenSubKey(keyPath);
            string fullWordPath = key?.GetValue("")?.ToString();

            if (!string.IsNullOrEmpty(fullWordPath))
                if (exePathRegex.IsMatch(fullWordPath))
                    return fullWordPath;
        }
    }
    throw new Exception("Path to Word not found"); ;
}

And then we start Word with something like that (in our case hidden==true because a VSTO add-in in Word does the real stuff):
public void StartMsOfficeAppExe(
    string msOfficeAppExePath,
    string startArguments,
    bool hidden)
{
    ProcessStartInfo startInfo = new ProcessStartInfo(
        msOfficeAppExePath,
        startArguments)
    {
        UseShellExecute = false // without this Hidden would not be allowed
    };
    if (hidden)
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    Process.Start(startInfo);
}

A: It turned out that the following change helps: Instead of starting the process with providing the full path to the EXE file, we now first change the current directory to that of the EXE, then start the EXE in the current directory, and finally we change back to the directory we were in before.
It is weird, but it helps.

A: Did you try using the Verbatim character (@) for the string? Could be that it is not escaping the backslashes.
Escaping them manually also works (replacing \ => \\ they will turn kind of yellow).


text:
Q: Replacing shared_ptr elements in std::vector I have a vector of shared_ptrs as below.
std::vector<std::shared_ptr<SharedThing>> things;

Now let's say I push a number of shared_ptrs onto the vector and each element now has a reference count of 1.
When I need to replace one of those elements with a new shared_ptr I want the old shared_ptr to go out of scope. Will regular element assignment achieve this or will it just copy the shared_ptr contents. For example:
things.at(0) = new_shared_ptr;

Will this decrement the reference count of things.at(0) and increment the count of new_shared_ptr?

A:
When I need to replace one of those elements with a new shared_ptr I
  want the old shared_ptr to go out of scope. Will regular element
  assignment achieve this?

The shared pointer in the vector won't go out of scope,
but it will replace the managed object with the new one given.
Calling:
things.at(0) = new_shared_ptr;

will preserve the count at 1.
Here is an easy way to observe this behaviour:
#include <iostream>
#include <vector>
#include <memory>

int main(){

  //vector with a shared pointer
  std::vector<std::shared_ptr<int>> things;
  things.push_back(std::make_shared<int>(1));

  //prints 1
  std::cout << things.at(0).use_count() << '\n';

  //assign a new value
  things.at(0) = std::make_shared<int>(2);

  //still prints 1
  std::cout << things.at(0).use_count() << '\n';
}

Although not a part of your question, it is often advised to use make_shared instead of a new.

A: Yes, basically you are right.
To be more accurate, the reference count of previous shared_ptr at(0) will be decremented. And then you assign it with a new shared_ptr, which may have the count 1. Looks like the reference count at(0) is the same, but it changed and changed back.
You can verify it by std::shared_ptr::use_cout()
For more details, we can debug into the STL, when
things.at(0) = new_shared_ptr;

include/c++/4.8.3/bits/shared_ptr_base.h:556

  __shared_count&
  operator=(const __shared_count& __r) noexcept
  {
_Sp_counted_base<_Lp>* __tmp = __r._M_pi;
if (__tmp != _M_pi)
  {
    if (__tmp != 0)
      __tmp->_M_add_ref_copy();
    if (_M_pi != 0)
      _M_pi->_M_release();
    _M_pi = __tmp;
  }
return *this;
  }

The new one _M_add_ref_copy(), then previous one _M_release(), which will decrease the _M_use_count by 1.


text:
Q: Azure devops self-host deploy agent If I am using a self-hosted deployment agent for my azure devops Ci\CD pipeline , and the pipeline is regarding to deploy Azure databricks notebook and also to build Azure sql database project and deploy dacpac ,
what component is required to be installed in that self-host agent ?

A:
what component is required to be installed in that self-host agent ?

Prerequisites:
•   Windows 7, 8.1, or 10 (if using a client OS)
•   Windows 2008 R2 SP1 or higher (if using a server OS)
•   PowerShell 3.0 or higher
•   .NET Framework 4.6.2 or higher

Note - the minimum required .NET version for build agents is 4.6.2 or
higher. If you're building from a Subversion repo, you must install
the Subversion client on the machine.

You should run agent setup manually the first time.
Prepare permissions
Information security for self-hosted agents
Authenticate with a personal access token (PAT)
Confirm the user has permission
Download and configure the agent

Before you install a self-hosted agent you might want to see if a
Microsoft-hosted agent pool will work for you. In many cases this is
the simplest way to get going.

For more information refer - https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=azure-devops&tabs=browser#install


text:
Q: Is there an example of an exponential family distribution with intractable normalizing constant? If so, what is it? Typically, one comes across examples of exponential family distributions that have analytically computable normalizing constants.  Consider the normal, beta, Poisson, etc. distributions.
However, I don't see why the normalizing constant would need to be tractable in general.  Is there an example of an exponential family distribution with intractable normalizing constant?

A: here is an example that is nothing like the normal, beta, Poisson, etc. distributions
The sample space of the Ising model is based on a graph $G=(V,E)$ specified by a set of vertices $V$ and a set of undirected edges $E$. The sample space is $\{-1,1\}^V$. The density is $$\exp\left(\sum_{i\in V}Q^1_ix_i+\sum_{(i,j)\in E}Q^2_{ij}x_ix_j\right)$$
The natural parameters are $(Q^1, Q^2)\in \mathbb R^V \times \mathbb R^{V\times V}$ and the sufficient statistics are $(x, xx^T)\in \{-1,1\}^V\times \{-1,1\}^{V\times V}$.
The normalizing constant is the complicated function
$$\Lambda(Q^1, Q^2)=\sum _{x\in \{-1,1\}^V}\exp\left(\sum_{i\in V}Q^1_ix_i+\sum_{(i,j)\in E}Q^2_{ij}x_ix_j\right)$$
source: pg 3 of


text:
Q: ggplot creates artefacts in plot with geom_line() I have two vectors x,y and want to create a line plot for y over x.
y =  c(-0.0400785, -0.0304795, -0.0208800, -0.0112805, -0.0016810,  0.0079185,  0.0175180,  0.0271175,
       0.0367170,  0.0463160,  0.0559155,  0.0655150,  0.0751145,  0.0847140,  0.0943135,  0.1039130,
       0.1135125,  0.1231120,  0.1327110,  0.1423105,  0.1519100)

x = c(-5.867304, -5.879089, -5.987021, -6.309500, -6.770748, -7.189354, -7.455675, -7.545589, -7.463138,
      -7.371971, -7.407384, -7.461245, -7.398057, -7.192540, -7.010408, -6.961792, -6.994748, -6.971052,
      -6.779542, -6.536575, -6.301766)

If I use the base plot function everything is fine.
plot(x,y, type = "l")

If I create a line plot using ggplot
library(ggplot2)
df = data.frame("y" = y, "x" = x)
ggplot(data = df) + geom_line(aes(x = x, y = y))

It introduces strange artefacts, as if wrong x are ordered to wrong y. Does anyone have the same experience and even better a solution for that problem?

A: You have to use geom_path:
ggplot(data = df) +
  geom_path(aes(x = x, y = y))


text:
Q: Tensorflow error: An initializer for variable dense_1/kernel of dtype: 'complex64' is required I am getting the following error when the code comes to the dense layer -> second line (y_est =...)

Tensorflow error:  An initializer for variable dense_1/kernel of dtype:'complex64' is required

My variable y_in has a complex value and it seems I have to initialize my dense layer with the same variable type (complex64) but I don't know how to do it.
Any ideas?
y_in = tf.reshape(input, shape=[-1,self.n])
y_est = tf.layers.dense(y_in, 20, activation= tf.nn.tanh) # line with error
h_hat = tf.layers.dense(y_est, 2, activation= None)

Thank you very much.

A: You have not specified your own custom kernel_initializer, and the standard initializers in TensorFlow do not support complex weights yet. See this ticket for the details and possible solutions.


text:
Q: What is type in auth_item table in rbac Yii2 I have been trying to setup rbac DbManager following the Yii2 GUide. So, I have create tables in database as their instruction using the migrate command. I found that there are few tables created. Now my problem is that there is column type in the table auth_item. I do not understand why it is used?

A: It is simply the auth item type :

The type of the item. This should be either TYPE_ROLE or TYPE_PERMISSION.

Read more : http://www.yiiframework.com/doc-2.0/yii-rbac-item.html

A: If you want to assign this item to someone as a role, then you should choose #1 because, as per the Yii Documentation, TYPE_ROLE = 1.
Likewise, to give permission to someone (User) to access the item, you should choose #2 as TYPE_PERMISSION = 2.


text:
Q: Apex line chart overflowing on first render and if anything changed it goes back to normal I'm using MUI and in there used ApexChart, but in case of line chart, the chart is overflowing, and makes the horizontal scroll appear. Here is the attached image:

If any state is changed in the page the width goes back to normal and the horizontal scroll goes back to normal. Here is the after image

And here are the options I'm using with the chart:
  <Card sx={{ maxWidth: "xl" }}>
      <CardContent
        sx={{
          "& .apexcharts-xaxis-label": { fontSize: "0.875rem" },
          "& .apexcharts-canvas svg": {
            maxWidth: "100%",
          },
        }}
      >
        <ReactApexChart
          type="line"
          height={206}
          options={options}
          width={"100%"}
          series={[
            {
              name: "Total Responses",
              data: [700, 258, 530, 240, 610, 400, 100, 610, 700],
            },
          ]}
        />
      </CardContent>
    </Card>

const options = {
    chart: {
      parentHeightOffset: 0,
      toolbar: { show: false },
      width: "100%",
    },
    fill: {
      type: "gradient",
      gradient: {
        opacityTo: 0.2,
        opacityFrom: 1,
        shadeIntensity: 0,
        type: "horizontal",
        stops: [0, 100, 100],
      },
    },
    stroke: {
      width: 5,
      //   curve: "smooth",
      //   lineCap: "round",
    },
    legend: { show: false },
    colors: [theme.palette.warning.main],
    grid: {
      strokeDashArray: 7,
      padding: {
        top: -1,
        right: 0,
        // left: -12,
        bottom: 5,
      },
    },
    xaxis: {
      axisTicks: { show: false },
      axisBorder: { show: false },
      categories: [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Nov",
        "Dec",
      ],
    },
    yaxis: {
      show: true,
    },
  };

I'm expecting the chart to always take the 100% width of its container and not to overflow.


text:
Q: doubt with the proposition used Is there any correction required for this sentence, She's waiting for people to respond by the invitations they sent out, is by the right preposition to use, if not then why ? and why can we use ** to instead of by ** ??

A: I advocate the use of 'to' in this regard:
Check Cambridge Advanced Learners it is a great dictionary that highlights the correct use of prepositions. I tend to believe that it's the only dictionary that has the various uses of prepositions highlighted in the examples.
Examples
I want to respond to something that Norman said.
He responded by marching off and slamming the door behind him.
As you can see, by is used to refer to the subject that responds rather than the recipient/receiver.


text:
Q: How can I run detached command with sudo over ssh? I want to run some script through ssh and detach it, so it run even after ssh session is closed. I need to do this with sudo.
I can run some script but I am not able to detach it.
I tried following commands:
ssh 10.0.139.120 -t "sudo -b nohup some_script"

and
ssh 10.0.139.120 -t "sudo nohup some_script &"

Neither of above worked. Every time I get communicate "Connection to 10.0.139.171 closed." and no process is running on server.
I have also tried to do it with screen:
ssh 10.0.139.120 -t "sudo screen -S script -md some_script"

It did not work either, even though command works when I enter it on server locally.
How can I do it then?

A: I did small survey and found this similar question on Stack Overflow. At all you must add path to the script or must go inside the directory, where the script is located:
ssh remote-host -t "sudo -b sh -c 'nohup /path/some_script > /dev/null 2>&1 &'"

ssh remote-host -t "sudo -b sh -c 'cd /path; nohup ./some_script > /dev/null 2>&1 &'"

Without sh -c or bash -c the ampersand & at the end breaks the command in some way.

I couldn't manage to use disown for this purpose, but setsid works  well:
 ssh remote-host -t 'sudo -b setsid /path/some_script'

A: You can try using disown to avoid the process being killed after you close you ssh session.


text:
Q: Using np package to publish to npm or yarn I'm trying to use np to publish a package to npm. Everything seems to be going fine until it hits the bumping the version number. I can't figure out what is going wrong.
  ✔ Prerequisite check
  ✔ Git
  ✔ Cleanup
  ✔ Installing dependencies using npm
  ✔ Running tests using npm
  ✖ Bumping version using npm
    → v1.0.3
    Publishing package using npm
    Pushing tags

✖ Command failed: npm version 1.0.3
npm ERR! code 128
npm ERR! Command failed: git tag v1.0.3 -sm 1.0.3
npm ERR! error: cannot run gpg: No such file or directory
npm ERR! error: gpg failed to sign the data
npm ERR! error: unable to sign the tag
npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ds/.npm/_logs/2019-06-28T13_11_44_469Z-debug.log

v1.0.3

A: The problem was that I had set version-sign-git-tag to true, and since I have no gpg installed on my machine, the signing of the tags was failing. Setting the flag to false solved the issue. Not the best approach I guess, but the quickest.


text:
Q: Using Java to read and process textfile with custom column and row separators I have a text file which contains content scraped from webpages. The text file is structured like this:
|NEWTAB|lkfalskdjlskjdflsj|NEWTAB|lkjsldkjslkdjf|NEWTAB|sdlfkjsldkjf|NEWLINE|lksjlkjsdl|NEWTAB|lkjlkjlkj|NEWTAB|sdkjlkjsld
|NEWLINE| indicates the start of a new line (i.e., a new row in the data)
|NEWTAB| indicates the start of a new field within a line (i.e. a new column in the data)
I need to split the text file into fields and lines and store in an array or some other data structure. Content between |NEWLINE| strings may contain actual new lines (i.e. \n), but these don't indicate an actual new row in the data.
I started by reading each character in one by one and looking at sets of 8 consecutive characters to see if they contained |NEWTAB|. My method proved to be unreliable and ugly. I am looking for the best practice on this. Would the best method be to read the whole text file in as a single string, and then use a string split on "|NEWLINE|" and then string splits on the resulting strings using "|NEWTAB|"?
Many thanks!

A: You could do something like this:
Scanner scanner = new Scanner(new File("myFile.txt"));

List<List<String>> rows = new ArrayList<List<String>>();
List<String> column = new ArrayList<String>();

while (scanner.hasNext()) {

    for (String elem : scanner.nextLine().split("\\|")) {

    System.out.println(elem);

    if (elem.equals("NEWTAB") || elem.equals(""))
        continue;
    else if (elem.equals("NEWLINE")) {
        rows.add(column);
        column = new ArrayList<String>();
    } else
        column.add(elem);
    }
}

Took me a while to write it up, since I don't have IntelliJ or Eclipse on this computer and had to use Emacs.
EDIT: This is a bit more verbose than I like, but it works with |s that are part of the text:
Scanner scanner = new Scanner(new File("myFile.txt"));
List<List<String>> rows = new ArrayList<List<String>>();
List<String> lines = new ArrayList<String>();
String line = "";

while (scanner.hasNext()) {
    line += scanner.nextLine();
    int index = 0;
    while ((index = line.indexOf("|NEWLINE|")) >= 0) {
        lines.add(line.substring(0, index));
        line = line.substring(index + 9);
    }
}

if (!line.equals(""))
    lines.add(line);

for (String l : lines) {
    List<String> columns = new ArrayList<String>();
    for (String column : l.split("\\|NEWTAB\\|"))
        if (!column.equals(""))
            columns.add(column);
    rows.add(columns);
}

A: I think that the other answers will work too, but my solution is as follows:
FileReader inputStream = null;
StringBuilder builder = new StringBuilder();

try {
    inputStream = new FileReader(args[0]);
    int c;
    char d;

    while ((c = inputStream.read()) != -1) {
        d = (char)c;
        builder.append(d);
    }
}

finally {
    if (inputStream != null) {
        inputStream.close();
    }
}

String myString = builder.toString();

String rows[] = myString.split("\\|NEWLINE\\|");

for (String row : rows) {
    String cols[] = row.split("\\|NEWTAB\\|");

    /* do something with cols - e.g., store */
}


text:
Q: What is the button on the end of the taskbar to clear the screen called? I don't know what the button on the end of the Windows taskbar which clears the screen is called. Anybody know?

A: It is just called the "Show Desktop Button"

A: "Show Desktop Button" is its name. But it doesn't just hide all windows. If you click it again, it will show them again, just as they were before you pressed it the first time. Winkey+D shortcut does the same. Basically, it toggles between all your visible windows and desktop.
Also, if you want to hide all windows, press Winkey+M. Pressing this combination multiple times will not bring up the hidden windows, you'll have to do it manually. A useful "boss-key".


text:
Q: eclipse throwing swt errror when adding a server Eclipse swt error while adding a server. I am using ubuntu 16.04. This error does not occur if I use 2019 eclipse version. Is this error related to gtk ?

emphasized text


text:
Q: Footer not placed correctly (not taking full width) I'd like my footer to take the whole width of my page but for some reason it does not work when I preview in safari (it looks OK within dreamweaver). What is wrong? I'd like it to be placed at the bottom of the page and take the whole width.
<!DOCTYPE html>

    <meta charset="utf-8">
  <title>
    Liveweave
  </title>

    My Name

          Menu I

              Biography

              Publications

            Menu 2

                Demo

                Features

                Comparison

            Menu 3

                Item 1

                Item 2

                Item 3

            Menu 4

                ddfd

                dsfd

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
      quis nostrud exercitation ullamco laboris nisi ut.

            Lorem Ipsum

            Lorem ipsum dolor sit amet, consectetur adipisicing elit... nisi ut aliquip ex ea commodo consequat.

            Ipsum

            Lorem ipsum dolor sit amet, consectetur adipisicing elit... laboris nisi ut aliquip ex ea commodo consequat.

            Lorem

            Lorem ipsum dolor sit amet, consectetur a... laboris nisi ut aliquip ex ea commodo consequat.

        Novitates autem si spem

        Novitates autem si spem adferunt, ut tamquam in herbis non fallacibus
        fructus appareat, non sunt illae quidem repudiandae, vetustas tamen suo
        loco conservanda; maxima est enim vis vetustatis et consuetudinis. Quin
        in ipso equo, cuius modo feci mentionem, si nulla res impediat, nemo est,
        quin eo, quo consuevit, libentius utatur quam intractato et novo. Nec vero
        in hoc quod est animal, sed in iis etiam quae sunt inanima, consuetudo
        valet, cum locis ipsis delectemur, montuosis etiam et silvestribus, in
        quibus diutius commorati sumus.

        This is a sub-title

        Ultima Syriarum est Palaestina per intervalla magna protenta, cultis abundans
        terris et nitidis et civitates habens quasdam egregias, nullam nulli cedentem
                sed sibi vicissim velut ad perpendiculum aemulas: Caesaream, quam ad honorem
                Octaviani principis exaedificavit Herodes, et Eleutheropolim et Neapolim
                itidemque Ascalonem Gazam aevo superiore exstructas.

        Itaque verae amicitiae difficillime reperiuntur in iis qui in honoribus
        reque publica versantur; ubi enim istum invenias qui honorem amici anteponat
        suo? Quid? Haec ut omittam, quam graves, quam difficiles plerisque videntur
        calamitatum societates! Ad quas non est facile inventu qui descendant.
        Quamquam Ennius recte. END END END

        Hot News

          Check us also on :

A: You need to specify width as 100%
 #main_footer {
        clear:both;
        position: fixed;
        background: #cfc8c0;
        height: 46px;
        overflow: hidden;
        display: block;
        bottom:0; width:100%
      }

DEMO

A: Please add css as per below
#main_footer{
    width:100%;
}

http://liveweave.com/xlhGg9

A: your footer doesn't have any width defined.
give width 100% to your footer i.e. update #main_footer css with below
#main_footer {
   clear: both;
   position: fixed;
   background: #cfc8c0;
   height: 46px;
   overflow: hidden;
   display: block;
   bottom: 0;
   width: 100%; /* add this rule */
}

see your working example

A: You've given it a fixed position and not supplied a width. position: fixed; is only as large as the content it contains unless you specify otherwise.
Add width: 100%; to the CSS for the footer.

A: width: 100%; Or width: 100vw; will do. You didn't define the width.


text:
Q: InputMismatchException while inputting multiple lines into ArrayList While putting a .txt file into a list I keep running into a InputMismatchException error. That won't read the "MovieType" or "AlbumTitle". Relevant code has been added.
public class MovieManager {

    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<MediaItem> list = new ArrayList<>();
        Scanner inputFile = new Scanner(new File("collection.txt"));
        try {
            while (inputFile.hasNextLine()){
                String mediaType = inputFile.nextLine();
                if (mediaType.equals("Movie")){
                    String movieTitle = inputFile.nextLine();
                    //System.out.println("String" + movieTitle);
                    int movieYear = inputFile.nextInt();
                    //System.out.println("int" + movieYear);
                    String movieType = inputFile.nextLine();
                    //System.out.println("String" + movieType);
                    Movie mov = new Movie(movieTitle, movieYear, movieType);
                    list.add(mov);
                } else if (mediaType.equals("Album")) {
                    String albumArtist = inputFile.nextLine();
                    //System.out.println("String" + albumArtist);
                    int albumYear = inputFile.nextInt();
                    //System.out.println("int" + albumYear);
                    String albumTitle = inputFile.nextLine();
                    //System.out.println("String" + albumTitle);
                    Album alb = new Album(albumArtist, albumYear, albumTitle);
                    list.add(alb);
               }
            }
            inputFile.close();
            System.out.print(list);
        } catch(InputMismatchException e) {
           inputFile.next();
        }
    }
}

Collection.txt
Album
ABBA
1976
Arrival
Album
ABBA
1981
The Visitors
Album
The Beatles
1969
Abbey Road
Album
Nazareth
1975
Hair of the Dog
Movie
Beauty and the Beast
1991
VHS
Movie
It's a Wonderful Life
1946
DVD
Movie
Tron
1983
Laserdisc
Movie
Tron: Legacy
2010
Blu-ray

A: With an input stream containing 1976\n, a call to Scanner#nextInt() will consume only the digit characters.  It leaves the \n newline character in the input stream, for the next call to a Scanner method to deal with.
The subsequent call to Scanner#nextLine() immediately sees the \n, character, and consumes it, and returns the empty string, because after the digits 1976 to the end of the line was the empty string.
Or, visualized another way...  nextLine(), nextInt(), nextLine() parses:
ABBA \n 1976 \n Arrival \n

as:
[ABBA\n][1976][\n]

returning:
"ABBA"   1976  ""

Solution:

 You need to discard the remainder of the "year" line, after calling nextInt(), by immediately calling nextLine(), and ignoring the returned value.


text:
Q: String comparison - strA.ToLower()==strB.ToLower() or strA.Equals(strB,StringComparisonType)? As per title, what practise for string comparisons do you use and why?

A: The Equals call scales better, as it's one string operation instead of three.
You get the best performance for case insensetive comparison with the StringComparison.OrdinalIgnoreCase option. However, as it doesn't consider cultural differences it might not always give the result that you want.
If you want to change the case for comparison, it's recommended that you use ToUpper rather than ToLower. Some exotic letters doesn't convert properly from upper to lower case, but conversion from lower to upper case works.
In most cases the performance is not crucial, so you should use the alternative that makes most sense in the situation.
You haven't specified which language you are using, but from the == operator it looks like C#. If you would use VB, you should consider that the = operator doesn't use the equality opreator of the string class, but VB's own logic for doing comparisons, which is slightly different.

A: You haven't specified a platform, but I'm guessing .NET. I would strongly suggest you use the latter form - because case comparisons aren't as simple as you might expect. (It also avoids creating extra strings, but that's a different matter.)
For example, what do you want your code to do when presented with "mail" and "MAIL" when it's running in Turkey? If you use ToLower it will return false, and likewise if you use CurrentCultureIgnoreCase - but if you use InvariantCultureIgnoreCase it will return true. You need to think about the source of the data and what you're trying achieve with it.
See the recommendations for using strings in MSDN for more information and guidance.
Aside from anything else, I'd say that the latter expresses your intent more effectively. You're not actually interested in the lower case values of the strings - you're interested in equality in a case-insensitive way... which is exactly what the second form expresses.

A: I feel more better in using second one than first one. Because, the second type will be supported in all languages and it will be more convenient to use.

A: Benchmark:

Method
Mean
Error
StdDev
Gen0
Allocated

ToLower
47.653 ns
2.0118 ns
0.1103 ns
0.0127
80 B

OrdinalIgnoreCase
7.432 ns
0.1664 ns
0.0091 ns
-
-


text:
Q: Upload a photo via Graph API using Jersey I have a Java application and i try to upload a photo to Facebook via graph api with Jersey.
Until now everything works fine with Jersey I can publish messages etc.
I searched hours to find an example how to do it.
The best tutorial I found was this one:
http://neopatel.blogspot.de/2011/04/jersey-posting-multipart-data.html
The only thing I know is that I have to use multipart/formdata.
Does anyone have an example or know have to do this?

A: Did you try using the jersey-multipart package?
You create a FormDataMultiPart with a FileDataBodyPart for the file and a FormDataBodyPart for the message and access_token..

A: This is my Solution.
String url = "https://graph.facebook.com/me/photos";
File file = new File("path");

ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(MultiPartWriter.class);
Client client = Client.create(cc);

WebResource webResource = client.resource(url);
FormDataMultiPart fdmp = new FormDataMultiPart();

fdmp.bodyPart(new FileDataBodyPart("source", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
fdmp.bodyPart(new FormDataBodyPart("message", "YAY I did it!"));
fdmp.bodyPart(new FormDataBodyPart("access_token", accessToken));

ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fdmp);
String string = response.getEntity(String.class);


text:
Q: Python PEG Grammar Notation Here is a snippet from the new python PEG grammar.
# type_expressions allow */** but ignore them
type_expressions:
    | ','.expression+ ',' '*' expression ',' '**' expression
    | ','.expression+ ',' '*' expression
    | ','.expression+ ',' '**' expression
    | '*' expression ',' '**' expression
    | '*' expression
    | '**' expression
    | ','.expression+

I don't understand what the dotted notation ','.expression+ means here? How do i read this? A python snippet matching it would be welcome.
Considering the context:
func_type: '(' [type_expressions] ')' '->' expression NEWLINE* ENDMARKER

It seems like type_expressions are function arguments, but I don't see how? How does it match multiple arguments?
The Docs state the following:

The notation is a mixture of EBNF and PEG. In particular, & followed by a symbol, token or parenthesized group indicates a positive lookahead (i.e., is required to match but not consumed), while ! indicates a negative lookahead (i.e., is required not to match). We use the | separator to mean PEG's "ordered choice" (written as / in traditional PEG grammars).

I checked both the EBNF and PEG wikipedia page, and the only thing I found is that the dot is a terminator symbol according to conventions. But that is confusing because semi colon is also a terminator symbol and in this context it doesn't seem like a terminator symbol.


text:
Q: ZCA whitening in python for Machine learning I am training 1000 images of 28x28 size. But before training, I am performing ZCA whitening on my data by taking the reference from How to implement ZCA Whitening? Python.
Since I have 1000 data images of size 28x28, after flattening, it becomes 1000x784.
But as given in the code below, whether X is my image dataset of 1000x784?
If it is so, then it means the ZCAMatrix size is 1000x1000.
In this case, for prediction I have a image of size 28x28, or we can say, size of 1x784.So it doesn't make sense to multiply ZCAMatrix to the image.
So I think, X is the transpose of image data set. Am I right?
If I am right, then the size of ZCAMatrix is 784x784.
Now how should I calculate the ZCA whitened image, whether I should use np.dot(ZCAMatrix, transpose_of_image_to_be_predict) or np.dot(image_to_be_predict, ZCAMatrix)?
Suggestion would be greatly appreciate.
def zca_whitening_matrix(X):
    """
    Function to compute ZCA whitening matrix (aka Mahalanobis whitening).
    INPUT:  X: [M x N] matrix.
        Rows: Variables
        Columns: Observations
    OUTPUT: ZCAMatrix: [M x M] matrix
    """
    # Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N
    sigma = np.cov(X, rowvar=True) # [M x M]
    # Singular Value Decomposition. X = U * np.diag(S) * V
    U,S,V = np.linalg.svd(sigma)
        # U: [M x M] eigenvectors of sigma.
        # S: [M x 1] eigenvalues of sigma.
        # V: [M x M] transpose of U
    # Whitening constant: prevents division by zero
    epsilon = 1e-5
    # ZCA Whitening matrix: U * Lambda * U'
    ZCAMatrix = np.dot(U, np.dot(np.diag(1.0/np.sqrt(S + epsilon)), U.T)) # [M x M]
    return ZCAMatrix

And an example of the usage:
X = np.array([[0, 2, 2], [1, 1, 0], [2, 0, 1], [1, 3, 5], [10, 10, 10] ]) # Input: X [5 x 3] matrix
ZCAMatrix = zca_whitening_matrix(X) # get ZCAMatrix
ZCAMatrix # [5 x 5] matrix
xZCAMatrix = np.dot(ZCAMatrix, X) # project X onto the ZCAMatrix
xZCAMatrix # [5 x 3] matrix

A: I got the reference from the Keras code available here.
It is very clear that in my case the co-variance matrix will give 784x784 matrix, on which Singular Value Decomposition is performed. It gives 3 matrix that is used to calculate the principal_components, and that principal_components is used to find the ZCA whitened data.
Now my question was

how should I calculate the ZCA whitened image, whether I should use
  np.dot(ZCAMatrix, transpose_of_image_to_be_predict) or
  np.dot(image_to_be_predict, ZCAMatrix)? Suggestion would be greatly
  appreciate.

For this I got the reference from here.
Here I need to use np.dot(image_to_be_predict, ZCAMatrix) to calculate the ZCA whitened image.


text:
Q: Diango matching a string with a regex field In django, if we have a regex and look for a rows whose a field is matching with a regex, it will be something like this:
MyAudience.objects.filter(email__iregex=f'^({'|'.join(emails)})$')

But what if I want to do it the other way?
Let's say I have a string:
email = 'abc@example.com'

and in my model AudienceFilter, I have a field pattern. This column keeps the regex for the model. I want to find with patterns do match my string? How can I do that?
AudienceFilter.objects.filter(pattern__?????=email)

A: You can inject the value as an alias, and then annotate:
from django.db.models import F, Value

AudienceFilter.objects.alias(email=Value(email)).filter(
    email__iregex=F('pattern')
)


text:
Q: Fix div at the bottom. (Without using javascript) To try to explain my problem, I did the following code:
http://jsfiddle.net/Ridermansb/REYZ6/
The question is.
The div "Footer" should always be glued to the bottom of the screen (bottom: 0).
BUT if the div "content" grow to the point of creating a scroll bar, the div "footer" should be just below the div "content"
One should never overlap each other!
As you can see in the example, if the screen is too small the "#footer" will override "#content". This can not happen!
Thanks!

A: From what I understand per your fiddle, what you want to do is impossible with just css.  That said, I've come up with a single line in jquery you can use to do what I think you want:
$('#spacer').height($("#footer > div").height());

Demo
Non jquery code:
document.getElementById('spacer').style.height = document.getElementById('footer-inner').offsetHeight + "px";

Demo
Both snippets however require a slight change to your HTML structure; they both add in a spacer div that pushes up the content out from under the footer div.  The second snippet however requires you give your footer's inner div an id as well.

A: .container {
    position: relative;
}
.container .glued_bottom {
    position: absolute;
    bottom: 0;
    height: 20px;
}

A: few ways to tackle the footer layouts
using percentage heights can work in some cases
html, body { height:100%;}
#header {height:10%; }
#content { height:80%; }
#footer { height:10%;}

Appreciate it might not fit for the content of your site, but worth a look as css only option.
Another is the use of background css elements , color your page to be your footer color ( lets say green )
and set the header and content elements to be, say, white for eg purposes
body { background-color:green; }
#header { background-color:white; }
#content { background-color:white; }

... Couple of non Javascript ideas to play with possibly
Yes, fixed or abs positioning will cause the overlaps without adding some Javascript to keep watch and make repositioning alterations.
Hope helps a little

A: Via this sticky footer tutorial. The following code should be all you need to create a sticky footer.
* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

/*

Sticky Footer by Ryan Fait
http://ryanfait.com/

*/

In your case, you were missing pretty much all of the above css except for the 100% height on the html and body. I have updated your jsfiddle.
Live DEMO

A: Use CSS's position:fixed; on the element with bottom and left set. e.g.:
#footer {
position: fixed;
bottom: 0px;
left: 0px;
}


text:
Q: How do you get info for an arbitrary time zone in Linux / POSIX? Ideally, what I'd like to be able to do is take the name of a time zone and call a function to ask for its corresponding time zone info (offset from UTC, DST offset, dates for DST switch, etc.) in Linux. However, I can't find any way to do this. The information exists in /usr/share/zoneinfo/ in the various binary files there, but I don't know how to read them or if there is a way to get the OS to give you the information in them rather than having to read them in yourself. So, I'm looking for a way to get this information. Ideally, there would be a posix function which would do it for you so that it would work on POSIX systems other than Linux, but if there isn't, I'd at least like to know the proper way (or at least the best way) to get the time zone info for an arbitrary time zone in Linux.

A: The tzcode package (found along with the data at  ftp://ftp.iana.org/tz/releases) contains a description of the tzfile format along with a header file tzfile.h for working directly with that data.

A: There isn't a standard way to do that.  You could look at ICU.  It claims:

*

*Formatting: Format numbers, dates, times and currency amounts according the conventions of a chosen locale. This includes translating month and day names into the selected language, choosing appropriate abbreviations, ordering fields correctly, etc. This data also comes from the Common Locale Data Repository.

*Time Calculations: Multiple types of calendars are provided beyond the traditional Gregorian calendar. A thorough set of timezone calculation APIs are provided (emphasis added).

A: New answer for an old question.
Rationale for new answer:  There is now a modern, free, open-source, C++11/14/17 library to do this.1  It does require some installation.  But it is portable across Linux/macOS/Windows.  And it has full documentation, and even a video introduction.
Here is an example program to get information about a specific time zone.  I'm using my own timezone just as an example.  This library supports the full IANA timezone database:
#include "tz.h"
#include <iostream>

int
main()
{
    auto zone = date::locate_zone("America/New_York");
    std::cout << *zone << '\n';
    std::cout << zone->get_info(std::chrono::system_clock::now()) << '\n';
}

The first line looks up a database by its IANA name.
auto zone = date::locate_zone("America/New_York");

The return type is a date::time_zone const*.  This function can never return nullptr, though it will throw if it can't locate the time zone (with an excellent what()).
The second line prints out the definition of the time zone:
std::cout << *zone << '\n';

The output of this line is not generally useful to clients of this library.  It is mainly useful to myself in debugging the library:
America/New_York                   -04:56:02                  LMT        1883 Nov/18                  12:03:58         1883-11-18 17:00:00 UTC   1883-11-18 12:03:58 STD   1883-11-18 12:03:58   00:00      {nullptr, -32768}   {nullptr, 32767}
                                   -05:00:00   US             E%sT       1920 Jan/01                  00:00:00         1920-01-01 05:00:00 UTC   1920-01-01 00:00:00 STD   1920-01-01 00:00:00   00:00   S   {US             1918    1919    Mar/Sun[last]           02:00:00       01:00   D, 1918}   {US             1918    1919    Oct/Sun[last]           02:00:00       00:00   S, 1919}
                                   -05:00:00   NYC            E%sT       1942 Jan/01                  00:00:00         1942-01-01 05:00:00 UTC   1942-01-01 00:00:00 STD   1942-01-01 00:00:00   00:00   S   {NYC            1920    1920    Mar/28                  02:00:00       01:00   D, 1920}   {NYC            1921    1954    Sep/Sun[last]           02:00:00       00:00   S, 1941}
                                   -05:00:00   US             E%sT       1946 Jan/01                  00:00:00         1946-01-01 05:00:00 UTC   1946-01-01 00:00:00 STD   1946-01-01 00:00:00   00:00   S   {US             1942    1942    Feb/09                  02:00:00       01:00   W, 1942}   {US             1945    1945    Sep/30                  02:00:00       00:00   S, 1945}
                                   -05:00:00   NYC            E%sT       1967 Jan/01                  00:00:00         1967-01-01 05:00:00 UTC   1967-01-01 00:00:00 STD   1967-01-01 00:00:00   00:00   S   {NYC            1921    1954    Apr/Sun[last]           02:00:00       01:00   D, 1946}   {NYC            1955    1966    Oct/Sun[last]           02:00:00       00:00   S, 1966}
                                   -05:00:00   US             E%sT       32767 Dec/31                  00:00:00UTC      32767-12-31 00:00:00 UTC   32767-12-30 19:00:00 STD   32767-12-30 19:00:00   00:00   S   {US             1967    1973    Apr/Sun[last]           02:00:00       01:00   D, 1967}   {US             2007    32767    Nov/Sun[1]              02:00:00       00:00   S, 32767}

But one of the reasons for me showing this line is to illustrate that asking for information about a time zone, without also supplying a time point, is not likely to give you the information you're looking for.  The information about a timezone is itself a function of time, including the offsets, daylight saving details, abbreviations, etc.
The final line:
std::cout << zone->get_info(std::chrono::system_clock::now()) << '\n';

is likely to be most helpful.  This returns an aggregate sys_info that looks like this:
struct sys_info
{
    sys_seconds          begin;
    sys_seconds          end;
    std::chrono::seconds offset;
    std::chrono::minutes save;
    std::string          abbrev;
};

This just output for me:
2016-11-06 06:00:00
2017-03-12 07:00:00
-05:00:00
00:00
EST

Which means:

*

*This information is valid from 2016-11-06 06:00:00 UTC up until (but not including) 2017-03-12 07:00:00 UTC.

*The UTC offset for this time period is -5 hours.

*This is not considered a daylight saving period (save == 00:00).

*The abbreviation for this period is EST.

Of course you can access the fields of this aggregate in your program as opposed to just printing them out.
If you want to see what this result might look like 6 months from now:
std::cout << zone->get_info(std::chrono::system_clock::now() + date::months{6}) << '\n';

which currently outputs:
2017-03-12 07:00:00
2017-11-05 06:00:00
-04:00:00
01:00
EDT

This is all considered to be low-level access in this library.  There exists higher-level API so that you don't have to deal with low level concepts such as the current UTC offset.  The low-level stuff is there if you need it (not hidden away), but not necessary for common use cases such as getting the current time in any specific time zone:
using namespace date;
using namespace std::chrono;
std::cout << make_zoned("America/New_York", system_clock::now()) << '\n';

which just output for me:
2017-03-07 19:26:53.711662 EST

In C++17, due to template deduction guides, the above line will no longer need "make factory functions" for deduction purposes:
std::cout << zoned_time{"America/New_York", system_clock::now()} << '\n';

zoned_time is a class template, templated on duration, and deduced by the chrono::duration of the chrono::time_point (the second argument -- in my case microseconds).
This is a full-featured date/time/timezone library with both low-level access, and high-level abstractions (true to the philosophy of C++). Correctness and type-safety are highly valued in this library.  It is an extension, not a replacement, of the <chrono> library introduced in C++11.

1Disclaimer: I am the principal author of this library, though there are many contributors (to which I am grateful).


text:
Q: share it on Ubuntu 16.04 I want to transfer files from my smartphone to the desktop so I can install wine and configure it with windows 7 and download share-it. It got installed alright using Wine but every time I double-click on the share-it shortcut it does not work. I am trying to find out a way to use share-it on Ubuntu 16.04

A: You could try AirDroid. It is similar to SHAREit but they also have a native linux variant for transferring from Android to desktop.
There also seems to be Shareit for Linux, however I'm not sure how safe this is. Try at your own risk - http://shareitappforpc.com/shareit-for-linux-download.
These are alternatives and probably don't fix your problem.

A: Shareit can be installed on Ubuntu 16.04 using wine. Wine installation described here.


text:
Q: Copy to clipboard using Javascript macro I'm pretty inexperienced with Javascript, especially within LaTeX, so I'd like some pointers, guidance or even an MWE of my proposed "button":
I want to create a button to copy data to the system clipboard. For this I'd like to suggest using a workaround with a flash leak (don't know if it works):
function copy(str) {
   var D=document;
    if(!copy.div) { copy.div = D.createElement('div'); D.body.appendChild(copy.div);  }

flashVar = "Q1dTB3kAAAB4nKtgYI1nYOBfwMDAw8jgzPT//3975lAGBoYOdQYWhu\
SczIKk/MSiFIac1Lz0kgyG4MriktRchuLUEme41DQmBg4GGRDJ6Cc0l4l  BAibCzsDO\
CDSJgwksyRwkzuAA5AIAd7oY/w==";

copy.div.innerHTML =  '<embed src="'+flashVar+'" FlashVars="clipboard='+encodeURIComponent(str) +
    '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
}

I want to use the following button which will do the copying:
\documentclass[11pt,a4paper]{standalone}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shadows}

\newcommand*\button{%
  \tikz[baseline=(key.base)]
    \node[%
      draw,
      fill=white,
      drop shadow={shadow xshift=0.25ex,shadow yshift=-0.25ex,fill=black,opacity=0.75},
      rectangle,
      rounded corners=2pt,
      inner sep=1pt,
      line width=0.5pt,
      font=\scriptsize\sffamily
    ](key) {Ctrl\strut}
  ;
    \tikz[baseline=(key.base)]
    \node[%
      draw,
      fill=white,
      drop shadow={shadow xshift=0.25ex,shadow yshift=-0.25ex,fill=black,opacity=0.75},
      rectangle,
      rounded corners=2pt,
      inner sep=1pt,
      line width=0.5pt,
      font=\scriptsize\sffamily
    ](key) {C\strut}
  ;
}

\begin{document}
\button
\end{document}

A: You have already asked the same question without the code some hours ago - maybe you could have modified it instead of posting it again.
Regarding your question:

*

*Be aware that JavaScript in PDF does not work reliably. It is often disabled for security purposes and other PDF readers than Acrobat may behave different or even lack JS support.

*Be sure to test with the newest Acrobat version. Adobe strengthened security recently and introduced an application sandbox. Reading the clipboard should (hopefully) be off limit / impossible as this would be an information leak (for example if you copied a password in the clipboard before). Overwriting the system clipboard may be blocked too (web browsers block it, for example).

*A workaround may be to write the content into a form-field in the document and asking the user to copy it manually.


text:
Q: Как работает проекция с камер в three.js? Не могу понять, как работает проекция векторов с использованием камер на three.js
Вроде, на обычную проекция векторов не похоже, ссылки из официальной документации на википедию ясности не внесли
На картинке пример проекции:
new THREE.Vector3( 5, 7, 0 ).project( camera );

A: Разобрался как происходит unproject
Если смотреть из камеры, то можно рассматривать текущую видимую область, как прямоугольник с углами (-1; 1), (1; -1)
Бардовыми точкам отмечены unproject векторов {1; 1; 0} и {1; 0; 0} из этой самой камеры
project операция обратная unproject


text:
Q: OpenCV Add columns to a matrix in OpenCV 2 and later there is method Mat::resize that let's you add any number of rows with the default value to your matrix is there any equivalent method for the column. and if not what is the most efficient way to do this.
Thanks

A: Use cv::hconcat:
Mat mat;
Mat cols;

cv::hconcat(mat, cols, mat);

A: Worst case scenario: rotate the image by 90 degrees and use Mat::resize(), making columns become rows.

A: Since OpenCV, stores elements  of matrix rows sequentially one after another there is no direct method to increase column size but I bring up myself two  solutions for the above matter,
First using the following method (the order of copying elements is less than other methods), also you could use a similar method if you want to insert some rows or columns not specifically at the end of matrices.
void resizeCol(Mat& m, size_t sz, const Scalar& s)
{
    Mat tm(m.rows, m.cols + sz, m.type());
    tm.setTo(s);
    m.copyTo(tm(Rect(Point(0, 0), m.size())));
    m = tm;
}

And the other one if you are insisting not to include even copying data order into your algorithms then it is better to create your matrix with the big number of rows and columns and start the algorithm with the smaller submatrix then increase your matrix size by Mat::adjustROI method.


text:
Q: Trouble with refreshView in Nested Components I've built nested lightning components available for a contact page. There are three components: the Pane which sits on the record home page this has three tabs one tab is a text field, the other two tabs are used to display different nested components. One of these components is a list of tasks. Clicking on the subject of a task in the list fires an force:editRecord event. This successfully brings up the window and any changes are saved. However it does not refresh the view. I've tried accomplishing this in a couple ways.
I tried implementing the method suggested here, which handles a force:refreshView event and uses aura:dependency.
I also tried handling a force:saveRecordSuccess however the associated controller code was not being accessed as evidenced by no console logs.
I've attempted putting the handlers in both the child component and the parent Pane component with no difference in behavior.
Lastly I tried window.location.reload(); after firing the editRecord event but it reloads the page before bringing the edit page up.
List component markup
<aura:component controller="AccountDevelopmentTaskController" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId">
<aura:attribute name="challenges" type="Task[]" access="GLOBAL"/>
<aura:attribute name="id" type="String" access="GLOBAL"/>
<aura:handler name="init" value="{!this}" action="{!c.start}"/>
<aura:dependency resource="markup://force:editRecord" type="EVENT"/>
<aura:handler event="force:refreshView" action="{!c.start}"/>

         ...

            <aura:iteration var="chlng" items="{!v.challenges}">

                                <ui:outputText value="{!chlng.Subject}" class="slds-text-link_reset" />

                    ...

            </aura:iteration>

List component controller
 start : function(component,event,helper) {
    var id = component.get("v.id");
    var action = component.get("c.loadChallenges");
    action.setParams({"tId":id});
    action.setCallback(this,function(response){
        var tasks = response.getReturnValue();
        component.set("v.challenges",tasks);
    });
    $A.enqueueAction(action);
},

showEditPanel : function(component,event,helper){
    var editRecordEvent = $A.get("e.force:editRecord");
    var selectedItem = event.currentTarget;
    var recId = selectedItem.dataset.record;
    component.set("v.currParamId",recId);
    editRecordEvent.setParams({
        "recordId" : recId
    });
    editRecordEvent.fire();

}

Here is the Pane component compacted to the relevant bits:
<aura:component controller="AccountDevelopmentTaskController" access="global" implements="force:appHostable,flexipage:availableForRecordHome,force:hasRecordId">
  <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  <aura:attribute name="msg" type="String" access="GLOBAL"/>
  <lightning:tabset class="slds-box" >
    ...
     <lightning:tab label="Challenge">
        <c:ADChallengeList id="{!v.recordId}" /> ...

A: Update: I did not factor in the part that you are clicking on a specific record and geetting the record Id. updated the code to take in the selected record Id and pass it to the force:recordEdit component.
Note to others: The OP reported that this implementation was browser dependent, he was having issues on chrome v.61 /32 bit version, and had no issues on 64 bit version/IE
Here we go,, this is the craziest thing I have done in a long time. I recreated the whole $A.get("e.force:editRecord") event to gain control of the save button.
First the Output:

This code involves
1) Winter 18 developer edition.
2) Dynamically creating the force:recordedit component and save button and wiring the save button to call the recordsave (event). Because I used force:recordedit component I now get to use recordsavesuccess.
<aura:handler name="onSaveSuccess" event="force:recordSaveSuccess" action="{!c.start}"/>

3) An event that can self handle itself : I created the custom event just to call the handleedit function by passing the selected record ID from the list of challenge records in my component. From here we can start creating the dynamic components as required.
Ref: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_component_fire.htm
4)Idea taken from this post (Aura Id of dynamic component is coming back as undefined)
Aura:Id of dynamically created compontns cannot be accessed
5) A modal concept to mimic force:recordedit event (note I have created force:recordedit component and mimicked it to look like $A.get("e.force:editRecord") event)
http://www.sfdcmonkey.com/2017/04/15/modal-box-lightning-component-salesforce/
Now to the code
App:
<aura:application extends="force:slds">
    <c:forceeditsavesuccesscomp></c:forceeditsavesuccesscomp>
</aura:application>

Component:
I have defaulted the task Id, you can use {!v.recordId} or however you want to populate the Id of the record. Used some SLDS html to mimic the modal like feeling.
<aura:component controller="AccountDevelopmentTaskController" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:registerEvent name="handleedit" type="c:handleeditevent"/>

    <aura:attribute name="challenges" type="Task[]" access="GLOBAL"/>
    <aura:attribute name="id" type="String" access="GLOBAL" default="00TB0000005p4cVMAQ"/>
    <aura:handler name="init" value="{!this}" action="{!c.start}"/>
    <aura:handler name="handleedit" event="c:handleeditevent" action="{!c.handleedit}" />
    <aura:handler name="onSaveSuccess" event="force:recordSaveSuccess" action="{!c.start}"/>

    <aura:attribute name="isOpen" type="boolean" default="false"/>

                Subject

                <aura:iteration var="chlng" items="{!v.challenges}">

                                    <ui:outputText value="{!chlng.Subject}" class="slds-text-link_reset" />

                        ...

                </aura:iteration>

    <aura:if isTrue="{!v.isOpen}">

                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close">
                        Close
                    </button>

Modal Header

                    {!v.body}

    </aura:if>
</aura:component>

Controller:
    ({
    start : function(component,event,helper) {
        var id = component.get("v.id");
        var action = component.get("c.loadChallenges");
        action.setParams({"tId":id});
        action.setCallback(this,function(response){
            var tasks = response.getReturnValue();
            component.set("v.challenges",tasks);
        });
        $A.enqueueAction(action);
    },

    showEditPanel : function(component,event,helper){
        var selectedItem = event.currentTarget;
        var recId = selectedItem.dataset.record;
        component.set("v.isOpen", true);
        var compEvent = component.getEvent("handleedit");
        compEvent.setParams({
            "selectedId": recId
        }).fire();
    },
    handleedit: function(component,event,helper){
        /*createComponentController.js*/

        $A.createComponents([
            ["force:recordEdit",
             {
                 "aura:id": 'editrecord',
                 "recordId": event.getParam("selectedId")
             }],
            ["lightning:button",
             {
                 "aura:id" : 'savebutton',
                 "label": "Save record",
                 "onclick": component.getReference("c.handlePress")
             }]
        ],
                            function(editcomp, status, errorMessage){
                                //Add the new button to the body array
                                if (status === "SUCCESS") {
                                    var editval = editcomp[0];
                                    var button = editcomp[1];
                                    var body = component.get("v.body");
                                    body.push(editval);
                                    body.push(button);
                                    component.set("v.body", body);
                                }
                                else if (status === "INCOMPLETE") {
                                }
                                    else if (status === "ERROR") {

                                    }
                            }
                           );
    },
    handlePress : function(component) {
        //component.find always comes back as undefined. Look at point 4.
        console.log('#######'+ component.find("editrecord"));
        component.find({ instancesOf : "force:recordEdit" })[0].get("e.recordSave").fire();
        component.set("v.isOpen", false);
        // the body was rendering differently on second click after saving the modal ( assuming this could be due the way the component's init is being handled by calling the start method, but as a dirty fix I used location.reload() to get back to original state)
        window.location.reload();

    }

})

Event:
<aura:event type="COMPONENT" description="Event template" >
    <aura:attribute Name="selectedId" type="String" access="global"/>
</aura:event>

controller:
//I am returning a bunch of tasks here, I am assuming you are passing a contact/account Id and gathering the tasks related to the selected record.Rewire this controller as required.
public class AccountDevelopmentTaskController {

    @AuraEnabled
    public static Task loadChallenges(id tId){
        return [select id,Subject from task where Id=:tId];
    }
}


text:
Q: If the type of a parameter is interface{} how do you know whether you pass by pointer or by value? Given any function that takes a parameter of type interface{} how would I know whether or not to pass that parameter with or without & without navigating the source code of the function.
For example if I had a function with this type signature given to me:
func foo(x interface{}, y int) int

Would there be any way to figure out if x was supposed to be passed by value or by pointer?

A: Here is the snippet from the source:
// DecodeElement works like Unmarshal except that it takes
// a pointer to the start XML element to decode into v.
// It is useful when a client reads some raw XML tokens itself
// but also wants to defer to Unmarshal for some elements.

func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
    val := reflect.ValueOf(v)
    if val.Kind() != reflect.Ptr {
        return errors.New("non-pointer passed to Unmarshal")
    }
    return d.unmarshal(val.Elem(), start)
}

It is checking val.Kind() != reflect.Ptr Which means you have to pass the pointer i.e &v.
Its entirely depend on the person who wrote the method or function, so interface{} could be either *ptr or anything but u ve to check that inside your function using reflect.ValueOf(v).Kind() whether the value is a pointer or not and proceeds accordingly.
And little bit about empty interface:
The interface type that specifies zero methods is known as the empty interface:
interface{}
An empty interface may hold values of any type. (Every type implements at least zero methods.)
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.
Another useful discussion: docs

A: DecodeElement() and friends have a formal v interface{} whose type is documented in the Unmarshal() function documentation:

Unmarshal parses the XML-encoded data and stores the result  in the
  value pointed to by v, which must be an arbitrary struct, slice, or
  string.

So to literally answer your question, no, you cannot know without reading the source - if the value you want to pass is a struct proper, you need to indirect.   If it is already a pointer to that struct, you do not.
For example:
type Result struct {
    XMLName xml.Name `xml:"Person"`
    Name    string   `xml:"FullName"`
    Phone   string
    Email   []Email
    Groups  []string `xml:"Group>Value"`
    Address
}

var (
    a Result
    b *Result
    c string
)

xmlDecoder.DecodeElement(&a, startElement)
xmlDecoder.DecodeElement(&c, startElement)

but
xmlDecoder.DecodeElement(b, startElement)