text:
Q: Bigendian/Littleendian confusion i am working on the legacy code, which is written for ipv4. Now i have added the similar code for ipv6. i have tried and tested on host machine..but i have concern whether it will work on the powerpc , because of endianness...the code is to extract the ip header from the incoming stream and compress it..any comments will be helpful
class st_ipv6
{
  //==================================================================================================
public:
  //==================================================================================================

#ifdef _BIG_ENDIAN
  uint32  version:4;              // version
  uint32  trafficclass:8;         // header length
  uint32  flowlabel:20;           // flow label
#else
  uint32  trafficclass_1:4;
  uint32  version:4;              // version
  uint32  flowlabel_1:4;
  uint32  trafficclass_2:4;         // traffic class
  uint32  flowlabel_2:4;           // flow label
  uint32  flowlabel_3:4;           // flow label
  uint32  flowlabel_4:4;           // flow label
  uint32  flowlabel_5:4;           // flow label
#endif
  uint16  payloadlength;          // payload length
  uint8   nextheader;             // next header
  uint8   hoplimit;               // hop limit
  uint32  sourceaddress[4];       // source address
  uint32  destinationaddress[4];  // destination address

#ifdef _BIG_ENDIAN
  //**********************************************************************************************
  //* Description:
  /**  Specify/Return IPv6 Version
  */
  //**********************************************************************************************
  inline void setVersion(uint8 ubyVersion)
  {
    version = ubyVersion;
  }
  inline uint8 getVersion()
  {
    return version;
  }

A: Bitfields and portability are generally a nightmare.  It is usually better to use and/or/shift.
See e.g. below.
As long as you call hton*()/ntoh*() on the various integers as you read/write them you will (hopefully) have no problems.
I'd also write the rest of the accessors and make the data fields private.
class st_ipv6
{
public:
    uint32 version_info;
    uint16 payloadlength;
    uint8  nextheader;
    uint8  hoplimit;
    uint32 sourceaddress[4];
    uint32 destinationaddress[4];

    uint8 GetVersion()
    {
        return version_info & 0xF;
    }
    void  SetVersion(uint8 v)
    {
        version_info = (version_info & ~0xF) | (v & 0xF);
    }
    uint8 GetTrafficClass()
    {
        return (version_info & 0xFF0)>>4;
    }
    void  SetTrafficClass(uint8 c)
    {
        version_info = (version_info & ~0xFF0) | ((c & 0xFF) << 4);
    }
    uint32 GetFlowLabel()
    {
        return (version_info & 0xFFFFF000)>>12;
    }
    void  SetFlowLabel(uint32 f)
    {
        version_info = (version_info & ~0xFFFFF000) | ((f & 0xFFFFF) << 12);
    }
};

A: I would recommend using a struct rather a class as things like RTTI could insert extra things in the memory layout.
and I think this should be sufficient
#ifdef _BIG_ENDIAN
  uint32  version:4;              // version
  uint32  trafficclass:8;         // header length
  uint32  flowlabel:20;           // flow label
#else
  uint32  flowlabel:20;           // flow label
  uint32  trafficclass:8;         // header length
  uint32  version:4;              // version
#endif

...but you should ntohl(flowlabel) when reading the flowlabel and htonl(flowlabel) when setting it.

A: Be careful with different compilers and using bitfields. Some compilers start the bitfield at the high bit and work downward while others work from the low bit.  You are better off doing the masking from the raw bytes yourself unless you test carefully across the different compilers you are using.

A: thanks a lot Michael. Based on inputs i wrote a simple version of the function and tried to do the basic test and it looks ok for the version fields. My program looks like this. Only concern now is, when we have array of uint32's like src and dst address
class ip_v6{
public:
   uint32 version_info;
   uint16 payload_len;
   uint8 next_header;
   uint8 hop_limit;
   uint32 src_addr[4];
   uint32 dst_addr[4];
uint32 GetVersionInfo()
   {
      return ( ntohl(version_info));
   }
void SetVersionInfo(uint32 vinfo)
   {
      version_info = htonl(vinfo);
   }
uint8 GetVersion()
   {
      return ( ( (GetVersionInfo() )& (0xf0000000)) >> 28);
   }
void  SetVersion(uint8 v)
   {
      SetVersionInfo( ( GetVersionInfo() & 0x0fffffff ) | (v<<28));
   }
uint8 GetTrafficClass()
   {
      return ( ( (GetVersionInfo() )& (0x0ff00000)) >> 20);
   }
void  SetTrafficClass(uint8 c)
   {
      SetVersionInfo( (GetVersionInfo() & 0xf00fffff) |(c<<20 )) ;
   }
uint32 GetFlowLabel()
   {
      return ( (GetVersionInfo() )& (0x000fffff)) ;
   }
void  SetFlowLabel(uint32 f)
   {
      SetVersionInfo( (GetVersionInfo() & 0xfff00000) |(f ) );
   }
};


text:
Q: value error: source code string cannot contain null bytes in import numpy
I installed package numpy,pandas, and I tried to import it to my project,but unfortunately I received the
error: "value error: source code string cannot contain null bytes"
i don't have same problem with other package.How should i solve this problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Backbone - Collections nested in Models Is it possible to nest collections within models?
I know that you can create new collections in the initialize callback of a model, and create references that you can pass back and forth between the collection and parent model.  But is it possible to set the collection as part of the model, such that the JSON it exports looks like this:
{
  blah: 'blah',
  myCollection: [
      {
         foo: 'asdf',
         bar: 'qwer'
      },
      {
         foo: 'asdf123',
         bar: 'qwer123'
      }
  ]
}

If not, how do you handle syncing a model with related collections to the backend?  Do you have to tap into backbone's sync and rebuild the JSON or is there something more seamless?
Sorry if this question has been answered elsewhere.  I've looked around and seen some workarounds, but nothing that really answers what I'm looking for.

A: Renato was close but "has" and "set" will not be available yet. I believe Reckoner pointed out part of that. Also, you will need to delete the property from the response, else it will override the default value.
_.extend(Backbone.Model.prototype, {
    parse: function(resp, xhr) {
        var attr, model, models, collection, options;
        for (var prop in resp) {
            if (this.defaults && this.defaults[prop]) {
                attr = this.defaults[prop];
                if (attr instanceof Backbone.Model) {
                    model = attr.clone();
                    model.set(resp[prop]);
                    resp[prop] = model;
                } else if (attr instanceof Backbone.Collection) {
                    models = attr.map(function (model) { return model.clone(); });
                    options = _.clone(attr.options);
                    collection = new attr.constructor(models, options);
                    collection.add(resp[prop]);
                    resp[prop] = collection;
                }
            }
        }
        return resp;
    }
});

Hope that helps someone.

A: There are two approaches.  The first is to define a root Model that gets everything.  You override it's parse() method to create sub-collections and sub-models for nested attributes, and override the toJSON() method to convert back to the JSON structure, suitable for saving to the server.
This is perfectly acceptable for small subcollections.  It takes a bit of programming, but if you can read the Backbone source code, how to do it should be, well, not obvious, but at least understandable.
Or you can use Backbone Relational, which does all the work for you.


text:
Q: Unexpected binary sequences in Postscript generated by Canon printer driver We are having issues with the Postscript code generated by the "Canon iR-ADV C5235/5240 PS3" printer driver. We print a test document (3 A4 pages of Lorem Ipsum text) and get the following Postscript output in the Windows spool directory:
http://files.etvdzs.info/original.ps
We have tried various Postscript viewers/converters, and they are unable to handle this file. The reason is that the file contains sections of binary data at the beginning and end, and also the following byte sequence at position 0x1060b:
cd ca 10 02 00 1a 00 01 82 6f ff ff 00 00 00 00 00 00 00 00 01

If we remove these three binary sequences, we get the resulting file, which works fine in most Postscript viewers/converters we have tried:
http://files.etvdzs.info/cleaned.ps
Has anybody else encountered similar issues with Canon printer drivers? Does anybody know what these binary sequences signify, or what format they are in?

A: The binary sequences are CPCA codes. One can download documentation about the data structures used in CPCA after registering here:
https://www.developersupport.canon.com/user/register
It is then reasonably straightforward to write a program that strips the CPCA codes out of the file. The file can then be loaded successfully by 3rd-party Postscript viewers/converters.


text: Q: Is it possible to know when device enters into Doze (STATE_IDLE) mode? I'd like to ask whether it is possible to receive a notification from the OS when the device is just about to enter into Doze mode (STATE_IDLE).


text:
Q: How to add additional attributes to standard XAML elements? This button click method launches a Window called "(assemblyname).Reports" when a button with Content "Reports" is clicked:
private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)e.OriginalSource;
    Type type = this.GetType();
    Assembly assembly = type.Assembly;
    Window window = (Window)assembly.CreateInstance(String.Format("{0}.{1}", type.Namespace, button.Content));
    window.ShowDialog();
}

But I want the Content attribute value of the button to be able to change, e.g. it might change to "Stock Reports" but I still want the clicking of the button to launch "(assemblyname).Reports".
Is there a way to add attributes to the button tag, e.g. "TheWindowFileName"?
<Button x:Name="btnReports" Content="Stock Reports" TheWindowFileName="Reports"/>

If not, how else can I add additional information to my button elements which I can read and process in code behind?

A: Certainly you can use attached properties to add extra attributes to XAML elements, but for what you need you could probably just use the existing Tag property:
<Button x:Name="btnReports" Content="Stock Reports" Tag="Reports"/>

A: Using Attached Property here can be an overkill but instead you can try to encapsulate your button behavior in a Command and pass the data you want to use in the command as a CommandParameter. That should do the trick.


text:
Q: Nested Promise execution is out of sync I have a simple setup, illustrated in this fiddle:
var doDelay = function(who) {
    return Promise.delay(50)
        .tap(function() {
            console.log(who + ' done');
        });
};

Promise.resolve()
    .then(doDelay('a'))
    .tap(function() {
        console.log('a done2');
    })
    .then(doDelay('b'))
    .tap(function() {
        console.log('b done2');
    })
    .then(function() {
        console.log('all done!');
    });

The output is:
a done2
b done2
all done!
a done
b done

But I expect:
a done
b done
a done2
b done2
all done!

What am I doing wrong?

A: You must not pass a promise (the result of immediately calling delayMany) to then. Instead, it expects a callback function to execute when the context promise resolves. You'll need to wrap your delayMany invocation in a function expression:
Promise.resolve()
.then(function(undefined) { return delayMany(xsa); })
.tap(function(xsa) { console.log(xsa[0] + ' done2'); })
.then(function(xsa) { return delayMany(xsb) })
.tap(function(xsb) { console.log(xsb[0] + ' done2'); })
.then(function(xsb) { console.log('all done!'); });

A: As Bergi points out, it's not valid to pass a promise as the argument to then, but even if it were allowed, another issue is that as soon as you call delayMany('a'), the Promise.delay(50) inside it will start executing which is not what you are looking to do.
You can either wrap the call in an anonymous function, or use .bind():
var delayMany = function(who) {
    return Promise.delay(50)
    .tap(function() {
        console.log(who  + ' done');
    });
};

Promise.resolve()
.then(delayMany.bind(null, 'a'))
.tap(function() { console.log('a done2'); })

.then(delayMany.bind(null, 'b'))
.tap(function() { console.log('b done2'); })

.then(function() {
    console.log('all done!');
});

Q: "Why doesn't then throw an error when I pass a promise to it?"
The answer to this is in the Promises/A+ spec:

A promise's then method accepts two arguments:
promise.then(onFulfilled, onRejected)
2.2.1. Both onFulfilled and onRejected are optional arguments:
2.2.1.1. If onFulfilled is not a function, it must be ignored.

A: Since you are using bluebird you can simply use the .delay method instead:
Promise.resolve()
    .delay('a', 50)
    .tap(function() {
        console.log('a done2');
    })
    .delay('b', 50)
    .tap(function() {
        console.log('b done2');
    })
    .then(function() {
        console.log('all done!');
    });


text:
Q: Multi-Band (RGBA) into single band raster I have the raster which contains 4 bands (RGBA), which ilustrates the pupulation (traffic) density. I want to convert it to the simple gridded ascii, however I'm getting in the trouble when I try the export it to the different formats. I suppose it comes from multi-band property of this map, therefore:
Is there any way I can convert from RGBA to single value representing the data I need ?
E.g. when I want to convert using RGB2PCT:

ERROR 1: TIFFOpen:traffic_przyciety2: Permission denied  Traceback
  (most recent call last):  File "C:\PROGRA~2\Quantum GIS
  Lisboa\bin\rgb2pct.py", line 136, in
  tif_ds.GetRasterBand(1).SetRasterColorTable( ct )  AttributeError:
  'NoneType' object has no attribute 'GetRasterBand'

BTW: AttributeError: 'NoneType' error is dropped in other functions as well when I want to do something on this map
Info about the map:

Band 1 Block=903x1 Type=Byte, ColorInterp=Undefined   Min=0.000
  Max=255.000    Minimum=0.000, Maximum=255.000, Mean=254.667,
  StdDev=9.206 Band 2 Block=903x1 Type=Byte, ColorInterp=Undefined
  Min=0.000 Max=124.000    Minimum=0.000, Maximum=124.000, Mean=119.886,
  StdDev=7.547 Band 3 Block=903x1 Type=Byte, ColorInterp=Undefined
  Min=0.000 Max=0.000    Minimum=0.000, Maximum=0.000, Mean=0.000,
  StdDev=0.000 Band 4 Block=903x1 Type=Byte, ColorInterp=Undefined
  Min=0.000 Max=255.000    Minimum=0.000, Maximum=255.000, Mean=217.937,
  StdDev=67.026'

Alternatively, do you know if there's any standard interpretation of the geodata maps ?
E.g. if the resulting pixel value may be obtained by specific operation on the bands ?
Thanks for the answers
BR
Krzysztof

A: If the output file format is not geotiff, rgb2pct.py creates an intermediate geotiff to write the results into before converting that to the final output format.  The comments in the code state:
# Create the working file.  We have to use TIFF since there are few formats
# that allow setting the color table after creation.

From lines 127-129 of rgb2pct.py:
126  if format == 'GTiff':
127      tif_filename = dst_filename
128  else:
129      tif_filename = 'temp.tif'

Note that no directory is specified for 'temp.tif'...
I think what is happening is that you are trying to output directly to an ascii raster, so rgb2pct.py tries to create an intermediate GeoTiff in the current working directory which in this case would probably be the directory that the script file lives in "C:\PROGRA~2\Quantum GIS Lisboa\bin\".  And I assume you don't have permission to write into that directory which is why you get the Permission denied error.
I'd say this is a bug in rgb2pct.py.  It should probably write to a temp directory instead of the current directory.
The simplest workaround would be to set the output format to geotiff and write to a path that you have permissions for, then convert to an ascii grid as a second step.
Edit: bug report and patch submitted to GDAL trac.

A: It depends what do you want to do with your outout data. Is your data on 1 of the layers of the raster or you have to convert 3 or 4 bands into 1? Either way you can make use of raster calculator. If you want mean of 3 or 4 bands in your output raster just add them up and divide by number of lyers: (r@1 + r@2 + r@3)/3, else you just select band of interest and export it to new file. Thats in theory, as I did not test it on QGIS.


text:
Q: How would I implement zipping all the files in a folder into my code? So far I have a code that takes screenshots every 2 seconds and saves them to the a folder. I would like to add in a function for the program to take those screenshots every 2 hours and zip them up. I am currently working on trying to figure out how to set individual timers in my code, but after that I will need to add this.
I have been looking up and trying to learn how to do it, but my knowledge on c# code is extremely limited.
I tried adding the following into my code
using System.IO.Compression

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = @"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);

but it comes back with "Using directive is unnecessary." for System.IO.Compression. Plus I can't figure out how my directory of C:\Intel\Logs\dsp would fit into each field ie.
c:\example\start
c:\example\result.zip
c:\example\extract

Can someone please help me figure out what I'm doing wrong and explain to me (in very blatant terms) how I can fix it?
Thank you so much!
P.S. Will adding in this part create the zip file and make it hidden? Also, which path do I put for that line then?
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
File.SetAttributes("c:\example\whichpath", FileAttributes.Hidden); //HERE
string extractPath = @"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);

A: From here you need add what the comment recommends as below:
using System.IO.Compression;
using System.IO.Compression.FileSystem;

...

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";

ZipFile.CreateFromDirectory(startPath, zipPath);

// and hide it
File.SetAttributes(zipPath, File.GetAttributes(zipPath) | FileAttributes.Hidden);


text:
Q: Object referencing confusion I am getting a NullPointerException on the MainClass.ob1.noOfVerts variable in the following code:

import java.awt.*;
import javax.swing.*;

public class drawr extends JPanel{

    public void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(Color.decode("#ffc000"));
        g.drawLine(0, 0, getWidth(), getHeight());
        for(int cnt=0; cnt/displayObject.dim*2<=**MainClass.ob1.noOfVerts**; cnt+=displayObject.dim*2){
            g.drawLine(MainClass.ob1.coords[cnt], MainClass.ob1.coords[cnt+1], MainClass.ob1.coords[cnt+2], MainClass.ob1.coords[cnt+3]);
        }
    }

The object is instantiated here:
import java.awt.Color;
import javax.swing.*;

public class MainClass{

    public static final int windowWidth = 1280;
    public static final int windowHeight = 640;
    public static boolean crash = false;

    public static displayObject **ob1**, ob2, ob3;

    public static void main(String[] args)
        throws InterruptedException {

        String colorString="#ff0000";
        int ob1verts[]={10,10,50,50,30,80};
        **displayObject ob1=new displayObject("#ff0000", ob1verts);**
        int ob2verts[]={30,50,70,90,130,180,75,30};
        displayObject ob2=new displayObject("#00ff00", ob2verts);
        int ob3verts[]={10,10,70,50,70,80,110,130,30,30};
        displayObject ob3=new displayObject("#0000ff", ob3verts);

with this constructor:
  public class displayObject {

        //  Each object is defined by a color, number of vertices, and dim (2,3,4) coordinate vertex locations
        //  Use dim to verify that the right number of vertices were sent

            public static int dim=2;

            public String color;
            **public int noOfVerts**;
            public int coords [];

            public displayObject (String col, int verts[]){

                if (verts.length%dim != 0){
                    System.out.printf ("Crap in!");
                    return;
                }
                this.coords=new int[verts.length+2];
                color=col;
                **noOfVerts=verts.length/dim;**
                for (int cnt=0; cnt<verts.length; cnt++){
                    coords[cnt]=verts[cnt];
                }
                coords[verts.length]=verts[0];  //make last vertex equal first to close the shape
                coords[verts.length+1]=verts[1];
            }

    }

I've created a static variable that I would think would refer to a specific memory space for the object with an appropriate pointer.  Why is the object reference a Null Pointer?

A:
The object is instantiated here:
public static displayObject **ob1**, ob2, ob3;

No, that's not instantiating anything. It's declaring a variable, but it's just got its default value of null. At some point you need to assign a non-null value to it, e.g.
ob1 = new displayObject(...);

Now you have this line:
displayObject ob1=new displayObject("#ff0000", ob1verts);

... but that's not the same thing. That's declaring an entirely separate local variable, and giving that a value. It happens to have the same name (ob1) but it's a different variable. You possibly just need to change it to not be a local variable declaration:
ob1 = new displayObject("#ff0000", ob1verts);

... and ditto the other variables.
(As an aside, I'd strongly recommend avoiding non-private fields, and also starting to follow Java naming conventions.)


text:
Q: Django CSRF_COOKIE_DOMAIN - how to change gracefully I have a public Django site which uses CSRF protection.
I have not set the CSRF_COOKIE_DOMAIN. My site uses subdomains.
Sometimes, a user ends up having a csrftoken cookie set on .toplevel.com as well as on sub.toplevel.com. This causes problems, as CSRF checking fails if the wrong cookie is used in the check.
I would like to set a CSRF_COOKIE_DOMAIN to .toplevel.com. However, I would also like to delete any csrftoken cookies for any *.toplevel.com subdomains. How would I do this?
If I do not delete the other cookies, I will just end up in the original situation of having two cookies with the same name on different domains, which causes issues.

A: I had a similar problem. The way I dealt with it is together with CSRF_COOKIE_DOMAIN I also changed the CSRF_COOKIE_NAME, making old "csrftoken" cookies obsolete.


text:
Q: Bit fields in C for signed integer-struct num { int a:3; int b:2; int c:1; } I am getting confused with bit fields in C. Can anyone explain me the bit fields concepts or can anyone suggest me some good resources for understanding the basic concepts of bit fields in structures?
I have tried this program, but I cant understand the output.
In gcc 32 bit compiler
struct num
{
    int a:3;
    int b:2;
    int c:1;
};
void main()
{
    struct num n={8,-6,5};
    printf("%d\n%d\n%d",n.a,n.b,n.c);
}

Output: 0,-2,-1

A: Okay as you are a beginner, lets try to explain this..
The first one is int a : 3 which means that you are interested to store 3 bits, but in the main you are assigning the value 8..
Now the binary value of 8 is 1000 but as you are considering only 3 bits, the last 3 zeros(0) are taken & the output is 0
Now the second one is int b : 2 which means you are storing 2 bits. Now from the main you are writing -6. Now whenever any negative number is stored inside the memory, it is stored as 2's complement. Hence the binary value of 6 is 00000000 00000000 00000000 00000110 and because it is a negative number, hence the 1's complement is 11111111 11111111 11111111 11111001 and if you add 1 to it for 2's complement it will be    11111111 11111111 11111111 11111010..Now because you are taking only 2 bits in the structure, hence last to bits will be the answer which is 10 or 2 and because it was actually a negative number hence the output will be -2
Now the 31st bit of the memory is already set hence whatever the new number you will give, it will take as a negative..Now c is of 1 bit & in the main you give 5 which is basically 0101 & hence it will be last 1 bit & hence the answer will be -1...
Hence your compiler is behaving normally..

A: A bitfield is a "tiny" integer type for which you can directly specify the exact size in bits.  Bitfields can be used only inside structures.  The main uses for bitfields are (a) saving space in structures you'll have lots of copes of, and (b) attempting to confirm to externally-imposed storage layouts, e.g. device driver control-and-status registers or networking packets.
The code fragment you presented gives unexpected results because the number 8 (1000 in base 2) can't be represented in 3 bits, -6 cannot be represented in 2 bits, and 5 clearly cannot be represented in 1 bit.

A: Firstly, in bit-field declarations int does not necessarily mean signed int. In bit-field context signedness of plain int is implementation-defined. It is one context in C language when you have to explicitly say signed [int] if you want to ensure signedness of the stored value.
Secondly, apparently in your case int bit-fields happen to be signed, which means that on 2's-complement platform your bit-fields will have the following ranges

*

*a : [-4, 3]

*b : [-2, 1]

*c : [-1, 0]

You are assigning values that do not fit into these ranges, causing signed integer overflow. The outcome of signed integer overflow on assignment is implementation-defined. In your implementation the 2's-complement representation is apparently simply truncated to the number of available bits (least significant bits are taken).
For example, 8 is 1000 in binary, which leaves us with 000 after truncation to 3 bits. -6 is ...1111010 in 2's-complement binary, which leaves us with 10 after truncation, which in turn is -2. And so on.


text:
Q: How to use SharedPreferences to change view visibility in login and logout How to create SharedPreferences with set visibility in login if the user is successfully login the button will be logout and the login will be gone
public class Login extends ActionBarActivity implements View.OnClickListener{

    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    private static String url_check_login = "";
    private static final String TAG_SUCCESS = "success";
    Context cont=this;
    EditText uname, pword;
    Boolean nega = false;
    private Toolbar toolbar;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_user);

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        uname = (EditText) findViewById(R.id.uname);
        pword = (EditText) findViewById(R.id.pword);

        Button login = (Button)findViewById(R.id.btnLogin);
        login.setOnClickListener(this);
        Button register = (Button)findViewById(R.id.btnRegister);
        register.setOnClickListener(this);

    }

        @Override
        public void onClick(View v)
        {
            final int id = v.getId();
            switch (id) {
                case R.id.btnLogin:
                    new SubmitLogin().execute();
                    break;
                case R.id.btnRegister:
                    Intent i = new Intent (this, Registration.class);
                    startActivity(i);
                    finish();
                    break;
                // even more buttons here
            }
        }

    class SubmitLogin extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Logging In ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", uname.getText().toString()));
            params.add(new BasicNameValuePair("pass", pword.getText().toString()));
            JSONObject json = jsonParser.makeHttpRequest(url_check_login, "POST", params);
            Log.d("Create Response", json.toString());
            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    nega = false;
                    SharedPreferences prefs =   PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString("username", uname.getText().toString());
                    editor.commit();
                    Intent gotoLogs = new Intent(cont, MainActivity.class);
                    startActivity(gotoLogs);
                    finish();
                } else {
                    nega = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if (nega) {
                new AlertDialog.Builder(cont)
                        .setTitle("Login Failed")
                        .setMessage("Wrong Username or Password")
                        .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                //Close current activity
                startActivity(new Intent(this,MainActivity.class));
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

A: To place info into SharedPreferences you should write following:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();

Variables PREFERNCES_FILE and PREFERENCES_LOGIN should be defined as String:
public static final String PREFERNCES_FILE = "my_preferences_file";
public static final String PREFERENCES_LOGIN = "login";

On logout there should be:
sp.edit().remove(PREFERENCES_LOGIN).apply();

Then to check if there is allready some info call:
boolean isLogged = sp.contains(PREFERENCES_LOGIN);

Then just set needed visibility:
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);

UPDATE
Ok, here is example. This code should be in onCreate:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Button login = (Button)findViewById(R.id.btnLogin);
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
login.setOnClickListener(this);
Button logout = (Button)findViewById(R.id.btnLogout);
logout.setVisibility(isLogged ? View.VISIBLE : View.GONE);
logout.setOnClickListener(this);

And there should be button in your login_user xml with btnLogout id.
In onClick should be:
    @Override
    public void onClick(View v)
    {
        final int id = v.getId();
        switch (id) {
            case R.id.btnLogin:
                SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
                sp.edit().putString(PREFERENCES_LOGIN, login).apply();
                findViewById(R.id.btnLogin).setVisibility(View.GONE);
                findViewById(R.id.btnLogout).setVisibility(View.VISIBLE);
                //another actions after login
                break;
            case R.id.btnLogout:
                SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
                sp.edit().remove(PREFERENCES_LOGIN).apply();
                findViewById(R.id.btnLogin).setVisibility(View.VISIBLE);
                findViewById(R.id.btnLogout).setVisibility(View.GONE);
                //another actions after logout
                break;
            // even more buttons here
        }
    }

In login variable should be login data - I don't know where you should get it.


text:
Q: JWT Token doesn't want to expire My session is not expiring after use of authentication despite expiration time being set to 1 minute. Let me show you my code
JWT Token generator
            var claims = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserName)
                });
            var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claims,
                Expires = DateTime.Now.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);

Identiy configuration in Startup.cs
            services.AddIdentity<ApplicationUser, IdentityRole>(
                options =>
                {
                    options.SignIn.RequireConfirmedAccount = true;
                    options.Password.RequireDigit = true;
                    options.Password.RequireLowercase = true;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = true;
                    options.Password.RequiredLength = 6;
                    options.Password.RequiredUniqueChars = 1;
                }
                )
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

            var jwtSettings = GetJwtSettings(configuration);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret)),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });

Pipeline in Program.cs
var app = builder.Build();
app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

I use this kind of code to sign in
await _signInManager.PasswordSignInAsync(existingUser, request.Password, true, false);

My controller
        [HttpGet]
        public async Task<IActionResult> GetIsAuthenticated()
        {
            return Ok(User.Identity.IsAuthenticated);
        }

        [HttpGet("test")]
        [Authorize]
        public async Task<IActionResult> GetTest()
        {
            return Ok("OK");
        }

Calling GetIsAuthenticated and GetTest methods in api using Swagger and no formerly logging return respectively False and 404 Error. And then if I sign in with fully functioning user credentials using methods above I get True and OK responses. Thats great and what I really need.
But the problem is, after few minutes token/session is still active(reminding I it set to 1 minute). I can wait even hour and respond from the methods are still the same...
My code is not extraordinary so what is going on?

A: You can refer to this code:
private string GerarTokenJWT()
        {
            var issuer = _config["Jwt:Issuer"];
            var audience = _config["Jwt:Audience"];
            var expiry = DateTime.Now.AddMinutes(1);
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(issuer: issuer, audience: audience,
expires: expiry, signingCredentials: credentials);
            var tokenHandler = new JwtSecurityTokenHandler();
            var stringToken = tokenHandler.WriteToken(token);
            return stringToken;
        }

The specific demonstration effect can be seen in this post:
Swagger verification authority


text:
Q: Why does this resource fail to load yet Jquery loads fine Receiving the following error when I try to add javascript file in a directory:
Failed to load resource: the server responded with a status of 404 (Not Found)
The resource it's failing to load is a file called: formLogic.js
form.html, which is in the root directory.
<!DOCTYPE html>

If you click on me, I will disappear.

both the jQuery js file and formLogic file are in the directory js but formLogic.js fails to load where as jQuery loads fine. It only loads the resource when I move the formLogic.js to the root directory and change this script tag.

I don't understand why it's unable to load it from this directory yet can load the jQuery file.
formLogic.js contents:
$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});

A: Maybe it's because of the relative path!? Have you tried to use an absolute path?

Take care of the beginning slash.
Within my Projects I try to use those to avoid relative path Errors.
If that doesn't help, please tell me your application structure and where your document root is.


text:
Q: `will-change: opacity` doesn't create new stacking context in MDN web docs it is mentioned that stacking context is formed in these scenarios:

*Element with a opacity value less than 1

*Element with a will-change value specifying any property that would create a stacking context on non-initial value

but when I set will-change to opacity (non-initial value of less than 1) the stacking doesn't work as expected (blue div below red one), see this fiddle
some other scenarios works as expected like; blue div above red one (links to fiddles)

*Element with a position value absolute or relative and z-index value other than auto

*Element that is a child of a grid container, with z-index value other than auto
what am I doing wrong, and is there any other way to make stacking context works as expected
I'm asking because sometime I can't change the position to relative as this will affect the absolute children of that element

A: The stacking (creation of a new layer) is actually working.

The problem is that z-index works only for:

*

*Positioned elements (absolute, relative, fixed, sticky).

*Children elements of a flex container.

No matter if you set z-index: 30, at the end it will remain at its default value, auto.


text:
Q: How to limit email field to allow only 5 emails of specific domain which are separated by ; 1.I need to allow maximum of 5 emails in email field on edit as part of UI validation.
2.It should take all emails separated by ;
3.All emails should be under specific domain.
4.Looking in JavaScript or in ReactJS.

A: You can try something like this...
function checkValid(inputText) {

  if (
    inputText.split(";").length > 5 ||
    inputText.split(";").length !== inputText.split("@specific.domain").length - 1
  ) {
    // Show error
  } else {
    // Process emails
  }

}


text:
Q: "He gets awake " "He gets waken up" As with can use "get" with both "an adjective" and 'past participle". SO can i say "He gets awake = he awakes. He gets woken up= he wakes up.

A: No
"He gets woken" does not mean "he wakes up" but rather "someone awakens him". "He gets awake" sounds wrong to a native speaker. It might possibly mean "He becomes awake" or "he wakes up" as in

After the light shies on his face, he gets awake gradually.

but it is still a strained and unusual form, and i would strongly advise avoiding it.

*

*he stays awake

*he remains awake

*he keeps awake

all mean much the same thing.
The word "gets" usually means "receives" as in "he gets a gift" or else it indicates a process as in

*

*He gets down from the ladder.

*He gets defeated in the fight

*He gets married.

It is often part of a fixed phrase.
There are other ways to use "gets", of course. But "He gets awake" is not really one of them.
By the way if one uses the regular past form: "He gets waked" it probably means that he is dead and people gather to eat, droink, and talk in the room where his body is laid out. See "Wake" and "Finnegan's Wake"


text:
Q: Python string 'in' operator implementation algorithm and time complexity I am thinking of how the in operator implement, for instance
>>> s1 = 'abcdef'
>>> s2 = 'bcd'
>>> s2 in s1
True

In CPython, which algorithm is used to implement the string match, and what is the time complexity? Is there any official document or wiki about this?

A: It's a combination of Boyer-Moore and Horspool.
You can view the C code here:

Fast search/count implementation, based on a mix between Boyer-Moore and Horspool, with a few more bells and whistles on the top. For some more background, see: https://web.archive.org/web/20201107074620/http://effbot.org/zone/stringlib.htm.

From the link above:

When designing the new algorithm, I used the following constraints:

*

*should be faster than the current brute-force algorithm for all test cases (based on real-life code), including Jim Hugunin's worst-case test

*small setup overhead; no dynamic allocation in the fast path (O(m) for speed, O(1) for storage)

*sublinear search behaviour in good cases (O(n/m))

*no worse than the current algorithm in worst case (O(nm))

*should work well for both 8-bit strings and 16-bit or 32-bit Unicode strings (no O(σ) dependencies)

*many real-life searches should be good, very few should be worst case

*reasonably simple implementation


text:
Q: Horizonatal Scrolling in FlowDocumentScrollViewer I have a flow document with images (created from drawings). I have provided a button for the user to enlarge the images (zoom) independently without zooming the text.
Is there anyway, I can force the FlowDocumentScrollViewer to display a horizontal scrollbar for scrolling when the images are enlarged? Currently, the enlarged images are simply clipped off.
Best regards,
Paul.

A: Found the answer, setting the PageWidth of the document does the trick.


text:
Q: Is OpenSSH sending an email to no-more-sessions@openssh.com every time I connect? When I try to connect to my EC2 (Ubuntu 14.04.3) server with ssh -v server, I see this at the end of the log:
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
Authenticated to <domain>.com ([192.168.1.42]:12345).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com  # <!-!-!-!-!-!- What's this?
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_CTYPE = en_US.UTF-8
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-55-generic x86_64)

This is my .ssh/config:
Host server
  HostName domain.com
  User myuser
  IdentityFile ~/path/to/EC2Key.pem
  Port <portnumber>

Which seems normal. I can see two possible reasons here:

*

*OpenSSH is trying to make a connection to openssh.com as a user no-more-sessions - but that doesn't make any sense either, why?

*OpenSSH is trying to send email to no-more-sessions@openssh.com. This makes even less sense, and both options seem a little creepy.

What's happening here?

A: No, that's not an email address. The something@domain syntax is used in many other places, and SSHv2 uses it for naming all "nonstandard" extensions (ciphers, subsystems, and so on).
So this particular request has @openssh.com because it was invented by OpenSSH, and hasn't been made part of the "main" standard documents.
Its purpose is explained in the OpenSSH 5.1 release notes:

*

*Added a no-more-sessions@openssh.com global request extension that is
  sent from ssh(1) to sshd(8) when the client knows that it will never
  request another session (i.e. when session multiplexing is disabled).
  This allows a server to disallow further session requests and
  terminate the session in cases where the client has been hijacked.


text:
Q: Detecting tiled map layer collision in cocos2d-x i am new in cocos2d-x3.2 and i am creating a tile based game something like mario. I created a tile map with a collidable layer . but when I am using Dictionary *properties; then its showing error in dictionary . So what can I use for detecting the collision?
Point tileCoord = this->tileCoordForPosition(position);

int tileGid = CollisionLAyer->tileGIDAt(tileCoord);

if (tileGid) {

    Dictionary *properties;
    properties = _tileMap->propertiesForGID(tileGid);
    if (properties) {
        String *collision = new CCString();
        *collision = *properties->valueForKey("Collidable");
        if (collision && (collision->compare("True") == 0)) {
            return;
        }
    }

A: With 3.2 I believe the properties are created in a ValueMap.
Value properties = this->getPropertiesForGID(0);
if (! properties.isNull())
{
    ValueMap dict = properties.asValueMap();
    Value collision = dict["Collidable"];
    if (! collision.isNull() && collision.asString() == "True") {
        return;
    }
}

You can also use an additional tile layer if you want and for example use a red semi-transparent single tile tileset. Draw over all tiles that should be collision tiles. Then  you can check if the gid on that layer is > 0 for collisions.


text:
Q: Post request in PHP to textfile What I want is to call for instance /?Hello and then the PHP program to upload "Hello" to the textfile.
<?php
    $sqldata = array (serialize($_REQUEST), $_SERVER['PHP_AUTH_USER']);
    file_put_contents('textfile.txt', $sqldata);
?>

If this is called, it comes out like this:
a:7:
{
    s:4:"Hello";
    s:0:"";
    s:8:"__cfduid";
    s:43:"d1e090c0f439f6aa6bad2e7b18dd9dc701473462630";
    s:9:"PHPSESSID";
    s:32:"6d602111da31b9a1646fa11d3c3c7e72";
    s:8:"cvo_sid1";s:12:"KTVET3PF62UB";
    s:9:"utag_main";
    s:197:"v_id:0157856889ad001e67d2f49d3db10206d006e06500918$_sn:1$_ss:0$_pn:2;exp-session$_st:1475413904309$ses_id:1475412003245;exp-session$dc_visit:1$dc_event:2;exp-session$dc_region:eu-west-1;exp-session";
    s:8:"cvo_tid1";
    s:38:"Bkbwvk_D0Uc|1475412341|1475412443|-337";
    s:12:"cf_clearance";
    s:60:"20d986c985fb1cbab15f286ed34cc09d79c7fb06-1475683723-31536000";
}

I then tried this, hoping it would take out only the part that says "Hello"
<?php
    $sqldata = array (serialize($_REQUEST), $_SERVER['PHP_AUTH_USER']);
    $myarray[array ]['4'];
    file_put_contents('textfile.txt', $myarray);
?>

My end objective, is to request something just like /?Hello and have just that uploaded to the text file.

A: What you are doing when you request a page with just ?Hello is actually setting the key "Hello" without a content, which would be the same as ?Hello=
You can test for this by using the following code:
<?php
if ( isset($_REQUEST['Hello']) ) {
    // Write stuff to the file.
}

If you don't want it to be triggered when a POST variable Hello is present, change the $_REQUEST to a $_GET

A: I am assuming that you do not know the exact key in advance and "Hello" can actually be anything.
In that case, you can use array_keys() to access keys of any array. So in this case, you want to access keys of $_GET. so something like:
$arrKeys = array_keys($_GET)

will give you all the keys. You can then save them to a file.


text:
Q: how to add Class to a template directive element? i'm new to AngularJs Directive.
what i'm trying to do is , i need to add a simple class into one of my elements in template directive on click.
for example:

var app = angular.module("peykaar",[]);

app.controller('main', function($scope , $rootScope) {

$scope.arry = ["Apple","banana","orange"];

});

app.directive("customCheckbox", function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {
            name:"@"
        },
        link: function(scope, element, attrs){

            var logic = {
                init: function(elem){
                    var self = this;
                    elem.on('click', function(){
                        if ( elem.hasClass('tik')){
                            self.unTik(elem);
                        } else if ( elem.hasClass('untik') ) {
                            self.tik(elem);
                        }
                    });
                },
                tik: function(elem){
                    elem.addClass('custom_checked tik');
                    elem.removeClass('untik');
                },
                unTik:function(elem){
                    elem.removeClass('custom_checked tik');
                    elem.addClass('untik');
                }
            };

            logic.init(element);

        },
        template: '

{{name}}

'
    }
});

so how can i add Class using element.addClass("checked") to span class="custom_checkbox"

A: You can use ng-class to fix. Declare a onClick and assign true while clicking.
For example
Var onClick = true;


text:
Q: Correct link break for mobile with font awesome (HTML, CSS) I have an ordered list with a font awesome icon. I want to let it break correctly.
My code:
https://codepen.io/altos/pen/BragXj
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Link 1 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 2 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 3 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 4 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

My goal:

A: I would add padding to the li and then absolutely position the number and arrows using before and after on the li:

ol {
  padding-left: 0;
  counter-reset: item;
  list-style-type: none;
}

ol li {
  position: relative;
  padding-left: 3em;
  line-height: 20px;
  /* match font size of font awesome icon */
}

ol li:before {
  content: counter(item, decimal-leading-zero) " ";
  counter-increment: item;
  display: inline-block;
  position: absolute;
  left: 0;
}

ol li:after {
  color: #E3000B;
  padding-right: 8px;
  font-size: 20px;
  font-family: FontAwesome;
  content: "";
  display: inline-block;
  position: absolute;
  left: 1.2em;
  top: -0.1em;
  /* seems to vertically align icon to number better */
}

a {
  text-decoration: none;
  display: inline-block;
  position: relative;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Link 1 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 2 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 3 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr

Link 4 - Lorem ipsum dolor sit amet, consetetur sadipscing elitr


text:
Q: Comparing two variables at different times I'm new to Android application development, would like to compare different variables over time.
My Service counts the number of SMS inside the smart-phone.
private static final Uri SMS_URI_ALL = Uri.parse("content://sms/");
final List<String> messages = new ArrayList<>();
    String id;

    final Cursor cursor = getContentResolver().query(SmsReader.SMS_URI_ALL,null, null,null, null);
    assert cursor != null;
    if (cursor.moveToFirst()){
        do {
            id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
            messages.add(id);
            currentMessage = messages.size();
        } while (cursor.moveToNext());

    }
    if (! cursor.isClosed()){
        cursor.close();
}

Every 15 mins service will be starts, and I would like to compare the value of "currentMessage" and calculate the difference between the old value of "currentMessage" and the new value of "currentMessage" for know how many message I have sent, received during this period of 15min
I don't know how to implement it, can you help me please

A: Store the count in database, also you cannot exactly monitor the count this way. Add broadcast receiver for when a sms is sent or received.

A: I found an other solution, I save the value inside a file, and I compare the current value whith the older value


text:
Q: I need to understand the Lorentz transformation Two observers A and B, in different initial system describe the same physical event with their particular, different space time coordinates . Let the coordinate of the event be $x^\mu$ for observer A and ${x^\prime}^\mu$ for observer B .Both coordinates are connected by means of the Lorentz transformation.
$${x^\prime}^\mu = \sum_{\mu=0}^{3}a^{\nu}_{\mu}x^\mu\equiv a^{\nu}_{\mu}x^\mu\ = (\hat{a}\overset{\Rightarrow}{x})$$
Where $\hat{a}$ denotes the abbreviated version of the transformation matrix and $\overset{\Rightarrow}{x}$ is a 4 dimensional world vector .
I need to understand the Lorentz transformation equation that how it transformed .
EDITED :
How both coordinates are connected in that transformation .


text:
Q: How can I see all terraform variables? Is there a way to see all variables a stack is spun up with? In my case, we have several workspaces with several variables set by another engineer.
I'm trying to work out if there's a way I can print them out as some are causing errors in terraform plan.


text:
Q: Asymptotic behavior of recursive sequence Suppose, the real sequence
$x_{n+1}=\frac{1}{2}(x_n+\sqrt{x_n^2+c})$ with c>0 is given.
Find the asymptotic behavior of this sequence.
I have shown, that this sequence goes to infinity as $n\to\infty$ per contradiction. I guess, that it holds
$x_n \approx \frac{1}{2}\sqrt{cn}$
which is motivated by
$x_{n+1}^2=\frac{1}{2}x_n^2(1+\sqrt{1+\frac{c}{x_n}})+\frac{1}{4}c \approx x_n^2 + \frac{1}{4}c$
where I used the approximation $\sqrt{1+\frac{c}{x_n}} \approx 1$ as $n \to \infty$.
I have problems, to turn this into a formal proof, since it holds for the error term for my approximation
$\frac{1}{2}x_n^2(1-\sqrt{1+\frac{c}{x_n}}) \to \infty$

A: If we set $y_n=x_n^2$ then
$$y_{n+1}=\frac{y_n}2+\frac c4+\frac{y_n}2\sqrt{1+\frac{c}{y_n}}=y_n+\frac{c}2+O(y_n^{-1}).$$
This proves that $(y_n)$ grows at least linearly, so that $y_n^{-1}=O(n^{-1})$.
Therefore
$$y_n=\frac{cn}2+O(\ln n)$$
and
$$x_n=\sqrt{\frac{cn}2}+O\left(\frac{\ln n}{\sqrt n}\right).$$

A: You've already derived that
\begin{align}
x_{n+1}^2 - x_n^2 &= \frac 12 \left(\sqrt{1 + \frac{c}{x_n^2}} -1 \right) + \frac c4 \\
&= \frac{c}{2x_n^2} \frac{1}{\sqrt{1 + \frac{c}{x_n^2}} +1} + \frac c4.
\end{align}
Taking $n \to \infty$ we obtain
\begin{equation}
\lim\limits_{n\to\infty}\left[x_{n+1}^2 - x_n^2 \right] = \frac c4.
\end{equation}
Let $\epsilon > 0$ be arbitrary. Then there exists $N \in \mathbb{N}$ such that for all $n \geq N$ it holds that
\begin{equation}
\left| x_{n+1}^2 - x_n^2 - \frac c4\right| < \epsilon.
\end{equation}
We can then write
\begin{align}
\left|\frac{x_n^2}{n} - \frac c4\right| &= \left|\frac{(x_n^2 - x_{n-1}^2 - \frac c4) + ... + (x_{N+1}^2 - x_N^2 - \frac c4)}{n} + \frac{x_N^2}{n} - \frac{cN}{4n}\right| \\
&\leq \frac{(n-N)\epsilon}{n} + \frac{x_N^2}{n} + \frac{cN}{4n}.
\end{align}
Taking $n \to \infty$ yields
\begin{equation}
\limsup\limits_{n \to \infty} \left|\frac{x_n^2}{n} - \frac c4 \right| \leq \epsilon.
\end{equation}
As $\epsilon$ was arbitrary we get
\begin{equation}
\lim\limits_{n \to \infty} \frac{x_n^2}{n} = \frac c4
\end{equation}
as desired.


text:
Q: Qual a melhor abordagem para entidades destintas com informações semelhantes e também diferentes? Estou fazendo um projeto que consiste em duas entidades: aluno e psicólogo. Ambos tem informações em comum, como: login, nome, sobrenome, idade, contato, endereço. Ambas as entidades também tem informações diferentes, como: aluno: matrícula, curso, semestre de ingresso; psicólogo: registro, crp, etc.
A princípio eu não queria criar duas tabelas diferentes com as mesmas coisas para ambos, por isso abstrai ao máximo e criei algo semelhante ao diagrama abaixo:

Porém, minha questão se é possível melhorar essa pegada. Como acabei criando duas tabelas para colocar as informações específicadas de cada entidade a tabela de cargos parece inútil.

A: É mais ou menos isso mesmo, o termo para o técnico para a modelagem que você esta fazendo é 'especialização ou generalização'.
https://sites.google.com/site/uniplibancodedados1/aulas/aula-9---generalizacao-e-especializacao
O detalhe é que você pode tornar o id do estudante, ou do psicólogo uma chave estrangeira para a entidade user, isso vai facilitar sua vida quando quiser pesquisar por todos os usuários, ou usuários com uma a outra característica.
p.s.: ia postar essa resposta como comentário mas ainda sou usuário novo por aqui.


text:
Q: Unable to process http delete request using powershell curl command PS C:\> $postParams = @{eventId='235'}
PS C:\> curl -Method DELETE -Uri http://localhost:8080/eventlist/api/v1/events -Body $postParams
curl : Error deleting event
At line:1 char:1
+ curl -Method DELETE -Uri http://localhost:8080/eventlist/api/v1/events -Body $po ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], Web
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

However, if I am trying to delete like
curl -Method DELETE -Uri http://localhost:8080/eventlist/api/v1/events?eventId=235

it works
Why is not working in the first way using $postParams ?

A: This is not working

    PS C:\Users\> $postParams = "{eventId='$eventId'}"
    PS C:\Users\> Invoke-WebRequest -Method POST -Uri "http://localhost:8080/eventlist/api/v1/events" -Body $postParams

Invoke-WebRequest : Error creating event
At line:1 char:1
+ Invoke-WebRequest -Method POST -Uri "http://localhost:8080/eventlist/api/v1/even ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

This is working
PS C:\> Invoke-WebRequest -Method DELETE -Uri 'http://localhost:8080/eventlist/api/v1/events?eventId=235'

StatusCode        : 200
StatusDescription : OK
Content           : Event deleted successfully
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 26
                    Content-Type: text/plain;charset=ISO-8859-1
                    Date: Mon, 20 Feb 2017 12:27:46 GMT
                    Server: Apache-Coyote/1.1

                    Event deleted successfully
Forms             : {}
Headers           : {[Content-Length, 26], [Content-Type, text/plain;charset=ISO-8859-1], [Date, Mon, 20 Feb 2017
                    12:27:46 GMT], [Server, Apache-Coyote/1.1]}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 26

A: EDIT
It's failing because DELETE isn't a POST command.
The code below is untested.
To recreate the DELETE in PowerShell, your syntax needs to be:
$eventId=235
Invoke-WebRequest -Method DELETE -Uri "http://localhost:8080/eventlist/api/v1/events?eventId=$eventId"

ORIGINAL POST
This relates to the commandline app curl, not the PowerShell curl which is an alis for Invoke-WebRequest
It's failing for two reasons, The first one is that DELETE isn't a POST command. The second, is that you're trying to pass a PowerShell object into a commandline application.
The code below is untested.
To recreate the DELETE in PowerShell, your syntax needs to be:
$eventId=235
&curl -Method DELETE -Uri "http://localhost:8080/eventlist/api/v1/events?eventId=$eventId"

A POST command could be like this (depending on your endpoint):
$eventId=235
$postParams = "{eventId='$eventId'}"
&curl -H "Content-Type: application/json" -X POST -d $postParams 'http://localhost:8080/eventlist/api/v1/events'

Note, the body is a json string, not a PowerShell object.


text:
Q: how can java subscriber monitor salesforce platform events I have a custom object called AdobeMeeting__c and platform event Meeting__e. If I did the changes in AdobeMeeting__c object,I need to push the notification to my external system(java subscriber  ).
For that I have created a trigger on AdobeMeeting__c object and it push the changes to platform event Meeting__e.
But here my questions

*

*how can Java subscriber monitor salesforce platform events which are in EventBus.

*how salesforce knows java subscriber received platform event messages successfully and is there any messages Sitting in EventBus.

*lets say saleforce published platform event messages to Java subscriber. but Java subscriber connection down for 1 day and not able receive platform event messages . now how can i monitor that messages which are in Eventbus

Can any One tell me the flow how can I achieve this.

A: Firstly, you may wish to use Change Data Capture instead, as it posts change events for you with no need for custom code in an Apex trigger. This appears to be a textbook use case for CDC.

how can Java subscriber monitor salesforce platform events which are in EventBus.

Salesforce provides example code. I'd recommend reviewing the Platform Events Developer Guide and specifically the Example: Subscribe to and Replay Events Using a Java Client (EMP Connector)

how salesforce knows java subscriber received platform event messages successfully and is there any messages Sitting in EventBus.

Salesforce doesn't track the receipt status of each subscriber for each event message. It is the responsibility of the subscriber to process messages and to take advantage of the replay functionality to request re-delivery (see below).

lets say saleforce published platform event messages to Java subscriber. but Java subscriber connection down for 1 day and not able receive platform event messages . now how can i monitor that messages which are in Eventbus

The event bus is not a persistent store. Salesforce provides a 24-hour replay window during which a subscriber can request that events are re-delivered to cope with such a connectivity gap.
Detailed information about how replay works is in the Streaming API Message Durability documentation. From that document:

A subscriber can choose which events to receive, such as all events within the retention window or starting after a particular event. The default is to receive only the new events sent after subscribing. Events outside the 24-hour retention period are discarded.

When your client reestablishes a connection to the server, it can request to have the entire retention window redelivered to it, or request all events subsequent to a specific replay Id that it previously received. Detailed examples are in the above documentation.


text:
Q: How to sanitize X-Editable value *before* editing? I'm using X-Editable to give users the possibility to edit values inline. This works great, but I now want to use it for some money values which are localized in a "European way" (e.g.: € 12.000.000,00). When I click edit, I want the input to only contain 12000000 though.
Is there a way that I can sanitize the value in X-editable before it gets displayed in the X-Editable input? All tips are welcome!

A: See the plunker http://plnkr.co/edit/Vu78gRmlKzxrAGwCFy0b. From X-editable documentation it is evident you can use value property of configuration to format the value you want to send to the editor as shown below.
Element displaying money value in your HTML:
 12.000.000,00

Javascript code in your HTML:

If you want to format the value back for display after editing you can do that in display property of the configuration hash like this:
           $('#money').editable({
                type: 'text',
                pk: 1, //Whatever is pk of the data
                url: '/post', //Post URL
                title: 'Enter money', //The title you want to display when editing
                value:function() {
                     return $('#money').text().replace(/\./g, '').replace(/,00$/,'');
                },
                display:function(value) {
                     //var formattedValue = formatTheValueAsYouWant(value);
                     //$('#money').text(formattedValue);
                }
           });

A: Seems like there is no callback function available for what you want.
so You need to make it outside of the library.
here is how to do it.
$(document).on("focus",".form-control.input-sm",function(){
  //remove all characters but numbers
  var _val = $(this).val().match(/\d/g).join("");
  //set it.
  $(this).val(_val);
});

replace the part of .form-control.input-sm into your case.
I just tested this on the library's demo site's first demo fieled named "Simple text field" with chrome developper tools
http://vitalets.github.io/x-editable/demo-bs3.html
Since x-editable form would be generated right before showing up.You need to hook an event to document and wait for input field inside of x-editable form gets focus which is the time x-editable shows up and edit the value into whatever you want.
and Yes, This method works AFTER the input field shows up but It's hardly possible to notice that value is changing after it gets displayed.


text:
Q: Accumulating previous rows with grouping I have this table on MS SQL Server
Customer    Month    Amount
-----------------------------
Tom         1        10
Kate        1        60
Ali         1        70
Tom         2        50
Kate        2        40
Tom         3        80
Ali         3        20

I want the select to get accumulation of the customer for each month
Customer    Month    Amount
-----------------------------
Tom         1        10
Kate        1        60
Ali         1        70
Tom         2        60
Kate        2        100
Ali         2        70
Tom         3        140
Kate        3        100
Ali         3        90

Noticing that Ali has no data for the month of 2
and Kate has no data for the month of 3
I have done it but the problem is that for the missing month for each customer  no data shows
i.e. Kate has to be in month 3 with 100 amount
and Ali has to be in Month 2 with 70 amount
declare @myTable as TABLE   (Customer varchar(50), Month int, Amount int)
;

INSERT INTO @myTable
    (Customer, Month, Amount)
VALUES
    ('Tom', 1, 10),
    ('Kate', 1, 60),
    ('Ali', 1, 70),
    ('Tom', 2, 50),
    ('Kate', 2, 40),
    ('Tom', 3, 80),
    ('Ali', 3, 20);

select * from @myTable

select
    SUM(b.Amount),a.Customer, a.Month
from
    @myTable a
        inner join
    @myTable b
        on a.Customer = b.Customer and
            a.Month >= b.Month
group by
    a.Customer, a.Month

A: Use window function
select Customer, Month,
       sum(Amount) over (partition by customer order by month) Amount
from table t

So, you want some kind of look up tables which has possible months with customers.
with cte as
(
     select * from (
        select Customer from table
        group by Customer)c
     cross join (values (1),(2),(3))a(Months)
) -- look-up table

select c.Customer, c.Months,
       sum(t.Amount) over (partition by c.Customer order by c.Months) Amount
from cte c left join table t
      on t.Month = c.Months and t.Customer  = c.Customer

Result :
Customer Months Amount
Tom      1      10
Kate     1      60
Ali      1      70
Tom      2      60
Ali      2      70
Kate     2      100
Ali      3      90
Kate     3      100
Tom      3      140

A: with cte as
(select *
 from
  (select distinct customer from myTable ) c
  cross join ( values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) t(month))

select cte.customer, cte.month,
sum(myTable.amount) over (partition by cte.customer order by cte.month) as cumamount
from cte left join myTable
on cte.customer = myTable.customer and cte.month = myTable.month
order by  cte.month, cte.customer desc

A: Do you want get the sum amount every month for each customer , what ever the customer has transaction in that month?
In following script, If you have a customer table, you can join the customer table, do not need use (SELECT DISTINCT Customer FROM @myTable)
declare @myTable as TABLE   (Customer varchar(50), Month int, Amount int);
INSERT INTO @myTable(Customer, Month, Amount)
VALUES
    ('Tom', 1, 10),
    ('Kate', 1, 60),
    ('Ali', 1, 70),
    ('Tom', 2, 50),
    ('Kate', 2, 40),
    ('Tom', 3, 80),
    ('Ali', 3, 20),
    ('Jack', 3, 90);

    SELECT c.Customer,sv.number AS Month ,SUM(CASE WHEN t.Month<=sv.number THEN t.Amount ELSE 0 END ) AS Amount
    FROM master.dbo.spt_values AS sv
    INNER JOIN (SELECT DISTINCT Customer FROM @myTable) AS c ON 1=1
    LEFT JOIN @myTable AS t ON t.Customer=c.Customer
    WHERE sv.type='P' AND sv.number BETWEEN 1 AND MONTH(GETDATE())
    GROUP BY sv.number,c.Customer
    ORDER BY c.Customer,sv.number

----------

Customer                                           Month       Amount
-------------------------------------------------- ----------- -----------
Ali                                                1           70
Ali                                                2           70
Ali                                                3           90
Jack                                               1           0
Jack                                               2           0
Jack                                               3           90
Kate                                               1           60
Kate                                               2           100
Kate                                               3           100
Tom                                                1           10
Tom                                                2           60
Tom                                                3           140

A: Try this the table name is "a".
Using a combination of Cte and sub query. Tried it out in  MSSQL2008R2
 with cte as
(
 select * from (
    select Customer from a
    group by Customer)c
 cross join (values (1),(2),(3),(4),(5),(6),(7),(8),(9), (10),(11),(12))a(Months)
)
select  Customer,Months,

(select  SUM(total) from
(select customer , month , sum(amount)as total from a   group by  customer,
month) as GroupedTable
where GroupedTable.customer= cte.customer and  GroupedTable.month<= cte.Months) as total
  from cte
Group by  Customer,Months
order by Customer,Months

A: try this:
        create table #tmp (Customer VARCHAR(10), [month] INT ,Amount INT)
    INSERT INTO #tmp
    SELECT 'Tom',1,10
    union all
    SELECT 'Kate',1,60
    union all
    SELECT 'Ali',1,70
    union all
    SELECT 'Tom',2,50
    union all
    SELECT 'Kate',2,40
    union all
    SELECT 'Tom',3,80
    union all
    SELECT 'Ali',3,20

    ;WITH cte1 AS (
        SELECT [month], ROW_NUMBER() OVER(order by [month] desc) rn
        FROM (SELECT DISTINCT [month] as [month] FROM #tmp) a
        )
    , cte2 AS (
        SELECT customer, ROW_NUMBER() OVER(order by customer desc) rn
        FROM (SELECT DISTINCT customer as customer FROM #tmp) b
        )

    SELECT t2.Customer,t2.[month],ISNULL(t1.Amount,0) As Amount
    into #tmp2
    from #tmp t1
    RIGHT JOIN
    (select [month],customer from cte1
    cross apply
    cte2) t2 ON t1.customer=t2.customer and t1.[month]=t2.[month]
    order by t2.[month]

    SELECT Customer,[Month] ,SUM (Amount) OVER(partition by customer order by customer ROWS UNBOUNDED PRECEDING ) as Amount
    FROM #tmp2
    order by [month]

    drop table #tmp
    drop table #tmp2

A: to be clear(in answer Amount and AmountSum)
DECLARE @myTable TABLE(Customer varchar(50), Month int, Amount int);

INSERT INTO @myTable(Customer, Month, Amount)
VALUES
    ('Tom', 1, 10),
    ('Kate', 1, 60),
    ('Ali', 1, 70),
    ('Tom', 2, 50),
    ('Kate', 2, 40),
    ('Tom', 3, 80),
    ('Ali', 3, 20);

DECLARE @FullTable TABLE(Customer varchar(50), Month int, Amount int);

INSERT INTO @FullTable(Customer, Month, Amount)
SELECT c.Customer, m.Month, ISNULL(mt.Amount, 0)
FROM (SELECT DISTINCT [Month] FROM @myTable) AS m
CROSS JOIN (SELECT DISTINCT Customer FROM @myTable) AS c
LEFT JOIN @myTable AS mt ON m.Month = mt.Month AND c.Customer = mt.Customer

SELECT t1.Customer, t1.Month, t1.Amount, (t1.Amount + ISNULL(t2.sm, 0)) AS AmountSum
FROM @FullTable AS t1
CROSS APPLY (SELECT SUM(Amount) AS sm FROM @FullTable AS t WHERE t.Customer = t1.Customer AND t.Month < t1.Month) AS t2
ORDER BY Month, Customer

A: I think this does what you want
declare @myTable as TABLE   (Customer varchar(50), Month int, Amount int);
INSERT INTO @myTable (Customer, Month, Amount)
VALUES
    ('Tom', 1, 10),
    ('Kate', 1, 60),
    ('Ali', 1, 70),
    ('Tom', 2, 50),
    ('Kate', 2, 40),
    ('Tom', 3, 80),
    ('Ali', 3, 20);

 select dts.Month, cts.Customer, isnull(t.Amount, 0) as Amount
      , sum(isnull(t.Amount, 0)) over(partition by cts.Customer order by dts.Month) as CumAmt
  from ( select distinct customer
                from @myTable
       ) cts
  cross join ( select distinct Month
                from @myTable
             ) dts
  left join @myTable t
    on t.Customer = cts.Customer
   and t.Month = dts.Month
 order by dts.Month, cts.Customer;

Month       Customer                                           Amount      CumAmt
----------- -------------------------------------------------- ----------- -----------
1           Ali                                                70          70
1           Kate                                               60          60
1           Tom                                                10          10
2           Ali                                                0           70
2           Kate                                               40          100
2           Tom                                                50          60
3           Ali                                                20          90
3           Kate                                               0           100
3           Tom                                                80          140

A: Try Sum Over Partition By
https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql
This will help you get the idea how to accumulate. If the code i use in postgresql like this
Select sum(amount) over(partition by customer, month)

A: This should do it for you. Also here is a link to the Microsoft docs regarding aggregation functions.
https://learn.microsoft.com/en-us/sql/t-sql/functions/aggregate-functions-transact-sql
Example:
SELECT
    Customer, Month, SUM(Amount) as Amount
FROM myTable
    GROUP BY Customer, Month
    ORDER BY Customer, Month


text:
Q: Adding buttons on tableview - can't access the sender I have used the following code to add buttons to my tableviewcell , when the button is pressed i need to know which row was it. so i have tagged the buttons (playButton viewWithTag:indexPath.row)
The problem is that is if I define the target action method (play) to receive the sender it crashes with  "unrecognized selector ", any ides how to know on which row the button was pressed or why it is crashing like this
Thanks
-(void)configureCell: (UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[playButton setFrame:CGRectMake(150,5,40,40)];
[playButton viewWithTag:indexPath.row] ; //Tagging the button
[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];
[cell addSubview:playButton];

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *beatCell = nil;
beatCell = [tableView dequeueReusableCellWithIdentifier:@"beatCell"];
if (beatCell == nil){
    beatCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"beatCell"];
}
 [self configureCell:beatCell atIndexPath:indexPath];
return beatCell;

}
-(void) play:(id) sender{
UIButton *play = sender;
NSLog(@"Play %i" , play.tag);

}

A: Change one character of this line:
[playButton addTarget:self action:@selector(play) forControlEvents: UIControlEventTouchUpInside];

to
[playButton addTarget:self action:@selector(play:) forControlEvents: UIControlEventTouchUpInside];

When you include parameters on a selector, the colon actually does matter for the Objective C runtime to be able to look up that selector on the object you're targeting.

A: Instead of
[playButton viewWithTag:indexPath.row] ;

Where you try to receive a subView of UIButton (i dont know why), you should set tag using setter method :
[playButton setTag:indexPath.row];

You also must cast your sender to UIButton type
-(void) play:(id) sender{
UIButton *play = (UIButton *)sender;
NSLog(@"Play %i" , play.tag);
}


text:
Q: Android How to pass value in this asynctask? how to pass a Value from edittext to this asynctask (do in background)?
public class connectTask extends AsyncTask<String,String,TCPClient> {
    @Override
    protected TCPClient doInBackground(String... message) {
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            public void messageReceived(String message) {
                publishProgress(message);
            }
        });
        mTcpClient.run(MY_PASSED_VALUE);
        return null;
    }

A: got it!
public class connectTask extends AsyncTask<String,String,TCPClient> {
    @Override
    protected TCPClient doInBackground(String... message) {
        String myip = message[0];

        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            public void messageReceived(String message) {
                publishProgress(message);
            }
        });
        mTcpClient.run(myip);
        return null;
    }


text:
Q: Send data to fragment with FragmentTransaction I'm in my fragment class calling this:
@OnClick(R.id.blockedLinkLayout)
public void onBlockedClick(){
    final FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.content, new SettingsBlockedUsersFragment(), FRAGMENT_TAG);
    ft.commit();
}

And it just replace my current fragment with chosen one.
And my question is, how can I send some data (e.g. String value) from my parent fragment to my child fragment using FragmentTransaction?

A: FragmentTransaction is simply to transition Fragments, it doesn't "pass" anything. You need to use a Bundle.
SettingsBlockedUsersFragment frag = new SettingsBlockedUsersFragment();
Bundle b = new Bundle();
// put stuff into bundle...
b.putString("user", "steve");

// Pass the bundle to the Fragment
frag.setArguments(b);

// Use Fragment Transaction
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, frag, FRAGMENT_TAG);
ft.commit();

Then inside the onCreate of the Fragment, you can do
String user = getArguments().getString("user");

Other ways to pass data into a Fragment are discussed at Best practice for instantiating a new Android Fragment

A: Just pass them in a bundle as fragment arguments
in parent fragment :
SettingsBlockedUsersFragment fragment = new SettingsBlockedUsersFragment();
Bundle arguments = new Bundle();
arguments.putString( string_key , desired_string);
fragment.setArguments(arguments);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, fragment , FRAGMENT_TAG);
ft.commit();

in child fragment :
Bundle arguments = getArguments();
String desired_string = arguments.getString(string_key);

A: you can use a factory method in your fragment class(as recommended in the docs)
public static YourFragment newInstance(String sample) {
    YourFragment fragment = new YourFragment();
    Bundle args = new Bundle();
    args.putString(KEY, sample);
    fragment.setArguments(args);
    return fragment;
}

then call YourFragment.newInstance("string you need to pass"); to get an instance of your fragment and use that in your transaction.
The key here is actually using the setArguments() method to pass in data.
you can then retrieve this data in your fragment's oncreate method like this
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        streamSource = getArguments().getParcelable(KEY);
    }
}

A: In your SettingsBlockedUsersFragment class have a static method like the following
public class SettingsBlockedUsersFragment extends Fragment {
    private static final String MY_STRING = "my_string";

    public static SettingsBlockedUsersFragment newInstance(String yourStringValue){
        SettingsBlockedUsersFragment frag = new SettingsBlockedUsersFragment();
        Bundle args = new Bundle();
        args.putString(MY_STRING, yourStringValue);
        frag.setArguments(args);
        return frag;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState){
          Bundle args = getArguments();
          if(args != null){
               String myString = args.getString(MY_STRING);
          }
    }
}

In your fragment transaction you can pass the args like this
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content,SettingsBlockedUsersFragment.newInstance("my string"), FRAGMENT_TAG);
ft.commit();


text:
Q: Trigger a click on previous sibling with Jquery I would like to trigger a click on a checkbox when the text next to the checkbox is clicked ("Finance department" or "Sales department" in the snippet).
I have tried with both jquery and javascript but any of those two seem to work:
$(prevsibling).children().click();
$(prevsibling).children().trigger("click");

Please find attached a snippet with the code.
Any clue ?
Thanks a lot

$(document).mouseup(function(e) {

  clickeditem = $(e.target);

  if (clickeditem.hasClass('checkboxinfotd')) {
    prevsibling = $(clickeditem).prev()[0];
    $(prevsibling).children().click();

  } else if (clickeditem.hasClass('checkboxtd') || clickeditem.hasClass('checkbutton')) {
    if (clickeditem.hasClass('checkboxtd')) {
      clickeditem = clickeditem.children()[0];
    } else if (clickeditem.hasClass('checkbutton')) {

    } else {

    }

    console.log("clicked on checkbox");
    thirdclass = clickeditem.attr('class').split(' ')[2];

    if (thirdclass === "fa-square-o") {
      newclass = 'fa-check-square-o';
      clickeditem.removeClass("fa-square-o");
      clickeditem.addClass(newclass);

    } else if (thirdclass === "fa-check-square-o") {
      newclass = 'fa-square-o';
      clickeditem.removeClass("fa-check-square-o");
      clickeditem.addClass(newclass)
    }
  };
});
.checkboxinfotd {
  cursor: pointer;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

        Text

      Finance department

      Sales department

A: You can achieve what you want by using: clickeditem.closest('tr').find('.checkbutton').trigger('mouseup');
This code finds the table row parent. Inside the parent it looks for the element with the checkbutton class and triggers the mouseup event (your code is bound to mouseup not click)

As others already stated it might be wise to abonden the idea of using font awsome for checkboxes and use the html input and label elements instead and style those with css. This will make your life a lot easier handling your inputs.

$(document).mouseup(function(e) {

  clickeditem = $(e.target);

  if (clickeditem.hasClass('checkboxinfotd')) {
    clickeditem.closest('tr').find('.checkbutton').trigger('mouseup');

  } else if (clickeditem.hasClass('checkboxtd') || clickeditem.hasClass('checkbutton')) {
    if (clickeditem.hasClass('checkboxtd')) {
      clickeditem = clickeditem.children()[0];
    } else if (clickeditem.hasClass('checkbutton')) {

    } else {

    }

    console.log("clicked on checkbox");
    thirdclass = clickeditem.attr('class').split(' ')[2];

    if (thirdclass === "fa-square-o") {
      newclass = 'fa-check-square-o';
      clickeditem.removeClass("fa-square-o");
      clickeditem.addClass(newclass);

    } else if (thirdclass === "fa-check-square-o") {
      newclass = 'fa-square-o';
      clickeditem.removeClass("fa-check-square-o");
      clickeditem.addClass(newclass)
    }
  };
});
.checkboxinfotd {
  cursor: pointer;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

        Text

      Finance department
      Sales department

A: Your question is not clear completely. Would you trigger the checkbox by click on the text on the right side?
If yes, please use label.

/* Control the label position from here */
.control {
    font-family: inherit;
    display: block;
    position: relative;
    padding-left: 30px;
    margin-bottom: 5px;
    padding-top: 5px;
    cursor: pointer;
    font-size: inherit;
}
    .control input {
        position: absolute;
        z-index: -1;
        opacity: 0;
    }
.control_indicator {
    position: absolute;
    top: 3px;
    left: 0;
    height: 20px;
    width: 20px;
    background: #008736;
    border: 0px solid #000000;
    border-radius: 0px;
}
.control:hover input ~ .control_indicator,
.control input:focus ~ .control_indicator {
    background: #cccccc;
}

.control input:checked ~ .control_indicator {
    background: #008736;
}
.control:hover input:not([disabled]):checked ~ .control_indicator,
.control input:checked:focus ~ .control_indicator {
    background: #008736;
}
.control input:disabled ~ .control_indicator {
    background: #008736;
    opacity: 0.6;
    pointer-events: none;
}
.control_indicator:after {
    box-sizing: unset;
    content: '';
    position: absolute;
    display: none;
}
.control input:checked ~ .control_indicator:after {
    display: block;
}
.control-checkbox .control_indicator:after {
    left: 8px;
    top: 4px;
    width: 3px;
    height: 8px;
    border: solid #ffffff;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}
.control-checkbox input:disabled ~ .control_indicator:after {
    border-color: #008736;
}
.control-checkbox .control_indicator::before {
    content: '';
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    width: 4.5rem;
    height: 4.5rem;
    margin-left: -1.3rem;
    margin-top: -1.3rem;
    background: #008736;
    border-radius: 3rem;
    opacity: 0.6;
    z-index: 99999;
    transform: scale(0);
}

/* The ripple effect  */
@keyframes s-ripple {
    0% {
        transform: scale(0);
    }
    20% {
        transform: scale(1);
    }
    100% {
        opacity: 0;
        transform: scale(1);
    }
}
@keyframes s-ripple-dup {
   0% {
       transform: scale(0);
    }
   30% {
        transform: scale(1);
    }
    60% {
        transform: scale(1);
    }
    100% {
        opacity: 0;
        transform: scale(1);
    }
}
.control-checkbox input + .control_indicator::before {
    animation: s-ripple 250ms ease-out;
}
.control-checkbox input:checked + .control_indicator::before {
    animation-name: s-ripple-dup;
}
<input type="checkbox" value="">Option 1

        label
            <input type="checkbox" checked="checked" />

A: I think what you ultimatly want is to see the fake "checkbox" check/uncheck so I gave an example of toggling that class pair no matter where on the row you click.

$('#belowtable')
  .on('click', '.checkboxinfotd', function(e) {
    let clickeditem = $(this)
    let myparent = clickeditem.closest('tr')
      .find('.checkboxtd')
      .trigger('click');
  }).on('click', '.checkboxtd', function(e) {
    let clickeditem = $(this);
    let cb = clickeditem.find('.checkbutton.fa');
    cb.toggleClass('fa-square-o').toggleClass('fa-check-square');
  });
.checkboxinfotd {
  cursor: pointer;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

        Text

      Finance department

      Sales department


text:
Q: LoadModel does not load in XNA, C# Express Edition I use Windows XP, MSC# 2008 Express Edition, XNA 3.0. I try to load a model in the classic way :
model = Content.LoadModel("myModel");

In the folder Content I have to files : "myModel.fbx" and "myModel_Texture.png".
When I start with debugging I receive the message:

Error loading "myModel". File not found

When I start without debugging the message is that the "Game" (name of my program) has encountered a problem and needs to close and asks whether to send or not info to MS.
I try by adding the model to to the ContentManager with "Add existing item". The files exist; I even put the absolute path. I have the same problem.
What to do?


text:
Q: Laravel Eloquent - Retrieve data from relationship I need help being able to get data from the relationship between users, roles and permissions in my database. Please see below...
Database:
users
id    name   role_id
1     Phil   1
2     Rob    1
3     Dave   2

user_roles
id    name
1     Admin
2     Staff

permissions
id    endpoint
1     /users
2     /roles

user_role_permissions
user_role_id     permissions_id
1                1
1                2
1                2

From the user model I would like to be able to get the data from the permissions table, so I know what access the user has.
Here's the models:
User.php
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable, SoftDeletes;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'role_id'
];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'password',
];

protected $dates = [
    'deleted_at'
];

public function role()
{
    return $this->belongsTo('App\User');
}

public permissions()
{
    ?????
}

}

UserRole.php
class UserRole extends Model {

protected $fillable = ['name'];

protected $hidden = [];

public function users()
{
    return $this->hasMany('App\User');
}

public function permissions()
{
    return $this->belongsToMany('App\Permission', 'user_role_permissions');
}

}

Permission.php
class Permission extends Model {

protected $fillable = ['endpoint'];

protected $hidden = [];

public function roles()
{
    return $this->belongsToMany('App\UserRoles','user_role_permissions');
}

}

Please help!

A: You've correctly defined all the required relationships. You can use it like:
User::with('role.permissions')->first();
// It gives you all the permissions that are assigned to the role assigned to the underlying user :)
// Pretty vague to explain though

You don't need to define permission() on User model.


text:
Q: Strictly stationary but not weakly stationary (not i.i.d case) I am trying to find an example of strictly stationary but not weakly stationary.
Plus, this example should not be i.i.d time series data.
How can I find this example?


text:
Q: SelectOneRadio returns always 0 I am developing a web application with JSF and EJB 3.1, I want to retrieve a value from a selectOneRadio :

                                    <f:selectItem itemLabel="0" itemValue="0"/>
                   itemLabel="1" itemValue="1"/>
                                    <f:selectItem itemLabel="2" itemValue="2"/>
                                    <f:selectItem itemLabel="3" itemValue="3"/>
                                    <f:selectItem itemLabel="4" itemValue="4"/>

testPersist method :
 public void testPersist() {
    System.out.println("entrée dans la méthode testPersist");
    try {
        getFacade().saveListeNoteEntretien();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        System.out.println("finally !!!!!");
    }

}

saveListeNoteEntretien method :
public void saveListeNoteEntretien() {
    List<NoteEntretien> listNoteEntretien = new ArrayList<>();
    try {
        Collaborateur collaborateur = collaborateurFacade.find(1);

        List<Competence> competences = null;
        Competence competence = new Competence();
        competences = competenceFacade.findAll();
        Integer maxIdEntretien = (Integer) em.createQuery("SELECT MAX(e.idEntretien) from Entretien
   e").getSingleResult();
        Entretien entretien = new Entretien(maxIdEntretien + 1);
        entretien.setDateEntretien(new Date());
        entretien.setDiagnosticEntretien(entretienController.getDiagItem());
        entretien.setObservationsEntretien(entretienController.getObsItem());
        entretien.setIdCollaborateur(collaborateurController.getSelected());
        em.persist(entretien);
        for (int i = 0; i < 24; i++) {
            Integer maxIdNoteEntretien = (Integer) em.createQuery("SELECT MAX(n.idNoteEntretien) from
   NoteEntretien n").getSingleResult();
            NoteEntretien noteEntretien = new NoteEntretien(maxIdNoteEntretien + 1);
            noteEntretien.setIdCollaborateur(collaborateurController.getSelected());
            noteEntretien.setIdCompetence(competences.get(i));
            noteEntretien.setIdEntretien(entretien);
            try {
                System.out.println(entretienController.getVal1());
                noteEntretien.setValNoteEntretien((float)entretienController.getVal1());
            } catch (Exception e) {
                e.printStackTrace();
            }

            em.persist(noteEntretien);
            listNoteEntretien.add(noteEntretien);
        }
    } catch (EJBException e) {
        @SuppressWarnings("ThrowableResultIgnored")
        Exception cause = e.getCausedByException();
        if (cause instanceof ConstraintViolationException) {
            @SuppressWarnings("ThrowableResultIgnored")
            ConstraintViolationException cve = (ConstraintViolationException)
 e.getCausedByException();
            for (Iterator<ConstraintViolation<?>> it = cve.getConstraintViolations().iterator();
 it.hasNext();) {
                ConstraintViolation<? extends Object> v = it.next();
                System.err.println(v);
                System.err.println("==>>" + v.getMessage());
            }
        }
        System.err.println("ejb exception ! ! ! ! !");
    } finally {
        System.out.println("persistence OK !!!!!!!");
    }

}

The value retrieved is always set to 0 even if I select 1, 2, 3 or 4.
I tried a simple inputText and parse it to float on the defined method, then could get the proper value :

Note

UPDATE :
I also tried a spinner and it works perfectly. The issue is just with the selectOneRadio

Does anyone have the possibility to help me on that ?
Thank you !


text:
Q: Results Differs in ACR Cloud APP and Web Api I am using ACR cloud WEB API for fetching Metadata of Music
WEB API code : https://github.com/acrcloud/webapi_example/blob/master/identify%20protocol%201%20(recommended)/IdentifyProtocolV1.php
The API processed and gives result as count 11 but ACR App give the results as count 28..
I am messed..why this happens...Why results is varied from api and app..
Kindly Help me on this......
Thankz in Advance

A: i think it depends on how many queries you send to ACRCloud for matching. If we think about one same query from ACRCloud from api or from sdk, the result should the same.


text:
Q: Symfony - directly access the class properties I have created small method in entity class where I can change some things within two fields:
This is my Fruit Entity method:
 /**+
 * @return $this
 */
public function freeBasket(): Fruit
{
    $this->setFreshBasketName($this->getBasketName());
    $this->seBasketName(null);
    return $this;
}

But I got an idea that since this is inside Fruit class, there is no need to use methods for it, that there is a way I can directly access the class properties and than remove setFreshBasketName() method.
How can I accomplish that? New with Symfony. :)

A: You can try
public function freeBasket(): Fruit
{
    $this->freshBasketName = $this->getBasketName();
    $this->basketName = null;
    return $this;
}


text:
Q: NUnit3-Console.exe on Win Server 2012 has no TestFixtures I have been running NUnit3-Console on Win 2012 for almost two years. I recently updated my tests to .Net 4.7.2 and updated the NUnit and Selenium to the latest versions. I have installed NUnit3-Console v3.8 on the server and .Net 4.7.2.
All of the tests that used to run fine now fail with the message "Has no TestFixtures.
I wrote a simple test to isolate the issue and it does the same thing.
My Base class
enter code here
using NUnit.Framework;
using Utilities;

namespace CommonCode2.TestBases
{
    public class NoSeleniumBase
    {

        public Parameters parms = new Parameters();

        [OneTimeSetUp]
        public void InitializePageTests()
        {
            parms.GetParameters();
        }

        [OneTimeTearDown]
        public void CleanupPageTests()
        {
        }
    }
}

My SimpleTest
enter code here
using CommonCode2.TestBases;
using NUnit.Framework;
using System;

namespace SimpleTest
{
    [TestFixture]
    public class TestClass : NoSeleniumBase
    {
        [Test]
        public void Atest()
        {
            Console.WriteLine("This is a simple test");
        }
    }
}

The NUnit files are installed in C:\NUnit and the test is invoked using.
C:\Nunit\NUnit3-Console.exe --where "name =~ 'Atest'"
"C:\QA_Libraries3\SimpleTest.dll"

The TestResult file contains this tag
<property name="_SKIPREASON" value="Has no TestFixtures" />

and a message block
<![CDATA[Has no TestFixtures]]></message>

I am hoping that someone has encountered this issue and can point me in the right direction.

A: Thanks to Charlie Poole and Rob Prouse for their responsive and helpful support. The issue was not with NUnit3-Console but with the tests library directory access. Deleting and recreating the directory resolved the issue.