text:
Q: Persistent 3G connection with network manager fails I maintain a persistent 3G connection on a remote device using network manager. However, every so often, the link fails and then does not restart itself. I managed to identify an occurrence of this in my syslog, but honestly I'm not really sure what I'm looking at. It seems that the machine thinks the device has been unplugged, but there's no corresponding log entry for it actually being unplugged.
Would someone mind looking at the below syslog snip and guiding me in the right direction?
Oct 13 22:25:26 tracker pppd[1091]: LCP terminated by peer
Oct 13 22:25:26 tracker pppd[1091]: Connect time 206.7 minutes.
Oct 13 22:25:26 tracker pppd[1091]: Sent 203306 bytes, received 182777 bytes.
Oct 13 22:25:26 tracker pppd[1091]: Modem hangup
Oct 13 22:25:26 tracker pppd[1091]: Connection terminated.
Oct 13 22:25:26 tracker NetworkManager[333]: <info> (ttyUSB1): device state change: 8 -> 9 (reason 13)
Oct 13 22:25:26 tracker NetworkManager[333]: <info> Unmanaged Device found; state CONNECTED forced. (see http://bugs.launchpad.net/bugs/191889)
Oct 13 22:25:26 tracker NetworkManager[333]: <warn> Activation (ttyUSB1) failed.
Oct 13 22:25:26 tracker modem-manager[337]: <info>  (ttyUSB1) closing serial port...
Oct 13 22:25:26 tracker NetworkManager[333]: <info> (ttyUSB1): device state change: 9 -> 3 (reason 0)
Oct 13 22:25:26 tracker NetworkManager[333]: <info> (ttyUSB1): deactivating device (reason: 0).
Oct 13 22:25:26 tracker kernel: [12441.840088] ata1.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x6
Oct 13 22:25:26 tracker kernel: [12441.846744] ata1.00: BMDMA stat 0x66
Oct 13 22:25:26 tracker kernel: [12441.850446] ata1.00: failed command: WRITE DMA
Oct 13 22:25:26 tracker kernel: [12441.855020] ata1.00: cmd ca/00:02:c4:fb:5b/00:00:00:00:00/e0 tag 0 dma 1024 out
Oct 13 22:25:26 tracker kernel: [12441.855024]          res 51/84:00:c4:fb:5b/00:00:00:00:00/e0 Emask 0x30 (host bus error)
Oct 13 22:25:26 tracker kernel: [12441.870623] ata1.00: status: { DRDY ERR }
Oct 13 22:25:26 tracker kernel: [12441.874708] ata1.00: error: { ICRC ABRT }
Oct 13 22:25:26 tracker kernel: [12441.878820] ata1: soft resetting link
Oct 13 22:25:26 tracker modem-manager[337]: <info>  (ttyUSB1) serial port closed
Oct 13 22:25:26 tracker modem-manager[337]: <info>  Modem /org/freedesktop/ModemManager/Modems/0: state changed (connected -> disconnecting)
Oct 13 22:25:26 tracker modem-manager[337]: <info>  Modem /org/freedesktop/ModemManager/Modems/0: state changed (disconnecting -> connected)
Oct 13 22:25:26 tracker NetworkManager[333]: <warn> could not read ppp stats: No such device
Oct 13 22:25:26 tracker pppd[1091]: Exit.
Oct 13 22:25:26 tracker NetworkManager[333]: <info> Unmanaged Device found; state CONNECTED forced. (see http://bugs.launchpad.net/bugs/191889)
Oct 13 22:25:26 tracker NetworkManager[333]:    SCPlugin-Ifupdown: devices removed (path: /sys/devices/virtual/net/ppp0, iface: ppp0)
Oct 13 22:25:26 tracker NetworkManager[333]: <info> disconnect failed: (32) The serial port is not open.
Oct 13 22:25:27 tracker kernel: [12442.048218] ata1.00: configured for UDMA/100
Oct 13 22:25:27 tracker kernel: [12442.048241] ata1: EH complete
Oct 13 22:25:27 tracker kernel: [12442.050941] ata1.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x6
Oct 13 22:25:27 tracker kernel: [12442.057483] ata1.00: BMDMA stat 0x66
Oct 13 22:25:27 tracker kernel: [12442.061153] ata1.00: failed command: WRITE DMA
Oct 13 22:25:27 tracker kernel: [12442.065696] ata1.00: cmd ca/00:02:c4:fb:5b/00:00:00:00:00/e0 tag 0 dma 1024 out
Oct 13 22:25:27 tracker kernel: [12442.065699]          res 51/84:00:c4:fb:5b/00:00:00:00:00/e0 Emask 0x30 (host bus error)
Oct 13 22:25:27 tracker kernel: [12442.081273] ata1.00: status: { DRDY ERR }
Oct 13 22:25:27 tracker kernel: [12442.085366] ata1.00: error: { ICRC ABRT }
Oct 13 22:25:27 tracker kernel: [12442.089488] ata1: soft resetting link
Oct 13 22:25:27 tracker kernel: [12442.260206] ata1.00: configured for UDMA/100
Oct 13 22:25:27 tracker kernel: [12442.260226] ata1: EH complete
Oct 13 22:25:27 tracker kernel: [12442.268296] ata1.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x6
Oct 13 22:25:27 tracker kernel: [12442.274829] ata1.00: BMDMA stat 0x66
Oct 13 22:25:27 tracker kernel: [12442.278480] ata1.00: failed command: WRITE DMA
Oct 13 22:25:27 tracker kernel: [12442.283022] ata1.00: cmd ca/00:02:c4:fb:5b/00:00:00:00:00/e0 tag 0 dma 1024 out
Oct 13 22:25:27 tracker kernel: [12442.283026]          res 51/84:00:c4:fb:5b/00:00:00:00:00/e0 Emask 0x30 (host bus error)
Oct 13 22:25:27 tracker kernel: [12442.298605] ata1.00: status: { DRDY ERR }
Oct 13 22:25:27 tracker kernel: [12442.302693] ata1.00: error: { ICRC ABRT }
Oct 13 22:25:27 tracker kernel: [12442.306763] ata1: soft resetting link
Oct 13 22:25:27 tracker kernel: [12442.476225] ata1.00: configured for UDMA/100
Oct 13 22:25:27 tracker kernel: [12442.476248] ata1: EH complete
Oct 13 22:25:29 tracker NetworkManager[333]: <info> Activation (ttyUSB1) starting connection 'cdma'
Oct 13 22:25:29 tracker NetworkManager[333]: <info> (ttyUSB1): device state change: 3 -> 4 (reason 0)
Oct 13 22:25:29 tracker NetworkManager[333]: <info> Unmanaged Device found; state CONNECTED forced. (see http://bugs.launchpad.net/bugs/191889)
Oct 13 22:25:29 tracker NetworkManager[333]: <info> Activation (ttyUSB1) Stage 1 of 5 (Device Prepare) scheduled...
Oct 13 22:25:29 tracker NetworkManager[333]: <info> Activation (ttyUSB1) Stage 1 of 5 (Device Prepare) started...
Oct 13 22:25:29 tracker NetworkManager[333]: <info> Activation (ttyUSB1) Stage 1 of 5 (Device Prepare) complete.
Oct 13 22:25:30 tracker modem-manager[337]: <info>  Modem /org/freedesktop/ModemManager/Modems/0: state changed (connected -> registered)
Oct 13 22:25:30 tracker modem-manager[337]: <info>  Modem /org/freedesktop/ModemManager/Modems/0: state changed (registered -> connecting)
Oct 13 22:25:30 tracker modem-manager[337]: <info>  Modem /org/freedesktop/ModemManager/Modems/0: state changed (connecting -> registered)
Oct 13 22:25:30 tracker NetworkManager[333]: <warn> CDMA connection failed: (32) Sending command failed: device is not enabled
Oct 13 22:25:30 tracker NetworkManager[333]: <info> (ttyUSB1): device state change: 4 -> 9 (reason 0)
Oct 13 22:25:30 tracker NetworkManager[333]: <info> Unmanaged Device found; state CONNECTED forced. (see http://bugs.launchpad.net/bugs/191889)
Oct 13 22:25:30 tracker NetworkManager[333]: <info> Marking connection 'cdma' invalid.
Oct 13 22:25:30 tracker NetworkManager[333]: <warn> Activation (ttyUSB1) failed.
Oct 13 22:25:30 tracker NetworkManager[333]: <info> (ttyUSB1): device state change: 9 -> 3 (reason 0)
Oct 13 22:25:30 tracker NetworkManager[333]: <info> (ttyUSB1): deactivating device (reason: 0).
Oct 13 22:25:30 tracker NetworkManager[333]: <info> Unmanaged Device found; state CONNECTED forced. (see http://bugs.launchpad.net/bugs/191889)

A: That's unfortunately how some 3G dongles work. If the serial port is closed, they essentially need to be reset back to a poweron mode. This might be possible to do using the "Enable mobile broadband" option in nm-applet by deselecting and selecting it again. Otherwise, it may need to be modeswitched again, in which case it may be simple to disconnect it from the computer and plug it in again (but if you really want to switch it manually, you will need to find out what parameters are passed to usb-modeswitch by udev, via /var/log/usb_modeswitch.log after you enable logging in /etc/usb_modeswitch.conf).
As a possible workaround, you may with to set persist in /etc/ppp/options (which should still get read when establishing the connection). This may help in keeping PPP up and avoid closing off the modem's ports.

A: Could this be related to either of the following:

*

*https://bugs.launchpad.net/ubuntu/+source/linux/+bug/789508

*https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/566812
?

A: Your log starts a few lines too late. I think the important lines are the ones BEFORE
Oct 13 22:25:26 tracker pppd[1091]: LCP terminated by peer
which shows the PPP Daemon telling you that the "Other End" terminated the connection.
I'm also concerned by your ATA.1 disk errors - do you have a backup?


text:
Q: Calling a child function from a parent constant object There is a simple version of my code :
   class Action:
        {
        int updateOK() {
            std::cout << "" << std::endl;
            return 0;
        }
   }
   class Attack:public Action
        {
        int updateOK() {
            std::cout << "att" << std::endl;
            return 0;
        }
   }
   class Def:public Action
        {
        int updateOK() {
            std::cout << "DEf" << std::endl;
            return 0;
        }
    }

    namespace actions
    {
        const Attack light = Attack();
        const Attack meduim = Attack();
        const Attack heavy = Attack();
        const Block block = Block();
        const Block cancelBlock = Block();
        const std::vector<Action> listAction = { light , meduim, heavy , block, cancelBlock };
    }

    Main.cpp :
    for each (Action action in actions::listAction) {
                action.updateOK();
    }

The issue is that it always calls the parent function in the main.
I have tried virtual functions in many ways but I want to find a solution to the problem without casts.
Is it possible ?

A: what you are trying to do is Object slicing:
It happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object

A: If you don't mind casts you need to:

*

*Make parent function virtual for dynamic binding to work

*if you need to use a generic container you will need to use pointers to base class as objects.

Sample edits:
   class Action:
   {
        virtual int updateOK() {
            std::cout << "" << std::endl;
            return 0;
        }
   };

--- the rest of classes ---

    namespace actions
    {
        const Action* light = new Attack();
        const Action* meduim = new Attack();
        const Action* heavy = new Attack();
        const Action* block = new Block();
        const Action* cancelBlock = new Block();
        const std::vector<Action*> listAction { light , meduim, heavy , block, cancelBlock };
    }

    Main.cpp :
    for(Action* action : actions::listAction) {
                action->updateOK();
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the difference between the ring of Integers and the maximal order in a Number field? I have faced the concept of maximal order, while reading one of the books of Goro Shimura, Euler Products and Eisenstein Series.
I am familiar with the concept of ring of integers of a number field. I have read something on the orders and lattices, but its confused me.
So at first, I prefer to fix some definitions to reduce my confusion.
Let $\mathbf{F}$ be a number field, i.e. a finite extension of $\mathbb{Q}$. Let $n$ to be the degree of this extension, i.e. $n:=[\mathbf{F}:\mathbb{Q}]$, also we denote by $\mathfrak{O}_{\mathbf{F}}$ the ring of integers of $\mathbf{F}$.
By an order $\mathfrak{O}$ in $\mathbf{F}$ we mean a subring of $\mathfrak{O}_{\mathbf{F}}$, which has the $\mathbb{Z}$-dimension equal to $n$.
Are all of my definitions are right, Specially the definition of an order?

A: Yes, that is the definition of an order in a number field. And indeed
in a number field, the ring of integers is the unique maximal order.


text:
Q: How can I open Preference screen by long press from a key of sample keyboard? I am a beginner about java and android. I am learning about Sample softkeyboard in Android studio. I want to know how I can open Preference Screen by long press on a key (like Globe key) of sample keyboard instead of going to Setting menu of my phone. Thank you.
Sorry for my bad English.

A: Thats the way you can open the preference screen with a button click
   public void onClick(View v) {
   switch (v.getId()) {
   case R.id.btnPrefs:
      Intent intent = new Intent(PreferenceActivity.this,
      PrefsActivity.class);
      startActivity(intent);
      break;

The long click is something like following
btn.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return true;
        }
    });


text:
Q: Restricted group policy Hi I want to create an OU where i want to put all stored computers, servers and users with doubts. Idea is to restrict these objects (both Computer as well as user) in the domain.
When any floor engineer would take out the system from store, the group policy will not allow the system to be used in domain until he informs the Domain Admins. Once the admin moves the system to right OU, the system is then becomes usable.
Same way, if we have any doubt about any user id, we would move the user id to a restricted OU, where the group policy would restrict the user to get in to domain until domain admin moves the id to correct OU.
How do we do it? I want a group policy/ policies which will do this job for us.

A: For users, why would you move the account when you can simply disable it?  For systems, you should move it to a quarantine OU until it can be rebuilt (which is what you propose).  If these systems are offline they will have to get re-added to the domain if they stay offline too long.  For stored machines, wipe them, rebuild them, and don't add them to the domain until they are needed.

A: For both users and computers simply disable them.
You could move them to another OU for administrative purposes (disabled clients, disabled users) if you like.
As long as you keep them in Active Directory you will be able to reuse, while the objects keep the same ID.


text:
Q: How to show the full query of a view and query in SQL Im having issues with a homework assignment where I need to show the full query That the DBMS actually executes.
The view is
create view MAJOR_CUSTOMER as
select customer_num, customer_name, balance, credit_limit, rep_num
from customer
where credit_limit < 10001;

and the query I used is
select customer_name, customer_num
from major_customer
where balance > credit_limit;

The big thing I do not understand how to do is to select everything shown in the view and the in another query select and show only customer_name and customer_num.

A: Selecting everything in the view can be achieved with
SELECT *
FROM major_customer;

and as for selecting only customer_name and customer_num, your query you have should work, but to select everything, just remove the where clause:
SELECT customer_name, customer_num
FROM major_customer;


text:
Q: Is there css that I can use to stop the text wrapping, it's ok to cut off some data as well I have the table below where the columns are wrapping the data. Is there some css I can use to prevent it from doing that? I don't my if the data gets clipped either. Or what are some other options? I just want to keep all rows consistent and 1 line per row.

    <title></title>

            row1 col1 - The quick brown fox jumps over the lazy dog
            row1 col2 - The quick brown fox jumps over the lazy dog
            row1 col3 - The quick brown fox jumps over the lazy dog
            row1 col4 - The quick brown fox jumps over the lazy dog
            row1 col5 - The quick brown fox jumps over the lazy dog
            row1 col6 - The quick brown fox jumps over the lazy dog
            row1 col7 - The quick brown fox jumps over the lazy dog

            row2 col1
            row2 col2
            row2 col3
            row2 col4
            row2 col5
            row2 col6
            row2 col7

            row3 col1
            row3 col2
            row3 col3
            row3 col4
            row3 col5
            row3 col6
            row3 col7

            row4 col1
            row4 col2
            row4 col3
            row4 col4
            row4 col5
            row4 col6
            row4 col7

A: You can replace the scroll by clip.
Try this:

    table {
        border-spacing: 0px;
    }

    td {
        border: 1px solid #bbb;
        padding: 0.2em;
        white-space: nowrap;
        max-width: 170px !important;
        overflow-x: scroll;
    }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter</title>

        row1 col1 - The quick brown fox jumps over the lazy dog
        row1 col2 - The quick brown fox jumps over the lazy dog
        row1 col3 - The quick brown fox jumps over the lazy dog
        row1 col4 - The quick brown fox jumps over the lazy dog
        row1 col5 - The quick brown fox jumps over the lazy dog
        row1 col6 - The quick brown fox jumps over the lazy dog
        row1 col7 - The quick brown fox jumps over the lazy dog

        row2 col1
        row2 col2
        row2 col3
        row2 col4
        row2 col5
        row2 col6
        row2 col7

        row3 col1
        row3 col2
        row3 col3
        row3 col4
        row3 col5
        row3 col6
        row3 col7

        row4 col1
        row4 col2
        row4 col3
        row4 col4
        row4 col5
        row4 col6
        row4 col7

A:

td {
    white-space: nowrap;
}
.x{
overflow:hidden;
white-space: nowrap;
}

#y{
width:750px;
table-layout:fixed;
}

    <title></title>

            row1 col1 - The quick brown fox jumps over the lazy dog
            row1 col2 - The quick brown fox jumps over the lazy dog
            row1 col3 - The quick brown fox jumps over the lazy dog
            row1 col4 - The quick brown fox jumps over the lazy dog
            row1 col5 - The quick brown fox jumps over the lazy dog
            row1 col6 - The quick brown fox jumps over the lazy dog
            row1 col7 - The quick brown fox jumps over the lazy dog

            row2 col1
            row2 col2
            row2 col3
            row2 col4
            row2 col5
            row2 col6
            row2 col7

            row3 col1
            row3 col2
            row3 col3
            row3 col4
            row3 col5
            row3 col6
            row3 col7

            row4 col1
            row4 col2
            row4 col3
            row4 col4
            row4 col5
            row4 col6
            row4 col7

            row1 col1 - The quick brown fox jumps over the lazy dog
            row1 col2 - The quick brown fox jumps over the lazy dog
            row1 col3 - The quick brown fox jumps over the lazy dog
            row1 col4 - The quick brown fox jumps over the lazy dog
            row1 col5 - The quick brown fox jumps over the lazy dog
            row1 col6 - The quick brown fox jumps over the lazy dog
            row1 col7 - The quick brown fox jumps over the lazy dog

            row2 col1
            row2 col2
            row2 col4
            row2 col5
            row2 col6
            row2 col7

            row3 col1
            row3 col2
            row3 col3
            row3 col4
            row3 col5
            row3 col6
            row3 col7

            row4 col1
            row4 col2
            row4 col3
            row4 col4
            row4 col5
            row4 col6
            row4 col7

A: Add white-space: nowrap; overflow: hidden; text-overflow: ellipsis; to all td elements.
td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Or create a separate CSS class that you can use where it's needed.
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

row1 col1 - The quick brown fox jumps over the lazy dog

https://jsfiddle.net/wvq64zfu/

A: use the whitespace attribute and set it's value to no-wrap as below
    td {
    white-space: nowrap;
}


text:
Q: Avfoundation create mini clips from recording i was wondering how would i be able to create mini videos every certain amount of time from my recording without stopping my recording? i tried to look for an equivalent of AvAssetImageGenerator for videos an example would be nice.

A: The easiest way is to use two AVAssetWriters and set up the next writer while the current one is recording, then stop after x time and swap the writers.  You should be able to swap the writers without dropping any frames.
Edit:
How to do AVAssetWriter "juggling"
Step 1: Create instance objects for the writers and pixelbuffer adaptors (and you'll want file names for these files as well that you know)
AVAssetWriter*                        mWriter[2];
AVAssetWriterInputPixelBufferAdaptor* mPBAdaptor[2];
NSString*                             mOutFile[2];
int                                   mCurrentWriter, mFrameCount, mTargetFrameCount;

Step 2: Create a method for setting up a writer (since you'll be doing this over and over again)
-(int) setupWriter: (int) writer
{
NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];

NSDictionary* writerSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt: mVideoWidth], AVVideoWidthKey, [NSNumber numberWithInt: mVideoHeight], AVVideoHeightKey, nil];
NSDictionary* pbSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:mVivdeoWidth],kCVPixelBufferWidthKey,
                        [NSNumber numberWithInt:mVideoHeight], kCVPixelBufferHeightKey,
                        [NSNumber numberWithInt:0],kCVPixelBufferExtendedPixelsLeftKey,
                        [NSNumber numberWithInt:0],kCVPixelBufferExtendedPixelsRightKey,
                        [NSNumber numberWithInt:0],kCVPixelBufferExtendedPixelsTopKey,
                        [NSNumber numberWithInt:0],kCVPixelBufferExtendedPixelsBottomKey,
                        [NSNumber numberWithInt:mVideoWidth],kCVPixelBufferBytesPerRowAlignmentKey,
                        [NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey, nil];

AVAssetWriterInput* writerInput = [AVAssetWriterInput assetWriterWithMediaType: AVMediaTypeVideo outputSettings: writerSettings];
// Create an audio input here if you want...
mWriter[writer] = [[AVAssetWriter alloc] initWithURL: [NSURL fileURLWithPath:mOutfile[writer]] fileType: AVFileTypeMPEG4 error:nil];

mPBAdaptor[writer] = [[AVAssetWriterInputPixelBufferAdaptor alloc] initWithAssetWriterInput: writerInput sourcePixelBufferAttributes: pbSettings];

[mWriter[writer] addInput: writerInput];
// Add your audio input here if you want it
[p release];
}

Step 3: Gotta tear these things down!
- (void) tearDownWriter: (int) writer
{
if(mWriter[writer]) {

   if(mWriter[writer].status == 1) [mWriter[writer] finishWriting]; // This will complete the movie.
   [mWriter[writer] release]; mWriter[writer] = nil;
   [mPBAdaptor[writer] release]; mPBAdaptor[writer] = nil;
}

}

Step 4:  Swap!  Tear down the current writer and recreate it asynchronously while the other writer is writing.
- (void) swapWriters
{
 NSAutoreleasePool * p = [[NSAutoreleasePool alloc] init];
 if(++mFrameCount > mCurrentTargetFrameCount)
 {
    mFrameCount = 0;
    int c, n;
    c = mCurrentWriter^1;
    n = mCurrentWriter;  // swap.

    [self tearDownWriter:n];
    __block VideoCaptureClass* bSelf = self;
    dispatch_async(dispatch_get_global_queue(0,0), ^{
      [bSelf setupWriter:n];
              CMTime time;
    time.value = 0;
    time.timescale = 15; // or whatever the correct timescale for your movie is
    time.epoch = 0;
    time.flags = kCMTimeFlags_Valid;
    [bSelf->mWriter[n] startWriting];
    [bSelf->mWriter[n] startSessionAtSourceTime:time];
    });
    mCurrentWriter = c;
 }

[p release];
}

Note: When starting up you will have to create and start both writers.
Step 5: Capturing output
   - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
   // This method will only work with video; you'll have to check for audio if you're using that.
   CMTime time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer); // Note: you may have to create your own PTS.

   CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

   [mPBAdaptor[mCurrentWriter] appendPixelBuffer:pixelBuffer withPresentationTime: time];

   [self swapBuffers];
  }

You can probably skip the pixel buffer adaptor if you don't need it.  This should give you an approximate idea of how to do what you want to do.  mTargetFrameCount represents how many frames you want the current video to be in length.  Audio will probably take additional consideration, you may want to base your length off your audio stream instead of the video stream if you are using audio.


text:
Q: Add images from picasso to Gridview I am working on a project in which I get images URL dynamically from database. I previous created a gallery in LinearLayout which is fine. But I want to create a Gridview in which i can add the photos in same way. Can anyone give me hint or idea of from where to start. I have also created a GridView fragment (I want gridview in fragment) and ImageAdapter class according to tutorial here.

http://developer.android.com/guide/topics/ui/layout/gridview.html
This tutorial is for loading images from local resources which I don't need.
Also I have tried searching online but couldn't find an appropriate way. Any help would be appreciated. Thank You!.
Edit:
ImageAdapter.java
package com.example.imran.myapp;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

/**
 * Created by imran on 28-Mar-16.
 */
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    String url = "https://www.google.com/images/srpr/logo11w.png";
    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso.with(this.mContext).load(url).resize(100, 100).into(imageView);
        Picasso.with(this.mContext).setLoggingEnabled(true);

        return imageView;
    }

    // references to our images
    public Integer[] mThumbIds = {
          /*R.drawable.title_background,
            R.drawable.title_background,
            R.drawable.title_background,  R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
            */
    };
}

gridgallery.java
package com.example.imran.myapp;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class gridgallery extends Fragment {

    public gridgallery() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gridgallery, null);
        Myserver myserver = new Myserver();

        postStringRequest(myserver.url+"/api/albums/getalbums.php",view);
        return view;

        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_gridgallery, container, false);
    }

    public View postStringRequest(final String url,final View view){
        //final View view = inflater.inflate(R.layout.fragment_gallery, null);
        final TextView t = (TextView)view.findViewById(R.id.main_msg_gallery);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getContext());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string

                       // LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.fragment_gallery);
                        //GridView gridView = (GridView)view.findViewById(R.id.fragment_gridgallery);
                        //gridView.setAdapter(new ImageAdapter(getContext()));
                        try {
                            JSONArray jsonObj = new JSONArray(response);
                            Myserver myserver = new Myserver();
                            for (int i=0;i<jsonObj.length();i++){
                                JSONObject c = jsonObj.getJSONObject(i);

                                //ImageView albumpic = new ImageView(getContext());
                                //Picasso.with(getContext()).load(myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail")).centerCrop().resize(200,200).into(albumpic);
                                //linearLayout.addView(albumpic);
                                // gridView.addView(albumpic);

                                GridView gridView = (GridView) view.findViewById(R.id.fragment_gridgallery);
                                ImageAdapter myadap = new ImageAdapter(getContext());
                                myadap.url = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
                                gridView.setAdapter(myadap);

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                t.setText("Server error - Unable to reach server");
                Toast.makeText(getContext(), "Unable to reach server", Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getalbum", "getalbum");
                return params;
            }
        };
        queue.add(stringRequest);
        return view;
    }

}

A: This is one that I recently  worked on. There are number of ways you can do this, but you will always have to extend/import ListAdapter, which is base for all of those types for listViews. Here are the ways:

*

*Create an adapter like you'd always do when making ListView, or list-array, that extends ListAdapter. (For me, I called it GroupTileAdapater.java)

*You will have to create its own view for the tile, which is just like you'd create for the each list. For me, I just created a layout and fills up the entire view with imageview, and you can customize whatever you want.(It was called media_tile.xml inside res/layout)

*Then you'd specify the image inside the adapter, by finding the corresponding id that you instantiated in your tile image view. (By calling Picasso's method, which you can take a look at the question I posted recently, Load image through picasso)

To be more specific, you'd override 4 methods from listAdapter, getCount, getItem, getItemId, getView, and when setting the adapter, you'd pass in your image lists to constructor, and inside getView is where you'd show the images.

*Now, you'd just set adapter to whatever fragment/activity you are in, with whatever layout you have initialized your gridview.

And I don't know what your URL type is, but if it starts with file/content, take a look at the following, contentUri:show image, and incorporate with picasso. There are youtube videos out there that can help you out as well to understand more about listAdapter. Hope it helps!

A: Thanks guys for your help, I finally figured it out.
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c, String urls[]) {
        mContext = c;
        mThumbIds = urls;
        //myurls = urls;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return position;
        //return 0;
    }

    public String getURL(int position){
        return mThumbIds[position];
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(20, 20, 20, 20);
        } else {
            imageView = (ImageView) convertView;
        }

       // imageView.setImageResource(mThumbIds[position]);

        Picasso.with(mContext)
                .load(mThumbIds[position])
                .into(imageView);
        return imageView;
    }

    //private ArrayList<String> myurls = new ArrayList<String>();

    // references to our images
    private String[] mThumbIds = {

    };
}

gridgallery.java (fragment)
package com.example.imran.myapp;

    public class gridgallery extends Fragment {

    public gridgallery() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gridgallery, null);
        Myserver myserver = new Myserver();
        postStringRequest(myserver.url + "/api/albums/getalbums.php", view);
        return view;
    }

    public View postStringRequest(final String url,final View view){
        //final View view = inflater.inflate(R.layout.fragment_gallery, null);
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getContext());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
                        ArrayList<String> urls2 = new ArrayList<String>();
                        try {
                            JSONArray jsonObj = new JSONArray(response);
                            Myserver myserver = new Myserver();
                            for (int i=0;i<jsonObj.length();i++){
                                JSONObject c = jsonObj.getJSONObject(i);
                                String imgurl = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
                                urls2.add(imgurl);
                            }
                            String myabc[] = urls2.toArray(new String[urls2.size()]);
                            final ImageAdapter myadapter = new ImageAdapter(getContext(),myabc);
                            gv.setAdapter(myadapter);
                            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Toast.makeText(getContext(),myadapter.getURL(position),Toast.LENGTH_LONG).show();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Unable to reach server", Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getalbum", "getalbum");
                return params;
            }
        };
        queue.add(stringRequest);
        return view;
    }

}


text:
Q: In Button strike is getting fine, but unstrike not possible On a UIButton click a pair of button will strike and click another button the strike will not unstriken is the problem , strike function is working fine and unstrike in not getting....
code: unstrike
    func updAvaTime() {

    upAvailableTime(sender:time805Btn)
    upAvailableTime(sender:time830Btn)
    upAvailableTime(sender:time905Btn)
    upAvailableTime(sender:time930Btn)
    upAvailableTime(sender:time1005Btn)
    upAvailableTime(sender:time1030Btn)
    upAvailableTime(sender:time115Btn)
    upAvailableTime(sender:time1130Btn)
    upAvailableTime(sender:time125Btn)
    upAvailableTime(sender:time1230Btn)
    upAvailableTime(sender:time105Btn)
    upAvailableTime(sender:time130Btn)
    upAvailableTime(sender:time205Btn)
    upAvailableTime(sender:time230Btn)
    upAvailableTime(sender:time305Btn)
    upAvailableTime(sender:time330Btn)
    upAvailableTime(sender:time405Btn)
    upAvailableTime(sender:time430Btn)
    upAvailableTime(sender:time505Btn)
    upAvailableTime(sender:time530Btn)
    upAvailableTime(sender:time605Btn)
    upAvailableTime(sender:time630Btn)
    upAvailableTime(sender:time705Btn)
    upAvailableTime(sender:time730Btn)

}
func upAvailableTime(sender: UIButton) {
    let currentTime = sender.currentTitle//(for: .normal)!
    let attrString: NSMutableAttributedString = NSMutableAttributedString(string: currentTime!)
    attrString.removeAttribute(NSAttributedString.Key.strikethroughStyle , range:NSMakeRange(0, attrString.length))

}

A: Set strike and unstrike property for UIButton
let attributesUnstrike = [NSAttributedString.Key.strikethroughStyle : 0]
let titleUnselected = NSAttributedString(string: "YOUR STRING", attributes: attributesUnstrike)

//Set strike for selected state
let attributesStrike = [NSAttributedString.Key.strikethroughStyle : 1]
let titleSelected = NSAttributedString(string: "YOUR STRING", attributes: attributesStrike)

btn.setAttributedTitle(titleUnselected, for: .normal)
btn.setAttributedTitle(titleSelected, for: .selected)

@IBAction func reloadtable(sender:UIButton){
    sender.isSelected = !sender.isSelected
    //Automatically change Button state automatically based on curent state
}

Update:
time805Btn.isSelected = true // To Strike
time805Btn.isSelected = false // To Unstrike

Note: Make sure your UIButton type should be custom.


text:
Q: Can an issue be blamed for something? Can I say:

Many issues can be blamed for this ...

A: Yes, you can. Some examples:

*

*Identity issues can be blamed for adolescent depression…

*Mechanical stability issues were blamed for the collapse of the structure…


text:
Q: How to listen for Telegram Bot errors? (Google App Script + Webhooks) I have developed a fully functional Telegram Bot with Google App Script that uses Webhooks to read and write into a Google Spreadsheet.
Although the bot is stable, sometimes it crashes due to specific user interaction like pressing buttons too fast or making the bot send too many messages in a short amount of time.
The Error Handling section of the Telegram API mentions that errors are returned in rpc_error constructors, but there is no reference to any method that can be used to listen for any error that may occur.
I want to handle these errors but the only way I am aware is to listen for errors on each API request.
Here is an example of how I am handling an error right now:
function editKeyboardMessage(buttonArray) {
  var id = PropertiesService.getUserProperties().getProperty("inline_form_chat_id");
  var message_id = PropertiesService.getUserProperties().getProperty("inline_form_message_id");
  var keyboardMarkup = {"inline_keyboard": buttonArray};
  var data = {
    method: "post",
    payload: {
       method: "editMessageReplyMarkup",
       chat_id: String(id),
       message_id: Number(message_id),
       parse_mode: "HTML",
       reply_markup: JSON.stringify(keyboardMarkup)
     }
   };
  var response = UrlFetchApp.fetch(url + "/", data)
  var responseCode = response.getResponseCode()
  handleErrors(responseCode)
}

However, it seems unpractical to do this on all requests types and it doesn't allow complete error handling (like the ones that happen independently of requests, such as message flooding).
The expected outcome would be to properly handle all incoming errors in just one place.
Is there a way to listen for all bot errors with something similar to the doPost(e) function that is used to listen for updates?

A: Since we are currently talking on Telegram - it might be helpful for others.
The conversation started at https://t.me/BotTalk/105298

tl;dr you need to do error handling on your end. If you don't use a library, try checking each response from Telegram after sending out a request for errors. If there are errors, handle them accordingly.


text:
Q: @Basic(optional = false) vs @Column(nullable = false) in JPA What's the difference between @Basic(optional = false) and @Column(nullable = false) in JPA persistence?

A: So I tried the @Basic(optional=false) annotation using JPA 2.1 (EclipseLink) and it turns out the annotation is ignored in actual usage (at least for a String field). (e.g. entityManager.persist calls).
So I went to the specification and read up about it.
Here is what the spec has to say:
http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/

Basic(optional): Whether the value of the field or property may be
  null. This is a hint and is disregarded for primitive types; it may be
  used in schema generation.

So I think this sentence explains the real use case for Basic(optional) it is used in schema generation. (That is: when you generate CREATE TABLE SQL from Java Entity classes. This is something Hibernate can do for example.)

A: Gordon Yorke (EclipseLink Architecture Committee Member, TopLink Core Technical Lead, JPA 2.0 Expert Group Member) wrote a good answer on this topic so instead of paraphrasing him, I'll quote his answer:

The difference between optional and
  nullable is the scope at which they
  are evaluated. The definition of
  'optional' talks about property and
  field values and suggests that this
  feature should be evaluated within the
  runtime. 'nullable' is only in
  reference to database columns.
If an implementation chooses to
  implement optional then those
  properties should be evaluated in
  memory by the Persistence Provider and
  an exception raised before SQL is sent
  to the database otherwise when using
  'updatable=false' 'optional'
  violations would never be reported.


text:
Q: Usage example of boost::condition::timed_wait Does someone have an example of how to most easily use boost::condition::timed_wait? There are some threads on the topic here, here and here, but none feature a working example. And boost doc is as usual quite sparse.

A: Actually, I finally found a link with full example here. With a bit of adapting, this seems to be the call.
boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(35000);
boost::mutex::scoped_lock lock(the_mutex);
if(the_condition_variable.timed_wait(lock,timeout,&CondFulfilled))
{
    <cond fulfilled code>
}
else
{
    <timeout code>
}
bool CondFulfilled() { ... }


text:
Q: Junit VerificationModeFactory.times() vs mockito.times() What is the difference between VerificationModeFactory.times() and mockito.times()?

A: I thought it would be faster to ask rather than go check by myself :) I was lazy and wrong so I did the check by myself and here is the answer. It is the same thing, Mockito.Times() is internally calling the VerificationModeFactory.times()
From Mockito.class
/**
 * Allows verifying exact number of invocations. E.g:
 * <pre>
 *   verify(mock, times(2)).someMethod("some arg");
 * </pre>
 *
 * See examples in javadoc for {@link Mockito} class
 *
 * @param wantedNumberOfInvocations wanted number of invocations
 *
 * @return verification mode
 */
public static VerificationMode times(int wantedNumberOfInvocations) {
    return VerificationModeFactory.times(wantedNumberOfInvocations);
}


text:
Q: $.ajax() methods data I have some div tags which onchange I want to insert the new value into my database.
As people suggest, I'm using $.ajax POST to insert. Since I'm new to JQuery and Ajax, I don't what actually that data and msg in $.ajax()..Please explain how to insert my value into a database asynchronously (on the Fly)
            $(".div"+increment).change(function(){
                   $.ajax({
                     type: "POST",
                     url: "./server",
                     data: "name=John&location=Boston",
                     success: function(msg){
                     alert( "Data Saved: " + msg);
                          }
                })

               });

A: The data attribute should be an object
            $(".div"+increment).change(function(){
               $.ajax({
                 type: "POST",
                 url: "./server",
                 data: {name:"John", location:"Boston"},
                 success: function(msg){
                 alert( "Data Saved: " + msg);
                      }
            })

           });

On the server-side simply retrieve post parameters as usual.
For example, in php you would do something like $_POST("name") and $_POST("location").
Response generated by PHP would appear as msg. So you can just echo "Save operation succeeded" in your PHP script after executing your insert.

A: You might consider using $.post instead. It is easier to handle. The drawback is that it doesn't offer error notification.

A: When you say "insert my value to database asynchronously....(on the Fly)", I hope you mean "insert into the database, period".
The POST request (either by $.ajax() or by $.post() ) can only send your data from the client to you server.
You will need to write server side code to do the insertion.
Lets say you have a script called "do-insertion.php" on your server that can insert data into a database, if the POST variables "name" and "location" are submitted to it.
So you would write (I guess you already know this):
$.post( "do-insertion.php",
{"name":"John", "location":"SF"},
function(data){alert("got response="+data);} );

The important thing is what you write on the server side code. I assume PHP, so you would use the mysql API for php and insert your data into your database.
ofcourse, you can read the submited data as
$name=$_POST['name'];
$location=$_POST['location'];
This applies only to PHP; other languages will have other methods to do everything.

By the way, did you mean anything special by the "asynchronously .... (on the fly)" in your question?


text:
Q: Serverless Typescript plugin packs all my lambda functions into one zip archive Below is my serverless.yml

service: serverless-typescript-example
provider:
  name: aws

package:
  individually: true

plugins:
  - serverless-plugin-typescript

functions:
  hello1:
    handler: hello1/src/index.handler
  hello2:
    handler: hello/src/index.handler

and my folder structure looks like below
hello1
 --index.ts
 --package.json
hello2
 --index.ts
 --package.json
package.json
serverless.yml

when I run sls package it creates 2 zip archives in .serverless folder with names hello1.zip and hello2.zip. Upon unzipping both folders have identitical contents i.e hello1 ande hello2 with node_modules.
Is there any option to resolve this and can we place the .zip file in the respective function folder ,i mean hello1.zip in hello1 and hello2.zip in hello2

A: i haven't used the serverless-plugin-typescript, but we use serverless-webpack and it does a pretty neat job. It reduced the lambda size a lot since it uses webpack to bundle.
there is also a serverless create template that uses the serverless-webpack plugin.
serverless create --template aws-nodejs-typescript

the zip files are placed by default in the .serverless folder. You can use the command below specify a destination folder. I don't think there is a way to define different destinations for each entry point.
serverless package --package my-artifacts


text:
Q: .isVisible() method not working for JFrame I've created a GUI, I included the 2 methods I'll be needing below. As you can see when I click the button the Menu's visibility is set to false. I want to do something on the other program but ONLY when the button has been clicked, and the frame has disappeared. For demonstration purposes I made my program keep spitting out millions of lines of "GUI Visible", until the Menu is set to invisible, where it should change to spitting out "GUI hiding".
public class Menu extends javax.swing.JFrame {
public Menu() {
    initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        this.WriteToText();
    } catch (Exception ex) {
        Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
    }
}

 public void WriteToText() throws Exception
 {

     FileWriter fw = new FileWriter("playerdetails.txt");
 BufferedWriter bw = new BufferedWriter(fw);
 bw.write(playername.getText());
     System.out.println("Printed");
     clicked = "1";
     this.setVisible(false); //HERE

This is the program where I am running the menu from. It would appear as though the "hm.isVisible();" method I used isn't working. When I run it, the program says that the GUI is hiding regardless of whether it is hiding or not. By using S.o.pl's I established that the method always returns a value of false. How can I get it to return the right value??
package monster.defense;
import java.io.*;
public class MonsterDefense{
public static void main(String args[]) throws Exception {

    Menu hm = new Menu();
    hm.setvisible(true);
    BufferedReader pdetails = new BufferedReader(new FileReader("playerdetails.txt"));
    BufferedReader inKb = new BufferedReader(new InputStreamReader (System.in));

    int yum = 1;
    while(yum == 1)
    {
        if(hm.isVisible()==true) //HERE
        {
            System.out.println("GUI visible");
        }
        else
        {
            System.out.println("GUI hiding");
        }
    }
    String cat = inKb.readLine();
    System.out.println("here"+hm.getPName());

  }
}

A: create a custom boolean inside the Main class. if you are not sure with isVisible()
class Main{

boolean opened = false;

public void setOpen(boolean open){
this.opened = open;
}

public Boolean isOpened(){
return opened;
}

}

in the logic that you have in main method can now check
if(hm.isOpened()){
}

when you are opening the frame call the method
hm.setOpen(true); along with the `setVisible(true);`

A: Check the tutorial on Swing Component listeners and move your logic to the componentHidden() and componentShow() listener methods.
Edit: As @MadProgrammer noted, WindowListener would be appropriate if you want to intercept window closing/opening events. It also has a tutorial.
You'd probably want to check the windowActivated() / windowDeactivated() methods.

A: So, once I made you code runnable, it run just fine for me.
However, it's the wrong approach, instead of using a while loop, which could potentially block the Event Dispatching Thread, making it impossible to close the window (or interact with your UI) at all, you should be using a modal dialog instead, for example...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                Menu menu = new Menu();
                JOptionPane.showMessageDialog(null, menu, "PlayerName", JOptionPane.PLAIN_MESSAGE);

                String playerName = menu.getPlayerName();

                // Now you can write it to the file if you need

            }
        });
    }

    public class Menu extends JPanel {

        private JTextField playerName;

        public Menu() {
            setLayout(new GridBagLayout());
            playerName = new JTextField(10);
            add(new JLabel("Player name: "));
            add(playerName);
        }

        public String getPlayerName() {
            return playerName.getText();
        }
    }

}

Have a look at How to Make Dialogs for more details


text:
Q: ASP.NET MVC 2: Breaking changes What will be broken after migrate to MVC 2?

I wonder what breaking changes will come with MVC 2, so how traumatic will be the migration?
How much smooth have been your experience migrating?

A: The release notes have the breaking changes: ASP.NET MVC 2 RTM Release Notes
I had no problem upgrading, just some issue with registering Castle Windsor IoC container... only had to change the signature though:
Migrate from .NET MVC 1 to MVC 2 RC


text:
Q: Regular Expression for Email in Spring Roo I am using Spring Roo and am having difficulty implementing the regular expression for the email field so that only properly formatted emails can be implemented into the field. When I run Tomcat and test the application using a local host I get a message saying

Enter a valid email

and this message appears everytime a "." is entered or if there is a space anywhere.
The current regex I am using is:
"^[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})$"

Can anyone help me figure out what I am doing wrong? Is it an issue with Spring Roo or am I just using the wrong regex?

A: Try to use regex written and debugged by somebody else.
Here are the examples:
Using a regular expression to validate an email address
http://www.regular-expressions.info/email.html
http://commons.apache.org/proper/commons-validator/


text:
Q: Invoke method with Reflection from an exe on a network drive I am trying to invoke a method using Reflection within an exe on a network drive, but I get the following exception.

[2013-07-12 11:58:54 AM] The following error occured :Exception has
  been thrown by the target of an invocation. Inner Exception
  :System.Security.SecurityException: Request for the permission of type
  'System.Security.Permissions.FileIOPermission, mscorlib,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
  failed.    at System.Security.CodeAccessSecurityEngine.Check(Object
  demand, StackCrawlMark& stackMark, Boolean isPermSet)    at
  System.Security.CodeAccessPermission.Demand()    at
  System.IO.FileStream.Init(String path, FileMode mode, FileAccess
  access, Int32 rights, Boolean useRights, FileShare share, Int32
  bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
  msgPath, Boolean bFromProxy)    at System.IO.FileStream..ctor(String
  path, FileMode mode, FileAccess access, FileShare share, Int32
  bufferSize, FileOptions options)    at
  System.IO.StreamWriter.CreateFile(String path, Boolean append)    at
  System.IO.StreamWriter..ctor(String path, Boolean append, Encoding
  encoding, Int32 bufferSize)    at System.IO.StreamWriter..ctor(String
  path, Boolean append, Encoding encoding)    at
  System.IO.File.AppendAllText(String path, String contents, Encoding
  encoding)    at System.IO.File.AppendAllText(String path, String
  contents)    at ccc.ControllerBO.ExecuteTest()

I have read up on the Security Settings, but I do not want to install the invoker EXE and cannot find a solution.
What can I do to overcome this?

A: You could copy the executable to a place local to your own assembly and invoke it from there.

A: You can create evidence instance and pass it to LoadForm method, like this:
#if NET35
            var evidence = new System.Security.Policy.Evidence();
            evidence.AddHost(new System.Security.Policy.Url(assemblyPath));
            evidence.AddHost(new System.Security.Policy.Zone(System.Security.SecurityZone.MyComputer));
            Assembly assembly = Assembly.LoadFrom(assemblyPath, evidence);
#elif NET40
            var evidence = new System.Security.Policy.Evidence();
            evidence.AddHostEvidence(new System.Security.Policy.Url(assemblyPath));
            evidence.AddHostEvidence(new System.Security.Policy.Zone(System.Security.SecurityZone.MyComputer));
            Assembly assembly = Assembly.LoadFrom(assemblyPath);
#endif

where assemblyPath - is a full path to file with an assembly (for e.g. on network drive).


text:
Q: Proving that $\sum (-1)^{n+1} n^{-z}$ defines an analytic function in $Re z>0$ I want to show that the series $\sum_{n=1}^\infty (-1)^{n+1} n^{-z}$ converges to an analytic function for $\Re z>0$.
For $\Re z>1$ the terms are dominated by $n^{-x}$ so that we have absolute and uniform convergence on compact sets, and by Weierstrass' theorem the sum is analytic there. For $\Re z \leq 1$ however I can't show absolute convergence. I tried splitting into real and imaginary parts:
$$\sum_{n=1}^\infty (-1)^{n+1} n^{-z}=\sum_{n=1}^\infty (-1)^{n+1} n^{-x}\cos(-y \ln n)+i\sum_{n=1}^\infty (-1)^{n+1} n^{-x}\sin(-y \ln n),$$
and showing convergence for both using Leibniz's test (or even the more general Dirichlet's test) without success.
I'd love to have any hints about how to do this right.

A: Hints:
$$\frac1{n^s}-\frac1{(n+1)^s}=s\int\limits_n^{n+1}\frac{dx}{x^{s+1}}$$
and now, putting $\,s=\sigma+it\;,\;\;\sigma\,,\,t\in\Bbb R\,$  and taking into account that $\,\sigma>0\,$:
$$\left|\;\int\limits_n^{n+1}\frac{dx}{x^{s+1}}\;\right|\le\int\limits_n^{n+1}\frac{dx}{\left|x^{s+1}\right|}=\int\limits_n^{n+1}\frac{dx}{x^{\sigma+1}}=\left.-\frac1\sigma x^{-\sigma}\right|_n^{n+1}=-\frac1\sigma\left(\frac1{(n+1)^\sigma}-\frac1{n^\sigma}\right)$$
and now observe that
$$-\frac1\sigma\left(\frac1{(n+1)^\sigma}-\frac1{n^\sigma}\right)<\frac1{n^{\sigma+1}}\iff\left[1-\left(\frac n{n+1}\right)^\sigma\right]<1\iff\left(\frac n{n+1}\right)^\sigma>0$$
and now we just apply the series test...

A: Here's a direct proof of the statement using Cauchy's criterion given in this file.
Let $K_{\epsilon,M} = \{s\in\Bbb C: Re(s)\geq\epsilon,|s|\leq M\}$ be a compact subset of $Re(s)>0$ for $0<\epsilon\ll 1$ and $1\ll M$. Then, $|n^{-s}|\leq n^{-\epsilon}$ for all $s\in K_{\epsilon,M}$. Let $S_n= \sum_{k=1}^n(-1)^{k+1}$ which is $1$ or $-1$. Choose $0<n_1<n_2\in\Bbb N$.
\begin{align*}
\left|\sum_{n_1+1}^{n_2}{(-1)^{n+1}\over n^s}\right| & = \left|\sum_{n=n_1+1}^{n_2}{1\over n^s}(S_n-S_{n-1})\right|\\
& = \left|\sum_{n=n_1+1}^{n_2}\left({1\over n^s}-{1\over(n+1)^s}\right)S_n+{S_{n_2}\over(n_2+1)^s}-{S_{n_1}\over(n_1+1)^s}\right|\\
&\leq{1\over(n_1+1)^\epsilon}+{1\over(n_2+1)^\epsilon}+\sum_{n = n_1+1}^{n_2}\left|{1\over n^s}-{1\over(n+1)^s}\right|\\
& \leq {1\over n_1^\epsilon}+{1\over n_2^{\epsilon}}+\sum_{n=n_1+1}^{n_2}\left|\int_n^{n+1}{-s\over x^{s+1}}\ dx\right|\\
& \leq {2\over n_1^{\epsilon}}+\sum_{n=n_1+1}^{n_2}{M\over n^{\epsilon+1}}\\
& \leq {2\over n_1^{\epsilon}}+M\int_{n_1}^{n_2}{1\over x^{1+\epsilon}}\ dx\\
& \leq {2\over n_1^\epsilon}+{M\over\epsilon n_1^{\epsilon}}\to 0,\quad \epsilon\to 0.\\
\end{align*}
Hence by Cauchy criterion, the series converges uniformly on a compact subset $K_{\epsilon,M}$ and as $\epsilon,M$ are arbitrary, we conclude the given series defines a holomorphic function on $Re(s)>0$.


text:
Q: Image url can't get through if statement I post an image url to a php script. In this php script I get the image url and check what the extension is and if this extension matches a couple of extensions or not:
        $ext1 = pathinfo($_POST['form_pic'], PATHINFO_EXTENSION);
        $ext = strtolower($ext1);

        if($ext != 'jpg' || $ext != 'jpeg' || $ext != 'png' || $ext != 'gif') {
            echo $ext; echo "wrong";
        }else{
            echo "a correct extension";
        }

But even when I a post an url like: http://www.test.com/picture.jpg and he gets the extension, in this case jpg, he still goes through the if statement, saying the extension is not equal to the one mentioned in the if statement.
I don't know what I am doing wrong?

A: You want to use and in this logic, not or.
if($ext != 'jpg' && $ext != 'jpeg' && $ext != 'png' && $ext != 'gif')

Currently, your if statement reads "If the extension isn't jpg or isn't png or isn't gif", which will always match, even if the extension is permitted (i.e. "jpg"), because "jpg" != "png".
You want and because it'll make the if statement read "If the extension isn't jpg and isn't png and isn't gif", then it's invalid.

A: You could also do
if(in_array($ext,array('gif','jpg','jpeg','png')){
//good
}else{
//bad
}

A: Try switching the logic:
if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
    echo "a correct extension";
}else{
    echo $ext; echo "wrong";
}

Using OR, the condition will be triggered if any of the criteria are met, and since a .jpg extension won't match a .png one, it'll give you the Wrong message.

A: Your code is almost right but you have to use correct operator which is && in this case.
Please try this:
$ext1 = pathinfo($_POST['form_pic'], PATHINFO_EXTENSION);
$ext = strtolower($ext1);

   if($ext != 'jpg' && $ext != 'jpeg' && $ext != 'png' && $ext != 'gif') {
        echo $ext; echo "wrong";
   } else {
        echo "A correct extension";
   }

When you a use a sequence of negative statements there always should be used operator &&.
There are a lot of ways to do what you want but if you want to keep your code as it is just change || to && and you will be fine.
Please read more about Logical Operators in PHP.


text:
Q: How to insert multiple choices in to the database and display My models is:
class LabRequest(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    lab_test = models.ManyToManyField(Lab)

My Form
class LabRequestModelForm(forms.ModelForm):
    class Meta:
        model = LabRequest
        fields = ['ticket', 'lab_test']
        widgets = {
            'lab_test': forms.CheckboxSelectMultiple,
        }

My view
def LabRequestToGenerateView(request):
    if form.is_valid():
        obj = form.save(commit=False)
        obj.created_by = request.user.id
        obj.save()

    return render(request, 'dashboard/laboratory_request.html', {'form': form})

My Template
<form action="." method="POST">
    {% csrf_token %}
    {{ form.as_p }}

        <button type="submit" name="submit" class="btn btn-success btn-sm" >
            Save</button>

</form>

{% for rl in rl %}

 Ticket: {{ rl.ticket }}

 Lab Tests: {{ rl.lab_test }}

{% endfor %}

So, It's displaying as a checkbox that's good. but when i want to save some data it saves only ticket, not lab_test? So, how do I save both?

As you see it displays only ticket which is Ubed Gedi ALi and where I wanted to see lab_test it shows me appname.modelname.None


text:
Q: Adding TextField to UIAlertView I need to add a TextField to an UIAlertView. I understand that apple discourage this approach. So is there any library that i could make use of to add a TextField to a UIAlertView look-alike frame ?

A: For iOS5:
UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Title" message:@"Please enter someth" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
av.alertViewStyle = UIAlertViewStylePlainTextInput;
[av textFieldAtIndex:0].delegate = self;
[av show];

Also, you 'll need to implement UITextFieldDelegate, UIAlertViewDelegate protocols.

A: I'm using BlockAlertsAndActionSheets instead of the Apple components for AlertViews and ActionSheets as I prefer the blocks-approach. Also contains a BlockTextPromptAlertView in the source, which might be what you want. You can replace the images of that control to get the Apple-style back.
Project on gitgub
Tutorial which gets you started
Example:
- (IBAction)newFolder:(id)sender {
    id selfDelegate = self;
    UITextField                 *textField;
    BlockTextPromptAlertView    *alert = [BlockTextPromptAlertView  promptWithTitle :@"New Folder"
                                                                    message         :@"Please enter the name of the new folder!"
                                                                    textField       :&textField];
    [alert setCancelButtonWithTitle:@"Cancel" block:nil];
    [alert addButtonWithTitle:@"Okay" block:^{
        [selfDelegate createFolder:textField.text];
    }];
    [alert show];
}

- (void)createFolder:(NSString*)folderName {
    // do stuff
}

A: Try something like this:
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Title"
                                                 message:@"\n\n"
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"Save", nil] autorelease];
CGRect rect = {12, 60, 260, 25};
UITextField *dirField = [[[UITextField alloc] initWithFrame:rect] autorelease];
dirField.backgroundColor = [UIColor whiteColor];
[dirField becomeFirstResponder];
[alert addSubview:dirField];

[alert show];

A: As of iOS 8 UIAlertView has been deprecated in favor of UIAlertController, which adds support for adding UITextFields using the method:
- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler;

See this answer for an example.

A: You can try:
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Your title here!" message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[myAlertView addSubview:testTextField];
[myAlertView show];
[myAlertView release];

Follow this link for detail.

A: Unfortunately the only official API for this is iOS 5 and up, it's a property called alertViewStyle which can be set to the following parameters:
UIAlertViewStyleDefault
UIAlertViewStyleSecureTextInput
UIAlertViewStylePlainTextInput
UIAlertViewStyleLoginAndPasswordInput

UIAlertViewStylePlainTextInput being the one you want.
Messing with the view hierarchy as described above is strongly discouraged by Apple.

A: first of All Add UIAlertViewDelegate into ViewController.h File like
#import <UIKit/UIKit.h>

@interface UIViewController : UITableViewController<UIAlertViewDelegate>

@end

and than Add Below Code where you wants to alert Display,
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
                                            message:@"Message"
                                           delegate:self
                                  cancelButtonTitle:@"Done"
                                  otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

and it's delegate method which returns what input of UItextField
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"%@", [alertView textFieldAtIndex:0].text);
}

A: refer this... http://iosdevelopertips.com/undocumented/alert-with-textfields.html this is private api and if you use it for app in appstore it might get rejected but it is fine for enterprise development.

A: adding to answer from 'Shmidt', the code to capture text entered in UIAlertView is pasted below (thank you 'Wayne Hartman' Getting text from UIAlertView)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        self.userNumber = [alertView textFieldAtIndex:0].text;
        if (self.userNumber) {
            // user enetered value
            NSLog(@"self.userNumber: %@",self.userNumber);
        } else {
            NSLog(@"null");
        }

    }
}


text:
Q: C# : bool array is not updating during execution i have this sample code which basically reads some string data from csv file and updates in textboxes and some variables.
The csv file is of the format 10,0,20,0,0,30,0..etc with 20 values. The idea is, if any of the value in csv file is 0, the isCashAvailable variable should be set to false and vice versa. Below is my code.
int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

public void UpdateCash()
{
        var cashCSV = File.ReadAllText("cash.csv");
        List<string> cashVal = cashCSV.Split(',').ToList();

        for (int i = 1; i <= 20; i++)
           {
            var control = this.Controls.Find("textBox" + i.ToString(), true).FirstOrDefault() as TextBox;
            if (cashVal[i - 1] != "0")
              {
                 isCashAvailable[i - 1] = true;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);
              }

            else
              {
                 isCashAvailable[i - 1] = false;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);

              }
           }
}

Now the issue is, when I try to update the value of the isCashAvailable and cash in runtime, its not updating. Whereas if am debugging it by stepping over each iteration, its updating. Can't seem to find why this is happening.

A: Try this:
int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

var cashCSV = File.ReadAllText("cash.csv");
List<string> cashVal = cashCSV.Split(',').ToList();

// changing this allows you to use i+1 just once, instead of doing i-1 over and over
for (int i = 0; i < 20; i++)
   {
    // this way it will throw an error if TextBox is not found instead of
    // not throwing it here and then throwing NullReference later
    var control = this.Controls.Find("textBox" + (i+1).ToString(), true).First() as TextBox;

    //if-else is not needed here
    //TryParse to make sure it always works
    int.TryParse(cashVal[i], out cash[i]);
    isCashAvailable[i] = (cash[i] > 0);
    control.Text = cashVal[i];

    //it works
    Debug.Print($"{i}: isCashAvailable = {isCashAvailable[i]}, cashVal = {cashVal[i]}");
   }


text:
Q: Spark / Scala code no longer working in Spark 3.x This ran fine under 2.x:
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{Encoder, Encoders}
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.split
import org.apache.spark.sql.functions.broadcast
import org.apache.spark.sql.functions.{lead, lag}
import spark.implicits._

// Gen example data via DF, can come from files, ordering in those files assumed. I.e. no need to sort.
val df = Seq(
 ("1 February"), ("n"), ("c"), ("b"),
 ("2 February"), ("hh"), ("www"), ("e"),
 ("3 February"), ("y"), ("s"), ("j"),
 ("1 March"), ("c"), ("b"), ("x"),
 ("1 March"), ("c"), ("b"), ("x"),
 ("2 March"), ("c"), ("b"), ("x"),
 ("3 March"), ("c"), ("b"), ("x"), ("y"), ("z")
 ).toDF("line")

// Define Case Classes to avoid Row aspects on df --> rdd --> to DF which I always must look up again.
case class X(line: String)
case class Xtra(key: Long, line: String)

// Add the Seq Num using zipWithIndex.
val rdd = df.as[X].rdd.zipWithIndex().map{case (v,k) => (k,v)}
val ds = rdd.toDF("key", "line").as[Xtra]

The last statement returns now under 3.x:
AnalysisException: Cannot up cast line from struct<line:string> to string.
The type path of the target object is:
- field (class: "java.lang.String", name: "line")
- root class: "$linecfabb246f6fc445196875da751b278e883.$read.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.Xtra"
You can either add an explicit cast to the input data or choose a higher precision type of the field in the target object

I find the message hard to fathom and the reason for the change. I just tested under 2.4.5. and it is fine.

A: Since line is inferred as a struct, you can change a bit your schemas (case classes):
case class X(line: String)
case class Xtra(key: Long, nested_line: X)

And then get the desired result by using:
val ds = rdd.toDF("key", "nested_line").as[Xtra].select("key", "nested_line.line")


text:
Q: SQLITE3 + execute Insert Trying to execute insert an item coming from a list:`

item=u'Sunil Goyal'
c.execute('''INSERT INTO bpersons(person_name) VALUES (?)''',item)`

is simple enough, but it returns

Incorrect number of bindings supplied. The current statement uses 1, and there are 11 supplied.

Clearly instead of reading item as one element, it is reading characters. There is no problem with the earlier code which returns this list:
>>> if meta[7]:#bcoz list could be empty also
    for item in meta[7]:
        print item

Sunil Goyal
Rehan Yar Khan
Khan
Kae Capital
Ashish Shankar
Karthik Reddy
Feroze Azeez

len(meta[7])
      7

Any idea where I am going wrong?

A: insert is looking for an iterable (documentation) and this succeeds because your unicode string is an iterable, but you should put it inside of a tuple or list to be handled properly by sqlite3.
c.execute('''INSERT INTO bpersons(person_name) VALUES (?)''',(item,))`


text:
Q: how can i store my access token to defaults or into an array i want to hit an API at login then i'll get a access token then whenever i"ll run my app it moves directly to homepage but m unable to get the access token there,how can i achieve this.my homepage Conditions are not getting access token simply.

A: You can use user defaults objective c save your token
NSString *token = @"yourToken";
[[NSUserDefaults standardUserDefaults] setObject: token forKey:@"Token"];
[[NSUserDefaults standardUserDefaults] synchronize];

Get your token
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"Token"];

Swift3.0 code save data
let defaults = UserDefaults.standard
defaults.set("yourToken", forKey: "Token")

// Get the Token from UserDefaults
if let token = defaults.value(forKey: "Token") as? String {
    print("defaults Token: \(token)")
}

A: When you get a success response from login API.
write this line after your response and before you push to homepage.
[[NSUserDefaults standardUserDefaults] setObject:@"Token" forKey:@"accessToken"];

I hope it will work for you.

A: It is very simple to achieve using NSUserDefaults
Step 1: When login API called and got the response, then save the accessToken in user defaults, like:
[[NSUserDefaults standardUserDefaults] setObject:@"yourAccessToken" forKey:@"AccessTokenKey"];

Step 2: Retrieve the saved accessToken you have saved in user defaults whenever you required throughout the project, like:
NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"AccessTokenKey"];

Happy coding...


text:
Q: Airplay mirroring with extended desktop: how to choose which apps end up on Apple TV? I use my Macbook hooked up to a TV via HDMI for most of my work, and want to use Airplay mirroring from my Mac to extend my desktop and play online videos full screen on my Apple TV while also being able to do work on my computer that won't end up on the screen. It seems to me that using airplay mirroring with the "desktop extension" option is the best way to do this. However, whenever I turn it on, all of my apps end up on the TV screen and my desktop ends up completely blank. Is there a way to choose which desktop is the one that goes on to the TV?

A: When you switch from Mirroring to Extended Desktop

To move open windows, or Applications, to the Apple TV display simply
  click and drag the window by the Title Bar to the left hand side of
  your display (keep dragging over the screen edge). As you do this the window will appear in a transparent
  view on the Apple TV display. Once the entire window is on the new
  display, it will become active and can be interacted with in your
  second workspace........

You can also use Mission control and just drag the allocations between the displays.
And the cmd left arrow


text:
Q: What abilities are affected by Radiance? So the Radiance skill says that your abilities are boosted, but which abilities are boosted?

Is it just melee? Does it include grenades? What use is this skill on it's own without any upgrades?

A: Radiance greatly speeds up cooldown times for your melee ability (energy drain, scorch) and grenade. You also drop at least one light orb for every enemy you kill while Radiance is active.
I believe cooldown times are the only thing boosted by the base Radiance ability. I've never noticed any damage boost per grenade or melee ability while using Radiance. It simply lets you use a lot more of them in a short time span.
Source for more sunsinger/radiance information.
Edit: ran a quick test last night: hit a dreg with a fusion grenade, then I activated Radiance and hit another dreg of the same level with another fusion grenade. The grenade did the same damage to both enemies. Similar tests with scorch produced the same result.

A: In PVP the melee attack whilst using radiance is a one hit kill rather than the usual two (hitting an enemie with full health and armour).
So I would say that the melee damage is increased but this is just from personal experience/opinion.


text:
Q: Check duplicate using SQL before adding new asset I have table asset following this:
id  status  revision  EAN
-------------------------
1   Published    0     1
1   Published    1     2
1   Deleted      2     3
2   Published    0     4
2   Draft        1     5

Before adding new asset, I want to check EAN in table that if asset had status Deleted, EANs of this asset can be reused (it means 1, 2, 3 can be used for new asset) and otherwise, I can not use ean in table (4, 5 can not be used).
I used count in SQL to check if >0 -> duplicate :
select count(*)
from Asset a
where a.ean = '1'
  and a.id <> 0
  and a.status != 'Deleted'
  and a.revision = (select max(a1.revision)
                    from Asset a1
                    where a1.id = a.id)

but it's not right for case which asset had not status Deleted.
Can anyone give me some feedback?
Please help me.
Thanks

A: I think, your query mixed up something. You where counting only the exact line with your EAN you were searching. You can count all rows with the matching id from your EAN like this:
select count(*) from Asset
where id = (
select id
from Asset a
where a.EAN = 1)
and status='Deleted'

You can even add your check for the last revision like this:
and revision = (select max(revision) from Asset WHERE id=
(
select id
from Asset a
where a.EAN = 1
))

A: i'm done with sql:
select count(*) from Asset a where a.ean=? and a!=? and not exist(select * from Asset a1 where a1.id = a.id and a.status ='Deleted').
Thanks all.


text:
Q: Ошибка: имя типа или пространства имен отсутствует в пространстве имен using System.drawing;

В C# выдает:

Ошибка    1   Имя типа или пространства имен "drawing" отсутствует в пространстве имен "System" (пропущена ссылка на сборку?) E:\C#\librery\ConsoleApplication1\ConsoleApplication1\Program.cs    5   14  ConsoleApplication1

Я так понимаю, мне надо что-то загрузить, вот только что и где?
A: В C# регистр букв имеет значение. Drawing и drawing - это два разных идентификатора. Ошибка говорит о том, что в пространстве имен System нет имени drawing. И там его действительно нет. Надо так:
using System.Drawing;

A: Необходимо добавить ссылку на сборку System.Drawing.dll (консольной приложение, по умолчанию не добавляется). Ну и на всякий случай: drawing с большой буквы:
    using System.Drawing;


text:
Q: How can I change folder or file permissions when mount in Azure storage service? Please..Waiting for your earnest answers.
My development environment is Azure cloud - Kubernetes
and I want to install the Gitlab Docker image in Azure's storage service.
Look at the log below, Gitlab starts up and tries to change the permissions of Azure storage, but Azure storage does not allow this.
Eventually, Gitlab cannot be started.
I tried changing the mount option when loading Kubernetes' StorageClass, pv, and pvc, but couldn't apply it.
Please answer for this..
================================================================================
    Error executing action `create` on resource 'storage_directory[/var/opt/gitlab/.ssh]'
    ================================================================================
    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    ruby_block[directory resource: /var/opt/gitlab/.ssh] (/opt/gitlab/embedded/cookbooks/cache/cookbooks/package/resources/storage_directory.rb line 34) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
    ---- Begin output of chmod 00700 /var/opt/gitlab/.ssh ----
    STDOUT:
    STDERR: chmod: changing permissions of '/var/opt/gitlab/.ssh': Operation not permitted
    ---- End output of chmod 00700 /var/opt/gitlab/.ssh ----
    Ran chmod 00700 /var/opt/gitlab/.ssh returned 1
    Cookbook Trace:
    ---------------
    /opt/gitlab/embedded/cookbooks/cache/cookbooks/package/libraries/storage_directory_helper.rb:35:in `run_command'
    /opt/gitlab/embedded/cookbooks/cache/cookbooks/package/libraries/storage_directory_helper.rb:55:in `ensure_permissions_set'
    /opt/gitlab/embedded/cookbooks/cache/cookbooks/package/resources/storage_directory.rb:40:in `block (3 levels) in class_from_file'
    Resource Declaration:
    ---------------------
    # In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-shell.rb
     34:   storage_directory dir do
     35:     owner git_user
     36:     group git_group
     37:     mode "0700"
     38:   end
     39: end
    Compiled Resource:
    ------------------
    # Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-shell.rb:34:in `block in from_file'
    storage_directory("/var/opt/gitlab/.ssh") do
      action [:create]
      default_guard_interpreter :default
      declared_type :storage_directory
      cookbook_name "gitlab"
      recipe_name "gitlab-shell"
      owner "git"
      group "git"
      mode "0700"
      path "/var/opt/gitlab/.ssh"
    end
    System Info:
    ------------
    chef_version=14.14.29
    platform=ubuntu
    platform_version=16.04
    ruby=ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
    program_name=/opt/gitlab/embedded/bin/chef-client
    executable=/opt/gitlab/embedded/bin/chef-client
Running handlers:
There was an error running gitlab-ctl reconfigure:
storage_directory[/var/opt/gitlab/.ssh] (gitlab::gitlab-shell line 34) had an error: Mixlib::ShellOut::ShellCommandFailed: ruby_block[directory resource: /var/opt/gitlab/.ssh] (/opt/gitlab/embedded/cookbooks/cache/cookbooks/package/resources/storage_directory.rb line 34) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
---- Begin output of chmod 00700 /var/opt/gitlab/.ssh ----
STDOUT:
STDERR: chmod: changing permissions of '/var/opt/gitlab/.ssh': Operation not permitted
---- End output of chmod 00700 /var/opt/gitlab/.ssh ----
Ran chmod 00700 /var/opt/gitlab/.ssh returned 1
Running handlers complete
Chef Client failed. 7 resources updated in 07 seconds


text:
Q: Why are my functions triggering on page load and what can I do about it? I have the following javascript. For eample the console.log('test')triggers when I load the javascript. I expect it to trigger when I click a button with the class login. What am I doing wrong?
$(document).ready(function() {
    switchImage(5000, '#top .images');
    switchImage(5000, '#top .feature-text');
    $('.login input').focus(function(){
        $('.login .hidden').removeClass("hidden");
        $('.login [type=text]').removeClass("span2").addClass("span3");
    });
    $('.loginbutton').click(login());
});

function login(){
    event.preventDefault();
    console.log('test')
}

function switchImage(wait, element){

    //Fades out first element and put's it in the bottom of the stack
    $(element+'>*:first-child').delay(wait).fadeOut('slow', function() {

        //fade in imag2
        $(element+'>*:nth-child(2)').fadeIn('slow');
        $(element+'>*:first-child').appendTo(element);
        switchImage(wait, element);
    });
}

A: You have:
$('.loginbutton').click(login());

This says "When the button is clicked, invoke the result of login().
What you want is:
$('.loginbutton').click(login);

Which is "When the button is clicked, invoke the login function".


text:
Q: Firebase authentication error googleUser.getAuthResponse is not a function in react native I am attempting to Authenticate Using Google Sign-In with JavaScript in my react native app but I am getting the error in my onSignIn() function:
"googleUser.getAuthResponse is not a function"
I am not sure whats causeing this or why I seem to not be obtaining the correct credentials, can someone explain how to remove this error.
import React, { Component } from "react";
import { View, Text, StyleSheet, Button } from "react-native";
import firebase from "firebase";

import {
  getAuth,
  onAuthStateChanged,
  signInWithCredential,
  GoogleAuthProvider,
  getAuthResponse,
} from "firebase/auth";

import * as Google from "expo-google-app-auth";

class LoginScreen extends Component {
     isUserEqual(googleUser, firebaseUser) {
       if (firebaseUser) {
         var providerData = firebaseUser.providerData;
         for (var i = 0; i < providerData.length; i++) {
           if (
             providerData[i].providerId ===
               firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
             providerData[i].uid === googleUser.getBasicProfile().getId()
           ) {

             return true;
           }
         }
       }
       return false;
     }

  onSignIn(googleUser) {
    console.log("Google Auth Response", googleUser);
    // We need to register an Observer on Firebase Auth to make sure auth is initialized.
    let unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => {
      unsubscribe();
      // Check if we are already signed-in Firebase with the correct user.
      if (!this.isUserEqual(googleUser, firebaseUser)) {
        // Build Firebase credential with the Google ID token.
        const credential = firebase.auth.GoogleAuthProvider.credential(
          googleUser.getAuthResponse().id_token

        );
        console.log("Credential", credential);
        // Sign in with credential from the Google user.
        firebase
          .auth()
          .signInWithCredential(credential)

          .catch((error) => {
            // Handle Errors here.
            let errorCode = error.code;
            let errorMessage = error.message;
            // The email of the user's account used.
            let email = error.email;
            // The firebase.auth.AuthCredential type that was used.
            let credential = error.credential;
            console.log(errorCode, errorMessage, email);
          });
        console.log("WORKED");
      } else {
        console.log("User already signed-in Firebase.");
      }
    });
  }

  signInWithGoogleAsync = async () => {
    const result = await Google.logInAsync({
      androidClientId: `ANDROID CLIENT ID`,
      iosClientId: `IOS CLIENT ID`,
      scopes: [
        "profile",
        "email",
        "https://www.googleapis.com/auth/calendar",
        "https://www.googleapis.com/auth/calendar.events",
      ],
    });

    if (result.type === "success") {
      //console.log("Restult ", result);
      this.onSignIn(result);
      return result.accessToken;
    } else {
      return { cancelled: true };
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Sign In With Google"
          onPress={() => this.signInWithGoogleAsync()}
        />
      </View>
    );
  }
}
export default LoginScreen;

A: As documented here, if you want the user, you should use result.user.
Anyway, I see you're using the result just for the token, so you should be ok just changing your code to this:
    const credential = firebase.auth.GoogleAuthProvider.credential(
      googleUser.idToken
    );

since the token is already in the result object.


text:
Q: setting radio button checked under multiple tabs i have few tabs and each tab has same radio button groups like this

see case#1 has radio buttons name="managerid" and with class="managerid
<label>
    <input type="radio" name="managerid" class="managerid managerid_8" data-radio="iradio_square-grey" value="8">
     Spam Dead
</label>
<label>
    <input type="radio" name="managerid" class="managerid managerid_9" data-radio="iradio_square-grey" value="9">
     Stewart Stephenson
</label>

these are dynamically generated tabs and radio buttons
now i want to set radio button checked in each tabs with the value
this is how im doing
$.each($("#tab_"+r.id).find(".managerid"),function(i,v){
    if(v.value === r.managerid){
        v.checked = true;
    }
});

i know the id of the tab so i find() the managerid and set them checked if the value matches
the problem is that it sets radio checked on the last tab only
how do i set radios checked on each tab with different values

A: I would suggest you to assign different style class to radio button controls and that is a better possible way to select/deselect across multiple tabs


text:
Q: General questions on Cayley graphs In Graph Theory mainly in Cayley graphs there are four general questions " according to Audery Terras" : 'Suppose A is the adjacency operator of a connected regular (undirected)
graph $X$ of degree $k$ (without multiple edges). Let $spec(A)$ denote the spectrum
of $ A$, that is, the set of all eigenvalues of $A$. Let $d$ be the diameter of $X$ and $g$
be the girth.
Question 1. Is $X$ Ramanujan, that is, if $λ ∈spec(A)$, $|λ|≠k$ does $λ$ satisfy $|λ|≤ 2(k-1)^{1/2}$?
Question 2. Is $0∈  spec(A)$ or, equivalently, is $A$ invertible?
Question 3. Can we bound the diameter $d$?
Question 4. Can we bound the girth $g$?

As I am new in this field of mathematics, my question is: are there more important or maybe new questions that researcher can ask or for example analogue some questions?

A: Ramanujan graphs are important and interesting and, so far, all examples
are constructed as Cayley graphs. If you're interested in Ramanujan graphs,
then the problems that Audrey Terras lists are central. But Cayley graphs
appear all over graph theory and, when they do, raise questions not on her list.
One famous open problem is whether every Cayley graph has a Hamiltonian path.
(There are many variants, all of which are open.) In quantum information theory,
we would like to know which Cayley graphs admit perfect state transfer, even just
for Cayley graphs of abelian groups. There is
active work on the structure of the automorphism groups of Cayley graphs, particularly
circulants.


text:
Q: laravel cache failed to open stream: No such file or directory framework/views I use laravel 5.4. a clear cache after update config file. that appear like this error.
ErrorException in Filesystem.php line 111:
file_put_contents(/home/web_user/webhosts/mufer/backend.mufer.local/storage/framework/views/318a49f22562be3fc1c86c88ecc141c22e`8fed4e.php): failed to open stream: No such file or directory`

Then i try to fixed using following command:
php artisan route:cache
php artisan view:clear
php artisan config:cache

and:
file_put_content...fail to open stream:Permission denied in Laravel 5
Some answer are said craete /storage/framework  sub folders and then composer update. but that also not working.
screen shot
Then i run composer dump-autoload
andcomposer update`.
But problem not solved..

A: Perhaps you are using Homestead?
I ran into this problem when using Homestead. Basically, when you are using Homestead and run the php artisan config:cache command out of your virtual machine, the cache paths get broken.
I solved it login via ssh to Homestead vagrant ssh and running php artisan config:cache from there.

A: My solution was to chmod /storage/framework/views directory to 777.

A: I had this same problem and my mistake was so simple it's hilarious.
I forgot to git add one of my files. So on the backend, it was trying to get this file.php but it didn't exist. It's usually quite descriptive in the error, except, I was running a job that jumps on a queue. All of a sudden, that helpful exception no longer exists :D
So in order to fix it, I had to:

git add -A
git commit -m "blah blah"
git push

On the server, I needed to:

git pull
composer dump-autoload

A: It's worked for me gently:
php artisan view:cache


text:
Q: Graphql not loading data when page opened in new tab I am using graphql api for accessing some data ie. Transaction history for some payments.
When I am opening page by tapping on button to open page it is working fine. But when I am opening the page in new tab the data is not loading. When in the new tab I am refreshing then again data is loading.
Database used - mongodb
Api - graphql
Framework - react
Please someone help, I've searched whole google but couldn't find anything.


text:
Q: Jmockit mock abstract class I have a super abstract class
public abstract class PsActionBeanContext{
    ...
    abstract public Brand getBrand();
    ..
}

I want to mock the abstract class to get default value "TESTUSER_BRAND_ID", which is a constant.
 I tried:
final PsActionBeanContext contextFake = new MockUp<PsActionBeanContext>(){
 @Mock
 public Brand getBrand(){
      Brand brand = new Brand();
      brand.setBrandId(TESTUSER_BRAND_ID);
      return brand;
      }
 }.getMockInstance();
}

But I got

java.lang.IllegalArgumentException: Attempted to mock abstract method "getBrand"

I tried the same way to mock an interface but that is fine.
 any suggestion? thanks

A: Try the following instead:
@Test
public void mockAbstractClass(@NonStrict final PsActionBeanContext mock)
{
    final Brand brand = new Brand();
    brand.setBrandId(TESTUSER_BRAND_ID);

    new Expectations() {{ mock.getBrand(); result = brand; }};

    assertSame(brand, mock.getBrand());
}


text:
Q: list conversion of jsonlite in R I would like to have a list of matrices within R imported from a json file using jsonlite.
A <- matrix(rnorm(100),10,10)
B <- matrix(rnorm(100),10,10)
C <- matrix(rnorm(100),10,10)
l <- list(A,B,C)
import_l <- fromJSON(toJSON(l),simplifyMatrix = FALSE)

the above code doesnt work since it is R internally a list of list of numerics. However, I would like to have my list of A,B,C back, i.e. l. Is there a way to achieve getting back the correct list of matrices using jsonlite?

A: The issue here is that a column matrix and an unnamed list look the same if converted to JSON:
toJSON(list(1, 2, 3))
## [[1],[2],[3]]
toJSON(matrix(c(1, 2, 3), ncol = 1))
## [[1],[2],[3]]

However, a named list looks different:
toJSON(list(A = 1, B = 2, C = 3))
## {"A":[1],"B":[2],"C":[3]}

If you use a named list in your example, fromJSON() does indeed reproduce the original list:
l <- list(A = A, B = B, C = C)
all.equal(fromJSON(toJSON(l)), l, tol = 1e-4)
## [1] TRUE

If this is not possible - for example because you don't create the JSON file yourself, but get it as an input - you can also convert the result you get with fromJSON():
l <- list(A, B, C)
import_l <- fromJSON(toJSON(l))
l2 <- lapply(1:3, function(i) import_l[i, , ])
all.equal(l2, l, tol = 1e-4)
## [1] TRUE