text:
Q: Calling a method in service which is in another app using aidl I am following the method that is described in Android Developer's Cookbook.
Here is my aidl interface
package com.test.aidl;
interface IMyAidl{

    int add(int n1, int n2 );
}

My serice class
package com.test.usingaidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.test.aidl.IMyAidl;

/**
 * Created by HarshVardhan on 1/18/2016.
 */
public class AddService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private final IMyAidl.Stub mBinder = new IMyAidl.Stub() {
        @Override
        public int add(int n1, int n2) throws RemoteException {
            return n1+n2;
        }
    };

}

My MainActivity
package com.test.usingaidl;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.test.aidl.IMyAidl;

public class MainActivity extends AppCompatActivity {

    IMyAidl service;
    MServiceConnection con;

    class MServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder bound) {
            service =IMyAidl.Stub.asInterface(bound);
            Toast.makeText(MainActivity.this,"Service Connected!",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service = null;
            Toast.makeText(MainActivity.this,"Service Disconnected!",Toast.LENGTH_LONG).show();
        }
    }

    private void initService(){
        con = new MServiceConnection();
        Intent i = new Intent();
        i.setClassName(this, com.test.usingaidl.AddService.class.getName());
        if(!bindService(i, con, Context.BIND_AUTO_CREATE)){
            Toast.makeText(this, "Bind Service Failed!", Toast.LENGTH_SHORT).show();
        }
    }

    private void releaseService(){
        unbindService(con);
        con = null;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initService();
        Button b = (Button) findViewById(R.id.button);
        final EditText et1 = (EditText) findViewById(R.id.editText);
        final EditText et2 = (EditText) findViewById(R.id.editText2);
        final TextView tv = (TextView) findViewById(R.id.textView);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int i = service.add(Integer.parseInt(et1.getText().toString()),Integer.parseInt(et2.getText().toString()));
                    tv.setText(i+"");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}

and the menifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.usingaidl">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".AddService" android:process=":remoteService">
            <intent-filter >
                <action android:name="com.test.usingaidl.addService"></action>
            </intent-filter>
        </service>
    </application>

</manifest>

I have two EditText and m getting two numbers and adding them using service.
It works fine for this example as the interface and service is in the same package. But I want to use service and call the method in another activity.
I have searched a lot but the answers I found were not so helpful.

A: So after lot of search I finally have found the answer.
The problem was that I had to have the aidl file of both of the client and server application in the same package name.


text:
Q: How to Add a scroll bar to an adaptive card I m showing a list of users in a card, can I add a scrollbar to the card so that it fits the screen size?
I am currently using Adaptive card 1.0 and sending this card to MS Teams.

A: AdaptiveCards do not allow scrolling or paging.
If you want to implement paging you could add a "next page" button to your card, when pressed you just update the card with the new list data.
MS Teams allows you to update cards/message you already sent so you could send the first page and when a user clicks on the action button you sent the second page etc.

A: AdaptiveCards do not have the ability to specify scrolling.But we can do with Carousel feature.
{
   attachmentLayout: Attacenter code herehmentLayoutTypes.Carousel,
   attachments: [CardFactory.adaptiveCard()]
}

A: AdaptiveCards do not have the ability to specify scrolling. It would be up to the client to implement this functionality. However, you may be able to send a list card, depending on if it suits your needs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Wilson's theorem implies the existence of an infinitude of composite numbers of the form $n! + 1$? This is a paragraph in David M. Burton, "elementary number theory, seventh edition:
":

But I do not understand:
1- How Wilson's theorem implies the existence of an infinitude of composite numbers of the form $n! + 1$?
This is the statement of Wilson's theorem that I know:
$P$ is a prime iff $(p-1)! \equiv -1 (mod p)$
Could anyone explain this for me please?
2- I do not understand the second statement in the paragraph, especially in comparison to the first statement, does they mean that the form $n! +1$ can give us prime and composite numbers ?

A: Wilson's Theorem says that if $p$ is prime, then $p$ divides the number $m:=(p-1)!+1$. Since clearly $p < m$ if $p>3$, it follows that $m$ is composite.

A: 1) this follows if you also use Euclid's result that there are infinitely many primes, as $(p-1)!+1$ will be composite for each such prime $p$.
2) Indeed, this implies that while we are sure there are infinitely many $n$ such that $n!+1$ is composite, we don't know if there are infinitely many $n$ for which it's prime. In other words if $n-1$ is not prime, this doesn't necessarily imply that $n!+1$ is prime.


text:
Q: How to Create multiple aggregation using Java API in ElasticSearch I have below ElasticSeach query
What should be equivalent Java api code for this
GET my_index/_search
{
  "aggs": {
    "bucket_id": {
      "terms": {
        "field": "id"
        , "size": 1000
      },
      "aggs": {
        "bucket_name": {
          "terms": {
            "field": "name.keyword"
            , "size": 1
          }
        }
      }
    }
  }
}

A: Figured this out
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("bucket_id").field("id").size(1000);
aggregationBuilder.subAggregation(AggregationBuilders.terms("bucket_name").field("name.keyword"));


text:
Q: How does C handle non-booleans in an if statement? I sometimes see this in a C program (I'm using the C18 compiler):
unsigned char someValue = getSomeDataFromSomewhere();
if (someValue) {
    doStuff();
} else {
    doOtherStuff();
}

I know what happens when you give an if loop a boolean (unsigned in the C18 compiler), but what happens when you put a non-boolean in?
My guess: it does doStuff() when the value isn't zero, and doOtherStuff() when the value is zero. But I don't know this, so I'd like to get some reference.

A: Simply put -- if it is non-zero, it is true. If it is zero, it is false.

A: your guess is right:
from §6.8.4.1 of WG14/N1256

the first substatement is executed if the expression compares unequal to 0


text:
Q: PostgreSQL & JDBC "Multiple ResultSets were returned by the query" i am currently working on a practice project to learn PostgreSQL. I would like to use the following method to get a customer number assignment. Customer numbers should be assigned consecutively when adding a new customer in the customer table (1,2,3,4,.....). The variable "anz" contains the number of customers in the table.
If a customer is deleted, his customer number becomes free again and can be assigned again.For example the customer number 3 becomes free again and the FOR- loop in getIndex() only runs until the 3. This number is then assigned. If all numbers are occupied, the next higher number is assigned. So if 1,2,3 are assigned, 4 is chosen.
The function checkEx() checks for each number (1,2,3,4,...) whether it is already present in the table.
I know I could realize this with Java but I would like to program it for practice in the database.
Unfortunately I always get the error "Multiple ResultSets were returned by the query". The functions contain several Select queries, which I replaced with PERFORM, but without success.
Sorry if this sounds a bit complicated, I hope it is understandable.
Can anyone help me?
public static int getKdNr() throws SQLException {

            String sql =
            "SELECT * FROM getIndex(); " +

            // getIndex()
            "CREATE OR REPLACE FUNCTION getIndex() RETURNS integer AS $BODY$ " +

                "DECLARE " +

                   "inx integer := 0; "                          +
                   "check integer := 0; " +
                   "anz integer := 0; " +

                "BEGIN " +

                "PERFORM 'SELECT COUNT(1) FROM customer INTO anz'; " +

                            "FOR  i IN 1..anz LOOP "              +
                            //"check := checkVorh(i); "          +

                              "PERFORM 'SELECT checkEx(i) INTO check'; " +

                               "IF      check=1 THEN inx := i; "          +
                               "ELSE                 inx := anz+1; "            +
                               "END IF; "                         +
                            "END LOOP; "                          +

                        "RETURN inx; "                            +
                "END; "                                           +

            "$BODY$ LANGUAGE plpgsql; " +

            // checkEx(integer)
            "CREATE OR REPLACE FUNCTION checkEx(integer) RETURNS integer AS $BODY$ " +

                "DECLARE " +

                    "ct integer; " +

                "BEGIN " +

                    "PERFORM COUNT(1) INTO ct "      +
                    "FROM customer "                            +
                    "WHERE unique_key = $1; "            +

                    "RETURN ct; "             +

                "END; " +

            "$BODY$ LANGUAGE plpgsql; " ;

    ResultSet rs = stmt.executeQuery(sql);

    return rs.getInt(1);
}

EDIT:
I have now changed my program, but the if-statement does not work as it should.
But I don't understand why.
public static int getKdNr() throws SQLException {

String sql = "SELECT * FROM getIndex(); ";

ResultSet rs = stmt.executeQuery(sql);
rs.next();
return rs.getInt(1);
}

public static void createFunctions() throws SQLException {

stmt = conn.createStatement();

// checkEx(INTEGER)
    String sqlCheckEx = "CREATE OR REPLACE FUNCTION checkEx(INTEGER) RETURNS INTEGER AS $BODY$ " +

        "DECLARE " +

            "ct INTEGER; " +

        "BEGIN " +

            "PERFORM COUNT(1) INTO ct "      +
            "FROM customer "                            +
            "WHERE unique_key = $1; "            +

            "RETURN ct; "             +

        "END; " +

    "$BODY$ LANGUAGE plpgsql; " ;

    stmt.executeUpdate(sqlCheckEx);
    }

// getIndex()
String sqlIndex = "CREATE OR REPLACE FUNCTION getIndex() RETURNS INTEGER AS $BODY$ " +

    "DECLARE " +

       "inx INTEGER   := 1; "                          +
       "check INTEGER := 0; " +

    "BEGIN " +

                "FOR  i IN 1.." + getAnzKd() + " LOOP "              +
                   "check := checkEx(i); "                           +

                               "IF     check>0 THEN     inx := i; "                         +
                               "ELSE                  inx := " + (getAnzKd() +1) + "; "   +
                               "END IF; "                                               +

                 "END LOOP; "                                              +

            "RETURN inx; "                            +

    "END; " +

"$BODY$ LANGUAGE plpgsql; ";

stmt.executeUpdate(sqlIndex);

IO.println("\n\n--> Funktionen erstellt");}

A: You should split your SQL to 3 separate query and call executeQuery for each of them.


text:
Q: Getting previous weeks data with date filter applied Just wondering if anyone knows how to get Previous Week/Previous Year/WoW/YoY data showing up in their data table in tableau if they've filtered the date range in the table (as it goes in a dashboard and I dont want it to show 5 years worth of data). Currently I use:
lookup(SUM([Daily_Total]),-7) for previous week, '-364' instead of '-7' for previous year. IT does show the right data for the previous 7 days if it is filtered there (i.e I have it filtered for the previous 10 days, so for 3 days I've got prev wk/WoW data) but I need it for all 10 days, anyone know how to do this?
Thanks

A: I don't know if this will work for your case but you can try to create a calculated field field with just a call to the INDEX() function. Change this new field to Discrete.
After that, place the field in your workbook and put a filter on this field to choose only the row(s) or column(s) that you want.  You may have to have to "edit calculation" for this field so that it makes sens for your case.
After you can hide the index field in the sheet by unselecting "Show Header".
Hope this helps.


text:
Q: Remove www from string without affecting other parts of string I have a requirement to replace all Url prefixes from the string
Example Inputs
1)lorum ipsum www.goal.com
2)lorum ipsum http://www.goal.com
3)lorum ipsum https://www.goal.com
4)lorum ipsum https://www.goal.com/1234
5)lorum ipsum www.
Expected o/p
1)lorum ipsum goal.com
2)lorum ipsum goal.com
3)lorum ipsum goal.com
4)lorum ipsum goal.com/1234
5)lorum ipsum www.
So far i have this
function removeLinks($url) {

      //$url=preg_replace ("~^www\.~", "", $url);
      $disallowed = array('http://', 'https://','www.');
      foreach($disallowed as $d) {
            $url=str_replace($d, '', $url);

      }
      return $url;
   }

echo removeLinks('lorum ipsum http://www.goal.com and https://www.goal.com abd https://www.goal.com/4234234 and www.goal.com and not remove www.');

But this also remove www at the end which I don't want to be removed,any possible workaround to fix the problem

A: Try this: (http[s]?:\/\/)?www\.(?=.+)
Test regex here: https://regex101.com/r/fjScQn/2

A: function getCleanURL($url) {
    $pattern = '#^(http(s)?://)?w{3}.#';
    if($url == 'www.') {
        return $url;
    }
    return preg_replace($pattern, '', $url);
}

echo getCleanURL('www.goal.com'); // goal.com
echo getCleanURL('http://www.goal.com'); // goal.com
echo getCleanURL('https://www.goal.com'); // goal.com
echo getCleanURL('https://www.goal.com/1234'); // goal.com
echo getCleanURL('www.'); // www.


text:
Q: View messed up since Xcode 7.1 I had this app which I uploaded to the app store. 2 months later I'm having this bug, I didn't change anything in the app. Could it be a Xcode problem?

A: Might be your app would be working as you were using before. But you would not have applied the autolayout and sizeclasses to your app. Which xCode did you used before?


text:
Q: LibreOffice Calc IF Function returns True when should return cell I have been successfully using the IF function up until the last few days. I used this statement to return one of 2 values depending on whether or not an item is shaped:
=IF(G11=1,Q11,IF(G11=0,P11,""))

G11 is 1 (representing a yes) Instead of returning the value of Q11 it says TRUE.
I have tried breaking it down to just the one IF function, checking the structure of the formula. I've been getting around the problem by making new tables an replacing the IF with a VLOOKUP but that will not work here. What might be happening?

A: it might be the cell formatting, if the Category is set to Boolean Value then  TRUE or FALSE is returned and not your "then" or "else" values. credit https://superuser.com/a/709505

A: LibreOffice and OpenOffice use a different delimiter to Excel.
You should swap the comma to a semi-colon.
=IF(G11=1;Q11;IF(G11=0;P11;""))

EDIT: As pointed out by @fixer1234 you can change the delimiter from the default ; to ,. You should check what yours is in the settings.


text:
Q: iOS - confused on ARC and clearing NSMutableArray of objects I have a question about ARC nad NSMutableArray.
Here's the case:
I have a ListView with a NSMUtableArray (arr1) that contains all the elements of the listview. A separate thread, which runs in native code, makes callbacks into objective-c ListView. The native code creates a new NSMutableArray (arr2), fills it with elements of my custom class (each element has a name, id, icon etc), then passes it onto the ListView.
In the ListView, first I clear the array with [arr1 removeAllObjects], then I add each element from arr2 to arr1 with [arr1 addObject: ..].
NOTES:
*All the code, both native and objective-c, is compiled as Objective-C++ code.
*The native code part that allocs and init's arr2 (and all its elements) and calls the ListView stuff is all under @autoreleasepool directive
My questions;

*

*Is there any memory leaks from native code?

*Is there any memory leaks from ListView code? Will the old elements I release with [arr1 removeAllObjects] cause memory leaks?

*Does @autoreleasepool provide the same functionality as ARC, meaning I wont have to explicitly release the objects?

A:
Is there any memory leaks from native code?

Not due to lack of release/autorelease (you should look at weak/strong properties, discussion here)

Is there any memory leaks from ListView code? Will the old elements I
  release with [arr1 removeAllObjects] cause memory leaks?

No.

Does @autoreleasepool provide the same functionality as ARC, meaning I
  wont have to explicitly release the objects?

You CANNOT release objects with ARC. The autoreleasepool will just ensure that the objects that were allocated within it are destroyed after the closing curly bracket (useful if you have a for loop that allocates tons of stuff on each pass and you want to ensure that everything is cleaned up between each of them, for example).

A: 1) There shouldn't be, but sometimes there are small leaks (I've seen some with the keychain, and some audio libraries). It isn't your problem for dealing with and in most cases would be impossible to resolve.
2) removeAllObjects does send release to all the objects in the array. You can see this by putting a break point in the dealloc method.
3) yes ARC @autoreleasepool works the same
The situation you've described above looks safe to me.


text:
Q: Twitter Bootstrap not displaying gutter I am using twitter bootstrap 3 to create a website template, as far as I know it usually has a 15 px gutter on both sides at large display, I am not getting the gutter between divs.
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

Hello, world!

test

test

test

test

A: Try putting the boxes inside the columns.

test

test

test

test

JSFiddle

A: Boostrap rows have 15px negative left and right margins, and columns have 15px left and right padding respectively. You won't see a 'gutter' in the columns because of this fact. However, if you want to create a gutter-like effect, you can do this: Say you want a 2px gutter between each column. Add 1px to the column padding in addition to the 15px it needs.
CSS:
div.col-lg-3 {
  padding-left: 16px; // gutter / 2
  padding-right: 16px; // gutter / 2
}

Do not add margins to the columns.


text:
Q: Is it possible to use asynchronous receiver for unknown number of received bytes? My app is built on C# synchronous sockets, and I am trying to replace them with asynchronous ones, in order to improve efficiency (if possible). So far, I have replaced on the server the Send() and Accept() with the asynchronous ones (based on the MSDN documents), but I have some issues to implement the Receive().
Original (synchronous):
Socket _socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
bool _flag = true;
CheckFun()
{
   while (_flag)
   {
      Thread.Sleep(10); // every ~10ms check
      byte[] _buffer;
      if (_socket.Available != 0)
      {
          _buffer = new byte[1]; // just check 1st byte
          _socket.Receive(_buffer, 1, SocketFlags.None);
          if (_buffer[0] == 1)
          {
              ReceiveFun();
          }
      }
   }
}

ReceiveFun()
{
   int hdrSize = 12;
   byte[] buffer = new byte[hdrSize];
   _socket.Receive(buffer, hdrSize, SocketFlags.None);
   int _dataLength = buffer[0]; // the 1st byte has already been removed before calling the ReceiveFun()
   buffer = new byte[_dataLength];
   int _bytesRead = 0;
   while (_bytesRead != _dataLength)
   {
        while (_socket.Available == 0)
        {
             if (!_socket.Connected)
                 return 0;
        }
        _bytesRead += _socket.Receive(buffer, _bytesRead, _dataLength - _bytesRead, SocketFlags.None);
   }
   //read bytes blah blah...
}

My question is how to turn this operation into an asynchronous one and concatenate the bytes received until I receive all information? And then again wait for the next one?
EDIT
Async

public class State
{
    public int nToReadBytes = 0;
    public int nBytesRead = 0;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];     // Receive buffer.
}

List<byte> lReceivedBytes = new List<byte>();
int hdrSize = 12;
public void ReadCallback(IAsyncResult ar)
{
     // Retrieve the state object and the handler socket
    // from the asynchronous state object.
    var state = ar.AsyncState as State;

   // Read data from the client socket.
   int availableBytes = oSocket.EndReceive(ar);

   if (availableBytes > 0)
   {
       if (lReceivedBytes.Count == 0)
       {
            if (state.buffer[0] == 1)
            {
                 // the first field of the header has been successfully decoded
                 if (availableBytes > 1)
                 {
                     state.nToReadBytes = BitConverter.ToInt32(state.buffer, 1) + hdrSize;
                     int _bytesCopy = Math.Min(state.nToReadBytes, state.buffer.Length); //in case that the data is less than the State.BufferSize (unlikely)
                     state.nBytesRead += _bytesCopy;
                     lReceivedBytes.AddRange(state.buffer);
                 }
            }
            else if (state.buffer[0] == 2)
            {
                 // the first field of the header has been successfully decoded but do nothing!
                 _socket.BeginReceive(state.buffer, 0, State.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                 return;
            }
            else
                throw new InvalidDataException("Invalid hdr field [1-2]: " + state.buffer[0]);
       }
       else
       {
            state.nBytesRead += state.buffer.Length;
            lReceivedBytes.AddRange(state.buffer);
       }

       if (lReceivedBytes.Count == state.nToReadBytes)
       {
           //read all information and clear list and States in the end (?)
           //   ...
           lReceivedBytes.Clear();
           state.nToReadBytes = 0;
           state.nBytesRead = 0;
           _socket.BeginReceive(state.buffer, 0, State.BufferSize, 0, new AsyncCallback(ReadCallback), state);
       }
       else
       {
            //int _newSize = Math.Min(state.nToReadBytes - state.nBytesRead, State.BufferSize); // for restriction (?)
            int _newSize = state.nToReadBytes - state.nBytesRead; // for now don't check
            _socket.BeginReceive(state.buffer, 0, _newSize, 0, new AsyncCallback(ReadCallback), state); //shall I increase the size (it could be between 90 kB - 170kB, until all info is received)
       }
    }
    else
       _socket.BeginReceive(state.buffer, 0, State.BufferSize, 0, new AsyncCallback(ReadCallback), state);
 }

A: The Socket class has two main asynchronous paradigms: the original callback-based Asynchronous Programming Model (APM) and the only-slightly-newed Event-based Asynchronous Pattern (EAP). Both of these can be somewhat unwieldy to implement as compared to the synchronous appproach, as they require you to adjust your thinking to connection state instead of just local method logic, breaking up what would be a single method into parts dealing with the initiation and completion of the operation.
Fortunately, the newer Task Parallel Library model leverages async and await to allow asynchronous code to be written in almost identical fashion to the equivalent synchronous version. For the Socket class, to take advantage of this, you need to wrap its asynchronous API in a TPL-compatible way. .NET does provide a general-purpose way to take existing APM APIs and wrap them in tasks (see https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/tpl-and-traditional-async-programming), but IMHO it is simpler to take advantage of the NetworkStream class, which wraps a socket in a Stream object.
Since Stream already has received the "TPL love", i.e. has ReceiveAsync() and similar methods to allow TPL-based operations, I find this somewhat easier than dealing with the wrapper methods designed to map APM to TPL.
In your code, that would wind up looking something like this:
// Somewhere appropriate -- your code example isn't specific or complete enough
// to offer anything more detailed than this
NetworkStream _stream = new NetworkStream(_socket);

async Task ReceiveFun()
{
    int _bytesRead = 0, hdrSize = 12;
    byte[] buffer = new byte[hdrSize];

    while (_bytesRead < hdrSize)
    {
        int bytesRead = await _stream.ReadAsync(buffer, _bytesRead, hdrSize - _bytesRead);

        if (bytesRead == 0) throw new InvalidDataException("unexpected end-of-stream");
        _bytesRead += bytesRead;
    }

    int _dataLength = buffer[0]; // the 1st byte has already been removed before calling the ReceiveFun()
    buffer = new byte[_dataLength];

    _bytesRead = 0;
    while (_bytesRead < _dataLength)
    {
        int bytesRead = await _stream.ReadAsync(buffer, _bytesRead, _dataLength - _bytesRead);

        if (bytesRead == 0) throw new InvalidDataException("unexpected end-of-stream");
        _bytesRead += bytesRead;
   }
   //read bytes blah blah...
}

Note that your original synchronous code had a bug: you were not using the returned byte count when reading the header, and so had no way to know if the full header was actually being returned in a single call or not. You must always look at the count of bytes read; this can always be as few as 1 when data is available, and of course will be 0 when the end of stream is reached (i.e. the remote endpoint uses the shutdown operation).
Your code also did not check for end-of-stream correctly. Just look at the bytes returned when you try to read from the socket. I've fixed that in the above as well.


text:
Q: When fixing near-duplicates, how to group fuzzy-matched records in Postgres 9.6+ We have an application that has been erroneously inserting duplicates into the database. As a result I have been asked to identify the duplicates and group them together for review. There are roughly 500 thousand records, some are indeed unique, but most have at least one duplicate.
A duplicate in this case can mean rows that are either exactly, or close to be the same thing. For example, a person may have been added with the address 124 Main St and then again with 124 Main St, and yet again with 124 Main Street. To find these dupes I've been using similarity() and that seems to work as desired.
I am having trouble figuring out how to get my query to group duplicates together.
Given a build schema like this:
CREATE TABLE Users (
   id  BIGINT NOT NULL,
   first_name TEXT,
   last_name TEXT,
   street_address CHAR(50)
);

INSERT INTO Users (id, first_name, last_name, street_address) VALUES
  (7, 'JAMES','FAZ', '39392 Example Pl'),
  (1, 'JOE','FOO', '124 Example St. SE'),
  (223, 'MARK','BAZ', '566 Example Blvd'),
  (3, 'JOESEPH','FOO', '124 Example St. SE'),
  (5, 'JOE','FOO', '124 Example Street SE'),
  (55, 'CHARLES','BOO', '399 Example Lane'),
  (54, 'JOESEPH','FOO', '124 Example St. Southeast'),
  (4, 'KATIE','BAR', '1455 Example Ave'),
  (7, 'KATIE','BAR', '1455 Example Ave'),
  (866, 'JAMES','FAZ', '39392 Example Place'),
  (33, 'KATIE','BAR', '1455 Example Avenue')
;

CREATE TABLE Dupes (
   id  BIGINT NOT NULL,
   first_name TEXT,
   last_name TEXT,
   street_address CHAR(50),
   searched_name TEXT,
   searched_user_id bigint
);

Which generates a table like:
+-----+---------+--------+---------------------------+
| id  | first_name | last_name | street_address      |
+-----+---------+--------+---------------------------+
| 7   | James   | Faz    | 39392 Example Pl          |
+-----+---------+--------+---------------------------+
| 1   | Joe     | Foo    | 124 Example St. SE        |
+-----+---------+--------+---------------------------+
| 223 | Mark    | Baz    | 566 Example Blvd          |
+-----+---------+--------+---------------------------+
| 3   | Joeseph | Foo    | 124 Example St. SE        |
+-----+---------+--------+---------------------------+
| 5   | Joe     | Foo    | 124 Example Street SE     |
+-----+---------+--------+---------------------------+
| 55  | Charles | Boo    | 399 Example Ln            |
+-----+---------+--------+---------------------------+
| 54  | Joeseph | Foo    | 124 Example St. Southeast |
+-----+---------+--------+---------------------------+
| 4   | Katie   | Bar    | 1455 Example Ave          |
+-----+---------+--------+---------------------------+
| 7   | Katie   | Bar    | 1455 Example Ave          |
+-----+---------+--------+---------------------------+
| 866 | James   | Faz    | 39392 Example Place       |
+-----+---------+--------+---------------------------+
| 33  | Katie   | Bar    | 1455 Example Avenue       |
+-----+---------+--------+---------------------------+

I want the same data but 'ordered' to look something like this:
+-----+---------+--------+---------------------------+
| id  | first_name | last_name | street_address     |
+-----+---------+--------+---------------------------+
| 55  | Charles | Boo    | 399 Example Ln            |
+-----+---------+--------+---------------------------+
| 1   | Joe     | Foo    | 124 Example St. SE        |
+-----+---------+--------+---------------------------+
| 3   | Joeseph | Foo    | 124 Example St. SE        |
+-----+---------+--------+---------------------------+
| 54  | Joeseph | Foo    | 124 Example St. Southeast |
+-----+---------+--------+---------------------------+
| 5   | Joe     | Foo    | 124 Example Street SE     |
+-----+---------+--------+---------------------------+
| 4   | Katie   | Bar    | 1455 Example Ave          |
+-----+---------+--------+---------------------------+
| 7   | Katie   | Bar    | 1455 Example Ave          |
+-----+---------+--------+---------------------------+
| 33  | Katie   | Bar    | 1455 Example Avenue       |
+-----+---------+--------+---------------------------+
| 866 | James   | Faz    | 39392 Example Place       |
+-----+---------+--------+---------------------------+
| 7   | James   | Faz    | 39392 Example Pl          |
+-----+---------+--------+---------------------------+

My attempts have been akin to the following
WITH
Matching (id, first_name, last_name, street_address, searched_name, searched_user_id) AS (
  SELECT DISTINCT
    l.id
    , l.first_name
    , l.last_name
    , l.street_address
    , r.first_name || ' ' || r.last_name
    , r.id
  FROM Users l
  JOIN Users r
  ON SIMILARITY(l.first_name || ' ' || l.last_name || ' ' || l.street_address,
                  r.first_name || ' ' || r.last_name || ' ' || r.street_address) > .50
      /*AND CAST(l.id AS int) = 72918*/
)
-- SELECT * FROM Matching
INSERT INTO Dupes (id, first_name, last_name, street_address, searched_name, searched_user_id)
  (
    SELECT id, first_name, last_name, street_address, searched_name, searched_user_id
    FROM Matching
  )
  ON CONFLICT (id) DO NOTHING;

SELECT * FROM Dupes;

This attempt results in a lot of repeated data.

The groups themselves can be in any order, it just matters that similarish records are grouped together in the final output.
Not sure if it helps but here's a sqlfiddle with the above data in case it might help someone with tinkering around.

A: This might do it:
WITH
Matching (id, first_name, last_name, street_address, searched_name, searched_user_id) AS (
  SELECT DISTINCT
    l.id
    , l.first_name
    , l.last_name
    , l.street_address
    , r.first_name || ' ' || r.last_name
    , r.id
  FROM Users l
  JOIN Users r
  ON SIMILARITY(l.first_name || ' ' || l.last_name || ' ' || l.street_address,
                  r.first_name || ' ' || r.last_name || ' ' || r.street_address) > .50
   and r.id>l.id
)
INSERT INTO Dupes (id, first_name, last_name, street_address, searched_name, searched_user_id)
  (
    SELECT id, first_name, last_name, street_address, searched_name, searched_user_id
    FROM Matching order by id
  );

SELECT * FROM Dupes order by id;

Here is another possibility:
WITH
Matching (id, first_name, last_name, street_address, searched_name, searched_user_id) AS (
  SELECT DISTINCT
    l.id
    , l.first_name
    , l.last_name
    , l.street_address
    , r.first_name || ' ' || r.last_name
    , r.id
  FROM Users l
  JOIN Users r
  ON SIMILARITY(l.first_name || ' ' || l.last_name || ' ' || l.street_address,
                  r.first_name || ' ' || r.last_name || ' ' || r.street_address) > .50

)
select * from (
  select distinct on (id) id, first_name, last_name, street_address from matching order by id
 ) d order by street_address;

The insert is trivial so I only do select for the insert here.
Best regards,
Bjarni


text:
Q: How do I JUnit test a Spring autowired constructor? I have done quite a bit of searching online and I can't find an example of unit testing with an autowired constructor. I am using Spring to autowire in the values from a properties file to my application. I want to unit test MyApp.java's start method, but I have an autowired constructor so I don't know how to instantiate MyApp. Without the autowired properties, I was doing this in my unit test:
@Test
public void testStart() {
  try{
   MyApp myApp = new MyApp();
   myApp.start();
   }
   catch (Exception e){
     fail("Error thrown")
   }
}

I don't want to mock the autowiring, as I need to obtain the values from the properties file and to further complicate things, I am configuring everything through annotations. I don't have a spring.xml, application-context.xml, or a web.xml file. So how do I go about instantiating/testing MyApp's start method? I tried adding in @RunWith(SpringJUnit4ClassRunner.class) and autowiring MyApp myApp, but it throws errors about failing to load the application context that aren't fixed by implementing ApplicationContextAware on the test class.
Here is MyApp.java
@Component
public class MyApp {

    private static ApplicationContext applicationContext;
    private static MyAppProperties myAppProperties;

    //Obtain the values from the app.properties file
    @Autowired
    MyApp(MyAppProperties myAppProps){
        myAppProperties = myAppProps;
    }

    public static void main(String[] args) throws Exception {
     // Instantiate the application context for use by the other classes
     applicationContext = new AnnotationConfigApplicationContext("com.my.company");

     start();
    }

    /**
     * Start the Jetty server and configure the servlets
     *
     * @throws Exception
     */
    public static void start() throws Exception {
        // Create Embedded Jetty server
        jettyServer = new Server();

        // Configure Jetty so that it stops at JVM shutdown phase
        jettyServer.setStopAtShutdown(true);
        jettyServer.setStopTimeout(7_000);

        // Create a list to hold all of the handlers
        final HandlerList handlerList = new HandlerList();

        // Configure for Http
        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        http_config.setSecurePort(myAppProperties.getHTTP_SECURE_PORT());
    ....
    }
}

Here is my app.properties file
# Spring Configuration for My application

#properties for the embedded jetty server
http_server_port=12345

Here is MyAppProperties.java
@Component
public class MyAppProperties implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    //List of values from the properties files to be autowired
    private int HTTP_SERVER_PORT;
    ...

    @Autowired
    public MyAppProperties( @Value("${http_server_port}") int http_server_port, ...){
        this.HTTP_SERVER_PORT = http_server_port;
    }

    /**
     * @return the applicationContext
     */
    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * @param applicationContext
     *            the applicationContext to set
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setHTTP_SERVER_PORT(String name) {
        JETTY_SERVER_NAME = name;
    }

    /**
     * @return the httpServerPort
     */
    public int getHTTP_SERVER_PORT() {
        return HTTP_SERVER_PORT;
    }
}

Here is MyAppTest.java
@RunWith(SpringJUnit4ClassRunner.class)
public class MyAppTest implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext appContext) {
        applicationContext = appContext;
    }

    @Autowired
    private MyApp myapp;

    @Test
    public void testStart(){
    try {
        if(myapp != null){
            myapp.start();
        }
        else{
            fail("myapp is null");
        }
    } catch (Exception e) {
        fail("Error thrown");
        e.printStackTrace();
    }
    }
}

UPDATE: Here is my configuration class
@Configuration
@Component
public class ApplicationConfig implements ApplicationContextAware {

    private final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class);
    private ApplicationContext applicationContext;

    /**
     * @return the applicationContext
     */
    public ApplicationContext getApplicationContext() {
        LOGGER.debug("Getting Application Context", applicationContext);
        return applicationContext;
    }

    /**
     * @param applicationContext
     *            the applicationContext to set
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    // Needed for @Value
    /**
     * Property sources placeholder configurer.
     *
     * @return the property sources placeholder configurer
     */
    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
        propertyPlaceholderConfigurer.setLocation(new ClassPathResource("app.properties"));
        return propertyPlaceholderConfigurer;
    }
    ...
}

A: We can mock the objects using the jmockito framework.
Using @InjectMocks for dependency injection via Mockito
You also have the @InjectMocks annotation which tries to do constructor, method or field dependency injection based on the type. The following code is a slightly modified example from the Javadoc.
// Mockito can construct this class via constructor
public class ArticleManager {
         ArticleManager(ArticleCalculator calculator, ArticleDatabase database) {
        }
}

// Mockito can also perform  method injection
public class ArticleManager {
        ArticleManager() {  }
        void setDatabase(ArticleDatabase database) { }
        void setCalculator(ArticleCalculator calculator) { }
}

// Mockito can also perform  field injection
public class ArticleManager {

    private ArticleDatabase database;
    private ArticleCalculator calculator;
}

The following will be the unit test class.
@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest  {
   @Mock private ArticleCalculator calculator;
   @Mock private ArticleDatabase database;
   @Spy private UserProvider userProvider = new ConsumerUserProvider();

   // creates instance of ArticleManager
   // and performs constructor injection on it
   @InjectMocks private ArticleManager manager;

   @Test public void shouldDoSomething() {
           // assume that ArticleManager has a method called initialize which calls a method
           // addListener with an instance of ArticleListener
           manager.initialize();

       // validate that addListener was called
           verify(database).addListener(any(ArticleListener.class));
   }

}
Make sure that you are using @RunWith(MockitoJUnitRunner.class)
For more information see http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/InjectMocks.html.


text:
Q: iOS how to work with simd_float3 correctly? I'm running into a weird issue, working with data created by Metal shader code. I want to do additional processing in Swift, and then inject the data back to be rendered by Metal.

*

*Metal shader is given a MetalBuffer

*Metal shader processes vertices one by one

*Metal shader writes the result to the provided buffer

*Metal shader executes it's completion block for buffer

*Swift code receives the buffer and iterates over it, rewriting one struct into another

*Swift code writes the result to the shared buffer used for rendering

*Metal shader renders pixels at slightly wrong positions, causing flicker and graphical glitches

All structs and math is using simd_float3
How do I correctly pass struct data from Metal code to be available in Swift and pass it back? What I'm seeing is that my values get corrupted as a result of processing (some kind of floating point error - pixels get mis-aligned when drawn using the new struct).
If I assign the value directly from one buffer to the shared buffer, the points are rendered at correct locations, and no flicker happens.
//ShaderTypes.h
#include <simd/simd.h>
struct ParticleUniforms {
    simd_float3 position;
    simd_float3 color;
//    float confidence; // I want to get rid of this value after processing in swift
};

struct DisplayPoint {
    simd_float3 position;
    simd_float3 color;
};

/// Vertex shader that takes in a 2D grid-point and infers its 3D position in world-space, along with RGB and confidence.
/// Updates the passed in particleUniforms buffer, one point at a time
vertex void screenSample(uint vertexID [[vertex_id]],
                         constant PointCloudUniforms &uniforms [[buffer(kPointCloudUniforms)]],
                         device ParticleUniforms *particleUniforms [[buffer(kParticleUniforms)]],
                         constant float2 *cameraSamplePatternBuffer [[buffer(kGridPoints)]],
                         texture2d<float, access::sample> capturedImageTextureY [[texture(kTextureY)]],
                         texture2d<float, access::sample> capturedImageTextureCbCr [[texture(kTextureCbCr)]],
                         texture2d<float, access::sample> depthMap [[texture(kTextureDepth)]],
                         texture2d<unsigned int, access::sample> confidenceMap [[texture(kTextureConfidence)]]) {

    //this is what combines and parses the data to create each point on the cloud
    const auto sampledCameraPoint = cameraSamplePatternBuffer[vertexID];

    const auto texCoord = sampledCameraPoint / uniforms.cameraResolution;

    // Sample the color depth map to get the depth value
    const auto depth = depthMap.sample(colorSampler, texCoord).r;
    // With a 2D point plus depth, we can now get its 3D position
    const auto position = worldPoint(sampledCameraPoint, depth, uniforms.cameraIntrinsicsInversed, uniforms.localToWorld);

    // Sample Y and CbCr textures to get the YCbCr color at the given texture coordinate
    const auto ycbcr = float4(capturedImageTextureY.sample(colorSampler, texCoord).r, capturedImageTextureCbCr.sample(colorSampler, texCoord.xy).rg, 1);
    const auto sampledColor = (yCbCrToRGB * ycbcr).rgb;
    // Sample the confidence map to get the confidence value
    const auto confidence = confidenceMap.sample(colorSampler, texCoord).r;

    if (confidence > 1.0) {
        particleUniforms[vertexID].position = position.xyz;
        particleUniforms[vertexID].color = sampledColor;
    }
}

Here's the shader which is actually drawing points on the screen:
vertex ParticleVertexOut particleVertex(uint vertexID [[vertex_id]],
                                        constant PointCloudUniforms &uniforms [[buffer(kPointCloudUniforms)]],
                                        constant ParticleUniforms *particleUniforms [[buffer(kParticleUniforms)]]) {
    // get point data
    const auto particleData = particleUniforms[vertexID];
    const auto position = particleData.position;

    // animate and project the point
    float4 projectedPosition = uniforms.viewProjectionMatrix * float4(position, 1.0);

    projectedPosition /= projectedPosition.w;

    ParticleVertexOut out;
    out.position = projectedPosition;

    const auto sampledColor = particleData.color;

    out.color = float4(sampledColor, 1);
    out.pointSize = 1.0 ;

    return out;
}

in swift (both conversions produce corruption of the position, and color).
let particle: ParticleUniforms = particlesBuffer[pointIndex]
let point = DisplayPoint(position: simd_float3(particle.position.x,
                                               particle.position.y,
                                               particle.position.z),
                         color: simd_float3(particle.color.x,
                                            particle.color.y,
                                            particle.color.z))
// -OR -
let point = DisplayPoint(position: particle.position,
                         color: particle.color))

The image corruption below - when passing the original struct from one shader into another shader, all pixels align properly and there are no "holes":

A: If I understood correctly what you are trying to do, you basically want to stall GPU timeline until you've modified intermediate result from the GPU on the CPU.
Basically, unless there's explicit synchronization, after command buffer is scheduled, CPU and GPU timelines are completely independent from your program's point of view, which means, that you can't make any assumptions on what executes first between CPU and GPU.
If you try to just do it in the completion handler of your command buffer, this isn't going to work. GPU will continue executing the next command buffer in the queue and you are basically gonna be racing to change the data on the CPU before GPU gets to it.
To do what you are trying to do properly, you need to use MTLSharedEvent and instead of using a completion block, you are gonna use event's notifyListener.
Your new timeline is gonna look like this, I'm going to use Objective-C here:
GPU Timeline:

*

*Metal shader is given a MetalBuffer

*Metal shader processes vertices one by one

*Metal shader writes the result to the provided buffer

*[commandEncoder encodeSignalEvent:event value:n]

*[commandEncoder encodeWaitForEvent:event value:n+1]
On CPU:
Subscribe to event: [event notifyListener:_sharedEventListener atValue:2 block:{your block}
And in your block you are going to do the following:

*

*Block receives the buffer and iterates over it, rewriting one struct into another

*Block code writes the result to the shared buffer used for rendering

*event.signaledValue = n + 1
n in this case should be a monotonically rising value. So every time you want to progress forward you bump it up by one. In this case since we signal both n and n + 1, you would need to bump it up by two. It all depends on your particular use case, just make sure that you aren't waiting on a value that's lower than the current signaledValue of an event
And this should work. For more info, refer to these articles from Apple: MTLSharedEvent and Synchronizing Events Between a GPU and the CPU
But you should also note, that if you aren't using multiple command queues, your GPU will basically stall, do nothing, while it waits for CPU to finish whatever modifications it's doing. Sometimes you can't avoid it, but it's usually best to try to move all the work you can to the GPU timeline avoid GPU stalling. You can try to schedule the work on the same queue to modify your vertices or use multiple queues and use techniques from this article: Synchronizing Events Within a Single Device.
Anyways, I hope this helps you solve your issue.


text:
Q: AngularJS service function not returning full promise after while loop has completed I'm trying to paginate a map. I want to force the controller to wait for the service which performs the pagination to return all the available products before trying to do anything.
I've implemented a resolve function in my router which will call the service that performs the pagination (using a while loop) and fetches the results.
When running the code, inside the controller the number of "products" is always 1/2 or 2/3rds of the full amount depending on the browser being used. The controller initialises before the while loop has finished running/returning all the promises. I'm a bit confused as to how to force the controller to wait for all the results from the while loop be fetched.  Do I need to make a change in my service function, my controller or the router (or all three?). Or, is it that my use of the $q library is incorrect?
Inside my router:
    .state('products-map', {
        url: "/products-map",
        parent: 'base',
        templateUrl: "../components/products/products.map.html",
        data: { pageTitle: 'Products Map', pageSubTitle: 'map of all the products'},
        controller: "ProductsMapController",
        resolve: {
            deps: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'myApp',
                    insertBefore: '#ng_load_plugins_before',
                    files: [
                        { type: 'js', path: '//maps.google.com/maps/api/js?v=3&key=<my_api_key>&libraries=visualization,geometry'},
                        '../js/markerclusterer_packed.js',
                    ]
                });
            }],

            total_products: function(DashboardService) {
                return DashboardService.getTotalProducts();
            },

            products: function(DashboardService, total_products){
                return DashboardService.getPaginatedProducts(total_products);
            },

        }
    })

Inside my service function which handles the pagination:
this.getPaginatedProducts = function(total_product_count) {

    var total_fetched_results = 0;
    var total_number_of_products = total_product_count;
    console.log("total number of products in paginated products: ", total_number_of_products);
    var results_per_page = 20000;
    var page = 1;
    var products = [];

    var deferred = $q.defer();

    while (total_number_of_products > total_fetched_results) {

        $http({
            url: $rootScope.apiUrl + 'products/location',
            method: "GET",
            params: { 'results_per_page': results_per_page, 'page': page}
        }).then(function(response) {
            console.log("response from service", response);
            var response_data = response.data.data;
            for (var i = 0; i < response_data.length; i++) {
                products.push(response_data[i]);
            }
        });

        page++;
        total_fetched_results += results_per_page;
    }

    deferred.resolve(products);
    return deferred.promise;
};

Inside my controller:
angular.module('SS2').controller('ProductsMapController', ['$rootScope', 'products', '$scope', '$http', 'NgMap', 'total_products',
    function ($rootScope, products, $scope, $http, NgMap, total_products) {

        $scope.$on('mapInitialized', function (event, map) {

            console.log("ProductsMapController Initialised")
            console.log("total_products inside ProductsMapController is: ", total_products);
            $scope.map_products = products;
            console.log("inside controller number of products is: ", products);

A: There's a few approaches you can take here and using Promises certainly make sense. What I'm seeing happening with your while loop is a logic flaw where your $http requests aren't all resolved before your function hits its exit condition.
You might want to look into using $q.all() and building out an array of $http calls to make sure everything is resolved BEFORE you return your results as I suspect, when you look at your network monitor, you'll see calls not resolved before the results are rendered.
https://docs.angularjs.org/api/ng/service/$q#all
an excellent example is https://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/


text:
Q: When they want to log in my app crashes firebase realtime database I am using a real-time database (in firebase) and my error is that when trying to enter the account it gives me an error and the application crashes in the case it indicates that the error is that attached the code and one more image clear
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    final EditText et_correo = findViewById(R.id.et_correo);
    final EditText et_contrasena = findViewById(R.id.et_contrasena);
    final Button btn_ingresar = findViewById(R.id.btn_ingresar);
    final TextView btn_registrate = findViewById(R.id.btn_registrate);

    btn_ingresar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final String correotxt = et_correo.getText().toString();
            final String contrasenaTxt = et_contrasena.getText().toString();

            if (correotxt.isEmpty() || contrasenaTxt.isEmpty()) {
                Toast.makeText(LoginActivity.this, "Favor de introducir sus datos", Toast.LENGTH_SHORT).show();
            } else {

                databaseReference.child("nombre").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                       //THIS IS MY ERROR
                        if (snapshot.hasChild(correotxt)) {

                            final String getPassword = snapshot.child(correotxt).child("contrasena").getValue(String.class);
                            if (getPassword.equals(contrasenaTxt)) {
                                Toast.makeText(LoginActivity.this, "Se ha logueado de manera exitosa!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            }else{
                                Toast.makeText(LoginActivity.this, "Correo o Contraseña incorrectos", Toast.LENGTH_SHORT).show();

                            }

                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
                btn_registrate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        // open RegistroActivity
                        startActivity(new Intent(LoginActivity.this, RegistroActivity.class));
                    }
                });

            }
        }
    });}}

IMG. LOGCAT


text:
Q: What is the difference between .profile and .bash_profile and why don't I have a .profile file on my system? So I'm pretty new to Linux and recently installed Fedora 19 on my netbook. I want to have a deeper understanding of Linux and the CLI so I'm now reading Learn Linux: The Hard Way.
In exercise 3 the author gives the following commands:

*

*ls -al

*cat .profile

I try to follow these instructions but to no avail. There is no .profile file in my user name directory as I can see from ls -al. From what I've learned the .bash_profile and .profile file are practically the same. The only difference I concluded from my research is that .bash_profile gets checked first.
What I don't understand is why are there multiple files for the same function in Linux, why is the Author using .profile and not .bash_profile (if I understand correctly .profile won't be read when the system finds .bash_profile first) and how comes that I don't have the .profile file on my system?

A: The .profile dates back to the original Bourne shell known as sh. Since the GNU shell bash is (depending on its options) a superset of the Bourne shell, both shells can use the same startup file. That is, provided that only sh commands are put in .profile
For example, alias is a valid built-in command of bash but unknown to sh. Therefore, if you had only a .profile in your home directory and put an alias statement in it, sh would complain. So there is a bash specific file that has shell initialization commands which bash will read if and only if there isn't a .profile file present.
Actually that's a bit of an oversimplification in some installations, and I'm not familiar with Fedora. Under bash, /etc/profile is read by the shell before any files in your home directory. If there is a system wide initialization script it often says something like
if there is a $HOME/.profile:
   source it
elseif bash is my shell and there is a $HOME/.bash_profile:
   source that

Why is that way? An attempt at compatibility across decades of shell dialects. Why is the tutorial written that way? The Bourne shell is not often used much any more and some people don't even know that there is any other Bourne-like shell than bash. Even when the (limited) Bourne syntax is used for greater cross-platform compatibility it is often being run by dash or bash in POSIX compatibility mode. Indeed, the actual Bourne shell source is probably a copyright component of Unix System V which appears to be the property of Novell now but I have no idea what, if anything, they are doing with it.
For the beginning user, use either $HOME/.profile or $HOME/.bash_profile but not both and you'll be fine. Since you already have a .bash_profile work with that because it may have system specific stuff in it that your installation needs.


text:
Q: How to serialize and consume ECDH parameters in Java I am looking to perform ECDH between 2 platforms to derive a shared secret. I am planning to use a named curve (which curve not yet determined). The flow would look something like this:

*

*Alice picks a curve

*Alice generates a random key pair for her curve

*Alice serializes some data about her curve

*Alice sends her public key and curve data to Bob

*Bob initializes a curve with Alice's data

*Bob creates a key pair based on Alice's data

*Bob performs ECDH to derive shared secret

*Bob responds to Alice with his public key

*Alice performs ECDH to derive shared secret

Using bouncycastle, what is the cleanest way to accomplish this?
Almost all examples I've seen (like this one: https://gist.github.com/wuyongzheng/0e2ed6d8a075153efcd3) illustrate the process of arriving at the shared secret, but none seem to factor in the process of actually serializing information about the curve / starting point (G) to "Bob" and how to use that data on Bob's side to rebuild the curve and generate corresponding keys. What data would you need to send to Bob?

A: I believe i found a relatively succinct way of demonstrating the problem / solution for this. I was originally missing the fact that named curves include a common starting point, so no need to serialize that data if you have an agreed-upon curve.
Security.addProvider(new BouncyCastleProvider());

// Alice sets up the exchange
KeyPairGenerator aliceKeyGen = KeyPairGenerator.getInstance("ECDH", "BC");
aliceKeyGen.initialize(new ECGenParameterSpec("prime256v1"), new SecureRandom());

KeyPair alicePair = aliceKeyGen.generateKeyPair();
ECPublicKey alicePub = (ECPublicKey)alicePair.getPublic();
ECPrivateKey alicePvt = (ECPrivateKey)alicePair.getPrivate();

byte[] alicePubEncoded = alicePub.getEncoded();
byte[] alicePvtEncoded = alicePvt.getEncoded();

System.out.println("Alice public: " + DatatypeConverter.printHexBinary(alicePubEncoded));
System.out.println("Alice private: " + DatatypeConverter.printHexBinary(alicePvtEncoded));

// POST hex(alicePubEncoded)

// Bob receives Alice's public key

KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey remoteAlicePub = kf.generatePublic(new X509EncodedKeySpec(alicePubEncoded));

KeyPairGenerator bobKeyGen = KeyPairGenerator.getInstance("ECDH", "BC");
bobKeyGen.initialize(new ECGenParameterSpec("prime256v1"), new SecureRandom());

KeyPair bobPair = bobKeyGen.generateKeyPair();
ECPublicKey bobPub = (ECPublicKey)bobPair.getPublic();
ECPrivateKey bobPvt = (ECPrivateKey)bobPair.getPrivate();

byte[] bobPubEncoded = bobPub.getEncoded();
byte[] bobPvtEncoded = bobPvt.getEncoded();

System.out.println("Bob public: " + DatatypeConverter.printHexBinary(bobPubEncoded));
System.out.println("Bob private: " + DatatypeConverter.printHexBinary(bobPvtEncoded));

KeyAgreement bobKeyAgree = KeyAgreement.getInstance("ECDH");
bobKeyAgree.init(bobPvt);
bobKeyAgree.doPhase(remoteAlicePub, true);

System.out.println("Bob secret: " + DatatypeConverter.printHexBinary(bobKeyAgree.generateSecret()));

// RESPOND hex(bobPubEncoded)

// Alice derives secret

KeyFactory aliceKf = KeyFactory.getInstance("EC");
PublicKey remoteBobPub = aliceKf.generatePublic(new X509EncodedKeySpec(bobPubEncoded));

KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("ECDH");
aliceKeyAgree.init(alicePvt);
aliceKeyAgree.doPhase(remoteBobPub, true);

System.out.println("Alice secret: " + DatatypeConverter.printHexBinary(aliceKeyAgree.generateSecret()));

And on first run, this yielded:
Alice public: 3059301306072A8648CE3D020106082A8648CE3D03010703420004D8FF8DAB9683C7D6C798FE381775AE3BCC25260E2B270C57584F684BFBF59A73221480040E70993F2F4DEBE25A19E772896F5C98DFAE6865C31830BBD876E8DF
Alice private: 308193020100301306072A8648CE3D020106082A8648CE3D030107047930770201010420A08DEC852618FA6BF0CA8B67DFFCC72AA39BE7402978CA456F73660337837DE1A00A06082A8648CE3D030107A14403420004D8FF8DAB9683C7D6C798FE381775AE3BCC25260E2B270C57584F684BFBF59A73221480040E70993F2F4DEBE25A19E772896F5C98DFAE6865C31830BBD876E8DF
Bob public: 3059301306072A8648CE3D020106082A8648CE3D03010703420004E4343FD573F117446925BBFE0DEF591098AA300066AB4F51DC2736736C8CE18BA72EA67AE4D0D6DD5E22007BA45BAA9DCE473002D17D6A29207AA15A1E97C596
Bob private: 308193020100301306072A8648CE3D020106082A8648CE3D030107047930770201010420D272E7BD59F7EA2AA3710910073AFE58082BC460B347A3782981CCCABA452538A00A06082A8648CE3D030107A14403420004E4343FD573F117446925BBFE0DEF591098AA300066AB4F51DC2736736C8CE18BA72EA67AE4D0D6DD5E22007BA45BAA9DCE473002D17D6A29207AA15A1E97C596
Bob secret: B65B4C8A1C797B867CE39F26DC97A0241A407FC79CF0D3CBA061A4A907CF3E1B
Alice secret: B65B4C8A1C797B867CE39F26DC97A0241A407FC79CF0D3CBA061A4A907CF3E1B

A: You don't necessarily need to send the curve, you can fix it in advance. As an important example Bitcoin, which uses ECDSA rather than ECDH, specifies secp256k1.
However, the code in your answer uses the encodings returned by Java PublicKey.getEncoded() and PrivateKey.getEncoded() which are 'X.509' (more precisely the SubjectPublicKeyInfo structure in X.509) and 'PKCS8' respectively; see the javadoc. These are both ASN.1 encodings that include an AlgorithmIdentifier containing parameters which for ECC define the curve either by an ASN.1 OBJECT IDENTIFIER aka OID or by a detailed specification of the underlying field, coefficients for the Weierstrass curve equation, base point, order and cofactor. In practice everyone uses the standard named curves which have OIDs. That is why 21 bytes beginning at offset 2 in all of your key printouts are identical; it's an ASN.1 SEQUENCE containing an OID for the algorithm (id-ecPublicKey) and an OID for the selected curve (prime256v1).
Other schemes are possible. TLS ECDHE sends either the curve details or a small integer identifying a standard curve as defined in rfc4492 of which the latter is almost always used; static-ECDH uses X.509 certs, and thus the X.509 format. SSH ECDH ephemeral or ECMQV sends a string containing the name or the OID, see rfc5656. CMS and thus S/MIME uses ASN.1 structures containing the AlgorithmIdentifier with OID-form namedCurve parameters, see rfc 5753.


text:
Q: Compactness and being finite-rank operators Suppose $T$ is a selfadjoint unbounded operator with compact resolvent on a given separable Hilbert space $H$, and $P$ a projection onto $\ker T$. Define $T_1$ to be $T+P$. Is it true that $|T_1|^{-1}$ is compact, $P$ is finite-rank operator and $|T_1|=|T|+P$?
If the answers are "not" what else should we assume about $T$ to get positive answers?
I am looking for some minimal condition of such perturbations. If we know that $P$ is compact then the last question has a positive answer. Does this condition follow from the compactness of the resolvent of $T$?

A: Yes to all your questions.
If $T$ is self-adjoint and has a compact resolvent then:

*

*$\sigma(T)$ is discrete with only accumulation point being $\infty$.

*There is a Hilbert basis of $H$ consisting of eigenvectors of $T$.

*Each eigenspace of $T$ is finite dimensional.

As an example, point 3. follows since if an eigenspace were infinite dimensional then $(z-T)^{-1}$ would also have an infinite dimensional eigenspace (to eigenvalue $\neq0$) contradicting compactness.
You may then write
$$T=\sum_{\lambda\in\sigma(T)} \lambda \,P_\lambda$$
where $P_\lambda$ is the projection onto the eigenspace of $\lambda$ (which is finite dimensional). Note that $|T|=\sum_{\lambda\in\sigma(T)}|\lambda|\,P_\lambda$ and that $T+P_0= \sum_{\lambda\in\sigma(T), \lambda\neq 0} \,\lambda\,P_\lambda+ 1\,P_0$, of which the absolute value is $|T+P_0|= \sum_{\lambda\neq 0}|\lambda|\,P_\lambda + 1\,P_0 = |T|+P_0$. Further you can see that
$$(T+P_0)^{-1} = \sum_{\lambda\neq0} \lambda^{-1}\,P_\lambda + P_0$$
which is globally defined (due to $0$ not being an accumulation point of $\sigma(T)$) and compact by the $P_\lambda$ all being finite dimensional and $\sigma(T)$ having no accumulation points other than $\infty$.


text:
Q: How to initialize specific class object inside a class? For example I have a class Number with predefined values 1, 2, 3.
class Number:
  one = Number(1)
  two = Number(2)
  three = Number(3)

  def __init__(self, val):
    self.value = val

But I get NameError: Number is not defined. How should I deal with this problem or what is the right way to do this?

A: Your class Number is not defined.
Is this what you want to do?
class Num:
    def __init__(self, val):
        self.value = val

class Number:
  one = Num(1)
  two = Num(2)
  three = Num(3)

  def __init__(self, val):
    self.value = val


text:
Q: Can this switch and while loop be simplified in C#? while (p3.Alive || p2.Alive)
        {
            Random rnd = new Random();
            int victim = rnd.Next(1, 3);

            switch (victim)
            {
                case 1:
                    p1.Attack(p2, 2);
                    break;
                case 2:
                    p1.Attack(p3, 2);
                    break;
            }

            Thread.Sleep(2000);
        }

p2 and p3 and objects of class Person. They are about to be killed off on random by the killer, p1. But when I look at it, I feel like there could be a better solution because what if I had 1000 objects of class Person ready to be killed? I just can't seem to get the p2 and p3 to be easily programmed variables.
The while loop is the same. What if I had 1000 objects. Or even just 10. How can I write this so that the condition is "while anyone but the killer is alive" and an "if" or "switch" which attacks anyone chosen by the Random rnd?
The question is badly written in the topic. I don't know how I could summarize all this into a short question. I'll edit it if anyone has a good suggestion. Thank you.

A: This seems like it is essentially a coin toss with 2 outcomes; 2 outcomes can be modelled with the "conditional" operator:
var target = rnd.Next(0,2) == 0 ? p2 : p3;
pi.Attack(target);

For larger groups, having the possible targets in a list or array may be useful; then you can essentially do:
var target = list[rnd.Next(list.Count)];

Or with C# 8, "switch expressions" may be useful:
var target = rnd.Next(4) switch (
   case 0: p1,
   case 1: p2,
   case 2: p3,
   case 3: p4,
   case _: default
);

A: Fixes for all issues:

*

*Only make one Random object

*Use a List to avoid repeated code

*Don't attack opponents that are no longer Alive

using System.Collections.Generic;             // provides the List type

Random rnd = new Random();
var opponents = new List<Player> { p2, p3 };  // add more as needed

while (true)
{
    opponents.RemoveAll(x => !x.Alive);  // only keep live enemies (efficient: does not create new List)
    if (opponents.Count == 0)            // if nobody left --> exit loop
        break;

    int victim = rnd.Next(0, opponents.Count);
    p1.Attack(opponents[victim]);
    Thread.Sleep(2000);
}


text:
Q: How to show files attached to Document with xp:fileDownload In an application I have files attached directly to the Notes document and not to the document via a Rich text field.
I would like to make those files available in the xp:fileDownload control but that allows only file binding to a Rich text object.

Binds the file control to a data element or other value which must be
  of type rich text.
  http://www-01.ibm.com/support/knowledgecenter/SSVRGU_9.0.0/com.ibm.designer.domino.ui.doc/wpd_controls_cref_filedownload.html

Is it possible to use the control somehow for making the files attached to the document available for download via this control?

A: try to download the file using domino url api
download

Domino URL


text:
Q: `obj.f(null)` in Java bytecode Is it safe to assume that obj.f(null) is always compiled to 2 consecutive instructions
ACONST_NULL
INVOKEVIRTUAL <type-of-obj> f <descriptor-of-f>

by javac, no matter where obj.f(null) appears in source code and how it is intermingled with other source code?
EDIT: I don't intend to do nullability check. I don't care about Object a = null; obj.f(a);.

EDIT: @OliverCharlesworth asked for my original problem. I want to detect obj.f(null) in bytecode with asm library. One can easily think of 2 ways of solving this problem.

*

*Use AnalyzerAdapter to verify whether the last element in stack is of type NULL when interested INVOKEVIRTUAL is called. This certainly works, but involves expanding stack frames, and is more expensive.

*Detect ACONST_NULL followed by INVOKEVIRTUAL. It probably works. But I'm not sure. Therefore, I'm asking the question here.

A: Assuming that obj.f is a non static, non interface, non superclass, non private method non inner/outer class method (edit: And also non varargs), then yes, I think it is safe to assume in practice. Of course, javac could always be changed tomorrow, but it is hard to immagine changing this, since it is the simplest and most natural way to compile the corresponding code.
Note that if any of the conditions listed above are true, it will probably be compiled differently. For example a static method will obviously use invokestatic instead of invokevirtual. If the method is being invoked on an outer class from an inner class, it will probably call a compiler generated synthetic method instead, and so on.


text:
Q: vuejs-paginate - switch to page 1 active class when pressing the navbar brand I'm using this handy pagination tool called vuejs-paginate and it works just fine in terms of functionality when I click each individual page item, but when I press the navbar brand (which switches to page 1), the pagination tool does not switch the active class to page 1 and the active class just remains on the page you were previously at.
Here's my pagination code:
<template>

                    <paginate
                        :page-count="20"
                        :click-handler="clickCallback"
                        :prev-text="'<'"
                        :next-text="'>'"
                        :container-class="'pagination'"
                        :page-class="'page-item'"
                        :page-link-class="'page-link'"
                        :next-class="'page-item'"
                        :next-link-class="'page-link'"
                        :prev-class="'page-item'"
                        :prev-link-class="'page-link'"
                        class="justify-content-center mb-0"
                    >
                    </paginate>

</template>

I was thinking of using some sort of way to programmatically click the first page item of the pagination when clicking on the navbar brand, but I'm not sure how to achieve this. Thanks for the help!

A: After a lot of debugging, I found out that it was actually where I had placed my pagination component. In my Nuxt app, I had put it inside default layouts. This means that when I had clicked on the navbar brand to go to the first page, the pagination did not remount. So what I did to resolve the problem was to transfer my pagination component to its individual pages. Now, when I switch from route to route, the active class will change because the pagination component remounts to react to the changes.


text:
Q: How to get Rancher scripts code when add agent to nodes hosts? Normally, get that code on master host's dashboard:
$ sudo docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher rancher/agent:v1.2.2 http://192.168.0.100:8080/v1/scripts/5D8B3FD489C00C7F361A:2483142400000:WvMClyNFLXQnT9pLuii3D0sYA

If want to deploy multiple nodes automatic to other hosts, it's necessary to get this code from master:

5D8B3FD489C00C7F361A:2483142400000:WvMClyNFLXQnT9pLuii3D0sYA

Then every node just add agent with this code is good. Is it right?
But, how to get it by cli from master?

A: Rancher has API, which enables you to interact with it remotely. What you require is called registrationTokens. Now, how to access them.
First, set up API tokens in your Rancher. Go to API -> Keys -> Add Account API Key and create the keys. If you can't find the buttons, your URL would be 192.168.0.100:8080/env/1a5/api/keys.
Now you know the keys and from remote host you can do something like this:
curl -u "${RANCHER_ACCESS_KEY}:${RANCHER_SECRET_KEY}" \
-X GET \
'http://192.168.0.100:8080/v2-beta/projects/1a5/registrationtokens'

Your result will be a JSON with required data:
{
...
    "data": [
    {
        "id": "1c3",
        "type": "registrationToken",
        "links": {
            ...
        },
        "actions": {
            ...
        },
        ...
        "command": "sudo docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher rancher/agent:v1.2.2 http://192.168.0.100:8080/v1/scripts/AAAAAAAAAAAAAAAAAAAA:0000000000000:ZZZZZZZZZZZZZZZZZZZZZZZZZZ",
        ...
    }],
...
}


text:
Q: Completion key vs extending the OVERLAPPED structure I am not sure what approach I should take when dealing with data associated with each socket. Should I use the completion key or should I extend the OVERLAPPED structure.
Extending the OVERLAPPED structure seems like a hack, so does it offer any advantages over the completion key?

A: The completion key is "per connection" data, that is it is the same on every completion for all operations on a given handle and is a good way to link to a "file" or "socket" structure.
The Overlapped is "per operation" data, each concurrent operation on a handle MUST use a unique overlapped structure. This makes it ideal to hold per operation data such as "type of operation" and associated memory (such as buffers), etc.
The "extended overlapped" isn't a hack, it's the way the design is supposed to be used.


text:
Q: methodnotallowedhttpexception in routecollection.php line 218 I know this is duplicate problem. Still I'm not able to correct this problem so can anyone help?
Routes.php
   Route::post('/form-submit',[
   'uses' => 'UserController@formSubmit',
   'as' => 'f.submit',
]);

UserController.php
public function formSubmit() #form-submit
{
   echo"Form Submit Method";
}

test_view.php
@extends('Layout.master')
@section('Content')
 {!! Form::open([
         'route' => 'f.submit', 'method' => 'post'
 ]) !!}
  {!! Form::test('username') !!}
  {!! Form::submit('submit')!!}
 {!! Form::close() !!}
@endsection

If I'm using get method for this code. then directly it is showing Form Submit Method and if I'm using post method then it is showing above error

A: You need to pass a csrf token along the request within the form.

A: i think
 //change '/form-submit' to 'f.submit'
    Route::post('/f.submit',[
       'uses' => 'UserController@formSubmit',
       'as' => 'f.submit',
    ])

and add csrf token also

A: I was getting directly "Form Submit Method" rather than it should open test_view form. I have a solution for it using POST or GET method.
    Route::post('/form-submit',['
        'uses' => 'UserController@formSubmit'
        'as' => 'f.submit'
  ']});

But POST method still not working.


text:
Q: + Sign converted to Space in iOS How to avoid it? I need to save the string in a server as input by the user.
i.e. ABCD[]{}#%^*+=
Server log = "password":"[]{}#%^* =" (+ sign replaced with space)
My Code
// Create Mutable Request
NSString *strHeaderField_ApplicationJson   = @"application/json";

NSString *strParameter   = @"userId=test@gmail.com&password=[]{}#%^*+=**";

NSData *parameterData = [strParameter dataUsingEncoding:NSASCIIStringEncoding
                                       allowLossyConversion:YES];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlEdit cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeInterval];

    [request addValue:strHeaderField_ApplicationJson forHTTPHeaderField:@"Contect-Type"];
    [request addValue:strHeaderField_ApplicationJson forHTTPHeaderField:@"Accept"];
    [request setHTTPMethod:HTTPMethodPost];
    [request setHTTPBody:parameterData];```

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable connectionError) {

    [[Singleton sharedManager] hideHUD];

    if (data.length > 0) {
        NSError *error;

        NSDictionary *responceDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        if (error) {
            [[Singleton sharedManager] showAlertTitle:MsgTitleError withMessage:MsgErrorOccured onView:self];
        }
        else {
            NSLog(@"responceDict : %@",responceDict);
            if ([responceDict valueForKey:@"status"]) {
                BOOL status = [[responceDict valueForKey:@"status"] boolValue];
                if (status) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        for (UIViewController *vc in self.navigationController.viewControllers) {
                            if ([vc isKindOfClass:[MyVehicleViewController class]]) {
                                [self.navigationController popToViewController:vc animated:true];
                                break;
                            }
                        }
                        [self.navigationController popViewControllerAnimated:true];
                    });
                }
                else {
                    [[Singleton sharedManager] showAlertTitle:MsgTitleError withMessage:[responceDict valueForKey:@"message"] onView:self];
                }
            }
            else {
                [[Singleton sharedManager] showAlertTitle:MsgTitleError withMessage:[responceDict valueForKey:@"message"] onView:self];
            }
        }
    }
    else {
        [[Singleton sharedManager] showAlertTitle:MsgTitleError withMessage:MsgConnectionErrorOccured onView:self];
    }
    [[Singleton sharedManager] hideHUD];
}];

[postDataTask resume];

A:  NSString *password = @"34^+=-";

 NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString: @"!*'();:@&=+$,/?%#[] "] invertedSet];
 NSString *encodedPassword = [password stringByAddingPercentEncodingWithAllowedCharacters: set];
 NSData *parameterData = [encodedPassword dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES];


text:
Q: Can not download Intellij via PPA - SSL certificate issue Hi am running Linux Mint 18.2 under VirtualBox (Windows host) and I have problem installing Intellij IDEA via PPA because of SSL certificate problem. Steps:
sudo add-apt-repository ppa:mmk2410/intellij-idea-community
sudo apt update
sudo apt install intellij-idea-community

Getting the following log:
The following additional packages will be installed:
  lib32ncurses5 lib32tinfo5 lib32z1 lib32z1-dev zlib1g-dev
The following NEW packages will be installed:
  intellij-idea-community lib32ncurses5 lib32tinfo5 lib32z1 lib32z1-dev zlib1g-dev
0 upgraded, 6 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/460 kB of archives.
After this operation, 1,541 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Selecting previously unselected package lib32tinfo5.
(Reading database ... 252386 files and directories currently installed.)
Preparing to unpack .../lib32tinfo5_6.0+20160213-1ubuntu1_amd64.deb ...
Unpacking lib32tinfo5 (6.0+20160213-1ubuntu1) ...
Selecting previously unselected package lib32ncurses5.
Preparing to unpack .../lib32ncurses5_6.0+20160213-1ubuntu1_amd64.deb ...
Unpacking lib32ncurses5 (6.0+20160213-1ubuntu1) ...
Selecting previously unselected package lib32z1.
Preparing to unpack .../lib32z1_1%3a1.2.8.dfsg-2ubuntu4.1_amd64.deb ...
Unpacking lib32z1 (1:1.2.8.dfsg-2ubuntu4.1) ...
Selecting previously unselected package zlib1g-dev:amd64.
Preparing to unpack .../zlib1g-dev_1%3a1.2.8.dfsg-2ubuntu4.1_amd64.deb ...
Unpacking zlib1g-dev:amd64 (1:1.2.8.dfsg-2ubuntu4.1) ...
Selecting previously unselected package lib32z1-dev.
Preparing to unpack .../lib32z1-dev_1%3a1.2.8.dfsg-2ubuntu4.1_amd64.deb ...
Unpacking lib32z1-dev (1:1.2.8.dfsg-2ubuntu4.1) ...
Preparing to unpack .../intellij-idea-community_2017.2.2-1_all.deb ...
--2017-08-29 17:48:04--  https://download-cf.jetbrains.com/idea/ideaIC-2017.2.2.tar.gz
Resolving download-cf.jetbrains.com (download-cf.jetbrains.com)... 146.112.252.204, 146.112.252.210, 146.112.252.211, ...
Connecting to download-cf.jetbrains.com (download-cf.jetbrains.com)|146.112.252.204|:443... connected.
ERROR: cannot verify download-cf.jetbrains.com's certificate, issued by 'O=Cisco,CN=Cisco Umbrella Secondary SubCA lon-SG':
  Unable to locally verify the issuer's authority.
To connect to download-cf.jetbrains.com insecurely, use ``--no-check-certificate'.
dpkg: error processing archive /var/cache/apt/archives/intellij-idea-community_2017.2.2-1_all.deb (--unpack):
 subprocess new pre-installation script returned error exit status 5
Processing triggers for libc-bin (2.23-0ubuntu9) ...
Processing triggers for man-db (2.7.5-1) ...
Errors were encountered while processing:
 /var/cache/apt/archives/intellij-idea-community_2017.2.2-1_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Of course I have the same SSL problem when trying downloading the idea manually from their website with chrome.
I could not find any thread regarding this issue but I know I could not recreate the problem with Ubuntu 16.04 (everything worked as expected).
Could some one provide me with explicit steps for solving this issue?

A: The most common issue with failed certificates is a wrong system time.
So make sure that the time on your machine is (at approximately) correct, ideally by configuring ntp (but manually entering it might be good enough as well).
$ sudo apt-get install ntpdate
$ sudo ntpdate-debian

Explanation
certificates are only valid during in a certain timeframe, e.g. from 2017-04-20 until 2017-10-20.
If your system has the time reset to (e.g.) 1970-01-01, you will not be able to access the webpage (as from your system's POV the certificate is invalid)

A: Did you try
sudo apt-get update
sudo apt-get install ca-certificates

before installing intellij-idea-community?

A: After investigating the problem further it seems to be related to the firewall in our office network.
Updating the /etc/resolv.conf to contain nameserver 8.8.8.8 instead of nameserver 127.0.1.1 solved the issue.


text:
Q: Error when concatenate square of a each digit of a number I'm doing a Codewars Challenge. I must square every digit of a number and concatenate them.
So, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
My code is below:
#include <math.h>

unsigned long long square_digits (unsigned n)
{
  // Count for digits
  int digits = log10(n) + 1, i = 0;

  // Array to store the split number
  int numDivided[digits];

  // Store concatenated numbers
  unsigned long long result = 0;

  if (n == 0)
  {
    return result;
  }

  // Split number and store their square
  while (n > 0)
  {
    numDivided[i] = pow(n % 10, 2);
    n /= 10;
    i++;
  }

  // Concatenated square of numbers
  for (i = digits - 1;i >= 0;i--)
  {
    if (numDivided[i] == 0)
    {
      result *= 10;
    }
    else
    {
      // Count digits of the current number
      digits = log10(numDivided[i]) + 1;

      // Multiply current result for 10^(digits)
      result *= pow(10, digits);

      // Add the current number to result
      result += numDivided[i];
    }
  }

    return result;
}

The test cases are below:
Test(test_suite, sample_tests)
{
    do_test(      3212u,                9414ull);
    do_test(      2112u,                4114ull);
    do_test(         0u,                   0ull);
    do_test(       999u,              818181ull);
    do_test(     10001u,               10001ull);
    do_test(3210987654u,    9410816449362516ull);
    do_test(3999999999u, 9818181818181818181ull); // :p
    do_test(   UINT_MAX,  164811681364948125ull);
}

The code works until the two last tests, so:
for n = 3999999999, expected 9818181818181818181, but got 9818181818181818449

I was think that the test case was wrong and check if the number was greater that ULLONG_MAX but it's less, so, all right.
What is my mistake at this point?

A:
What problems could i have with pow function? There is any alternative?

pow() typically returns, at best, a 53 significant bit result yet we have at least a 64-bit problem. powl() does not certianly help either as it may be as limiting as pow().  Do not use floating point functions for an integer problem. Using a floating point funtion for an integer problem is the wrong approach.
digits = log10(n) + 1 are numDivided[i] = pow(n % 10, 2) are not specified to get the desired value (due to imprecision) and certainly fail when n == 0.
Simple extract the least significant decimal digit with %10.  Scale by an integer type power-of-10.
unsigned long long square_digits(unsigned n) {
  unsigned long long nn = 0;
  unsigned long long pow10 = 1;

  while (n) {
    unsigned digit = n % 10;
    unsigned square = digit * digit;  // 0 to 81
    nn += square * pow10;
    if (square < 10) {
      pow10 *= 10;
    } else {
      pow10 *= 100;
    }
    n /= 10;
  }
  return nn;
}

A: The main culprit is this line:
result *= pow(10, digits);

Given that result is an unsigned long long while the return value of pow is a double, result is first converted to a double, then multiplied by the power and finally the result is converted back to an unsigned long long.
The problem is that while a double type has a much greater range than an unsigned long long, its precision is limited and not all the possible integral values can be represented (stored) exactly.
In particular, you can check the result of the following line:
printf("%.0lf\n", 981818181818181ull * 100.0);  // It won't print 98181818181818100

See @chux's answer for further details and a proper implementation of the solution.

A: I found two mistakes in your code.

*

*log() is not defined for 0. So, you cannot run your code against Test case 3.

*Use powl() instead of pow().

PS: One change you can do to pass test case 3 is check if N == 0 in the beginning of the function itself. The next script should calculate the number of digits in N.


text:
Q: Is it possible to plot on a surface in Matplotlib? In GNUPlot it is possible to plot a function on a surface (see, for example, this question). Similar thing can be done in Mathematica (see this question).
Is it possible to do the same thing in Matplotlib? Alternatively, is it possible to map the colourmap by the function that one intends to plot on the surface?
A good example of this is plotting an ellipsoid, and visualising the Gauss curvature at each point on it with the colourmap.


text:
Q: Java: what is the correct way to guarantee a non-final reference field will never be read as null? I'm trying to solve a simple problem and am falling into a Java Memory Model rabbit hole.
What is the simplest and/or most efficient (judgement call here), but race-free (precisely defined according to the JMM) way to write a Java class containing a non-final reference field which is initialized to a non-null value in the constructor and subsequently never changed, such that no subsequent access of that field by any other thread can see a non-null value?
Broken starting example:
public class Holder {

  private Object value;

  public Holder(Object value) {
    if (value == null)
        throw NullPointerException();
    this.value = value;
  }

  public Object getValue() {    // this could return null!
    return this.value;
  }
}

And according to this post, marking the field volatile doesn't even work!
public class Holder {

  private volatile Object value;

  public Holder(Object value) {
    if (value == null)
        throw NullPointerException();
    this.value = value;
  }

  public Object getValue() {    // this STILL could return null!!
    return this.value;
  }
}

Is this the best we can do??
public class Holder {

  private Object value;

  public Holder(Object value) {
    if (value == null)
        throw NullPointerException();
    synchronized (this) {
        this.value = value;
    }
  }

  public synchronized Object getValue() {
    return this.value;
  }
}

OK what about this?
public class Holder {

  private Object value;

  public Holder(Object value) {
    if (value == null)
        throw NullPointerException();
    this.value = value;
    synchronized (this) { }
  }

  public synchronized Object getValue() {
    return this.value;
  }
}

Side note: a related question asks how to do this without using any volatile or synchronization, which is of course impossible.

A: To safely publish a non-immutable object in Java, You need to synchronise the construction of the object and the write of the shared reference to that object. It's not just the internals of that object that matters in this question.
If you publish an object without proper synchronisation, with reordering, the consumer of a Holder object can still see a partially constructed object if the reference to the object got published before the constructor finishes. For example Double-checked locking without volatile.
There are several ways to publish an object safely:

*

*Initialising a reference from a static initializer;

*Storing a reference to it into a volatile field or AtomicReference

*Storing a reference to it into a final field of a properly constructed object; Or

*Storing a reference to it into a field that is properly guarded by a lock.

Note that those bullet points are talking about the reference to the Holder object, not fields of the class.
So the easiest way would be the first option:
public static Holder holder = new Holder("Some value");

Any thread accessing the static field is going to see a properly constructed Holder object.
See Section 3.5.3 "Safe publication idioms" of Java Concurrency in Practice. For more information about unsafe publication, see Section 16.2.1 of Java Concurrency in Practice.

A: The problem you are trying to solve is called safe publication and there exist benchmarks for a best performant solution. Personally, I prefer the holder pattern which also performs the best. Define a Publisher class with a single generic field:
class Publisher<T> {
  private final T value;
  private Publisher(T value) { this.value = value; }
  public static <S> S publish(S value) { return new Publisher<S>(value).value; }
}

You can now create your instance via:
Holder holder = Publisher.publish(new Holder(value));

Since your Holder is dereferenced via a final field, it is guaranteed to be fully initialized by the JMM after reading it from the same final field.
If this is the only usage of your class, then you should of course add a convenience factory to your class and make the constructor itself private to avoid unsafe construction.
Note that this performs very well as modern VMs erase the object allocation after applying escape anaysis. The minimal performance overhead comes from the remaining memory barriers in the generated machine code which are however required to safely publish the instance.
Note: The holder pattern is not to be confused with your example class being called Holder. It is the Publisher that implements the holder pattern in my example.

A: See section 17.5 of the Java Language Specification.

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

In other words, as long as we are careful not to leak this from the constructor of Holder to another thread, we can guarantee that other threads will see the proper (non-null) value of ref without additional synchronization mechanisms.
class Holder {

  private final Object ref;

  Holder(final Object obj) {
    if (obj == null) {
      throw new NullPointerException();
    }
    ref = obj;
  }

  Object get() {
    return ref;
  }
}

If you're seeking a non-final field, recognize we can use synchronized to enforce that get does not return until ref is non-null and also ensure a proper happens-before relationship (see: memory barrier) holds on the wrapped reference:
class Holder {

  private Object ref;

  Holder(final Object obj) {
    if (obj == null) {
      throw new NullPointerException();
    }
    synchronized (this) {
      ref = obj;
      notifyAll();
    }
  }

  synchronized Object get() {
    while (ref == null) {
      try {
        wait();
      } catch (final InterruptedException ex) { }
    }
    return ref;
  }
}

A: It is not possible to guarantee that a non-final reference will never be null.
Even if you initialize it correctly and guarantee not null in the setter,
it is still possible to set the reference to null via reflection.
You can limit the chances of returning a null reference by declaring the getter to be final and never returning null from the getter.
It is; however, still possible to override the final getter and force it to return null.  Here is a link that describes how to mock a final method: Final method mocking
If they can mock a final method, anybody can, using the same technique, override a final method and make it function poorly.