text:
Q: The first string argument to a stringstream is saved as a pointer/garbage
Possible Duplicate:
Printing a string to a temporary stream object in C++
std::ostringstream printing the address of the c-string instead of its content

I'm trying to build up a string using stringstream, in the same way you'd use cout. This for something like a logging class. The issue I'm having is that if the first argument to the << operator is a string, when I subsequently print out that stringstream with the stringstream::str() call, I get a garbage address, and not the string. This only occurs with the FIRST string. Subsequent strings are fine. Numbers are always fine. Here's the code:
    // class I use to print out the stream
    class StreamWriter
    {
    public:
        StreamWriter()
        {}

        ~StreamWriter()
        {
            std::string myMessage = m_stringstream.str();
            std::cout << myMessage << std::endl;
        }

        std::stringstream m_stringstream;
    };

    // macro for simplification
    #define OSRDEBUG (StreamWriter().m_stringstream)

    // actual use
    OSRDEBUG << "Hello " << "my " << "name is Pris " << 123456;

    // output
    0x8054480my name is Pris 123456
    0x8054480my name is Pris 123456
    0x8054480my name is Pris 123456
    0x8054480my name is Pris 123456

Could anyone shed some light on what's going on, and how I could get around the issue?
EDIT:
The following changes (in addition to padiablo's examples) works as well, maintaining the use of the class's destructor with the macro.
    // class I use to print out the stream
    class StreamWriter
    {
    public:
        StreamWriter()
        {   m_stringstream = new std::stringstream;   }

        ~StreamWriter()
        {
            std::string myMessage = m_stringstream.str();
            std::cout << myMessage << std::endl;
            delete m_stringstream;
        }

        std::stringstream * m_stringstream;
    };

    // macro for simplication
    #define OSRDEBUG *(StreamWriter().m_stringstream)

The original question still stands though, because it looks like it should work... and I think it's probably important to know when the times comes to put this into production-quality code.

A: The problem is indeed that the stream is a temporary.
Before C++11, there was no non-member operator<< overload that took an rvalue reference as the first parameter (aka, allowing writes to temporary streams).
As such, the only valid operator<< overloads were the members, since all non-member overloads take a non-const reference and as such will not bind to temporaries. One of those non-member overloads is the one responsible for printing C strings (aka char const*). Here's one of the member overloads:
basic_ostream<Ch, Traits>& operator<<(void* p);

And guess what your string literal liberally converts to. :)
After the first string, you get a normal reference back from the call to operator<<, which will then allow the non-member overloads to be viable.

A: I honestly don't understand exactly what's going on (it has something to do with your StreamWriter instance being a temporary), but I see the same effect as paxdiablo described in both GCC and MSVC.
However, here's something that can work around the problem.  Add the following helper to your StreamWriter class:
    ostream& get_ostream() {
        return m_stringstream;
    }

and change the macro to:
#define OSRDEBUG (StreamWriter().get_ostream())

A: It appears to be a consequence of the way you're instantiating the object. I'm still investigating (and you may get a better answer in the meantime) but explicitly instantiating the object works fine:
#include <iostream>
#include <sstream>

class StreamWriter {
public:
    StreamWriter() {}
    ~StreamWriter() { std::cout << m_stringstream.str() << std::endl; }
    std::stringstream m_stringstream;
};

int main (void) {
    StreamWriter *sw = new StreamWriter();
    sw->m_stringstream << "Hello " << "my " << "name is Pris ";
    delete sw;
    return 0;
}

As does instantiating on the stack as well:
int main (void) {
    StreamWriter sw;
    sw.m_stringstream << "Hello " << "my " << "name is Pris ";
    return 0;
}

Both of those print out what you expect but the following simplification of your code does not:
int main (void) {
    StreamWriter().m_stringstream << "Hello " << "my " << "name is Pris ";
    return 0;
}

If you're just after a solution, you can probably get by with:
#define ORSDEBUG StreamWriter sw; sw.m_stringstream

and ensuring you scope-protect the command so that it doesn't try to create more then one sw, and also that it's destroyed at the correct time, same as your original attempt:
{ ORSDEBUG  << "Hello " << "my " << "name is Pris"; }

A: I have tried a couple of alternatives, and the only thing I got working is something like this:
#define OSRDEBUG(s)                 \
    do                              \
    {                               \
        StreamWriter writer;        \
        writer.m_stringstream << s; \
    } while (0)

OSRDEBUG("Hello " << "my " << "name is Pris " << 123456);

I have personally used the above construct for my own logging solutions many times, and seen it done by others as well.
I'm not good enough to know why your example doesn't work, but I guess it has something to do with temporaries not staying alive long enough.


text:
Q: Electron Geolocation Network location provider So I've got this code:
navigator.geolocation.getCurrentPosition(console.log, console.error, {timeout:5000});

And its returning the following error:
GeolocationPositionError {code: 2, message: "Network location provider at
'https://www.googleapis.com/' : No response received."}
code: 2 message: "Network location provider at 'https://www.googleapis.com/' : No response received."

I dont seem to find any solution for this. I've already tried to set process.env.GOOGLE_API_KEY = config.GoogleAPIKeys.GeolocationAPI; (the config part is right I double checked it)
And I also switched to ssl (https) and added this in order for electron to diplay it  app.commandLine.appendSwitch('ignore-certificate-errors', 'true');
Thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Receive UDP packet to Class. Design/Implementation assistance appreciated I receive UDP data from localhost.  This data needs to be used and kept track of.  There could be  >250k packets sent over the course of about 5 minutes. Currently, I create the IPEndPoint, and Receive the data.  I then get the byte[] data into a string.  Then I split the string into an array because the data is comma separated.  From this array, I instantiate an object with the correct values from the array.
The incoming data has 4 properties and looks like this:  ProductId=1284,Quantity=48623,Time=08:45:12.034,Date=2019-09-09
Currently I am able to Console.WriteLine the incoming packets, and cast each packet to an object (Product).  Currently I do not store the data anywhere.
I need to monitor Quantity levels, and send alerts if the Quantity goes above or below certain thresholds.  Secondly, I need to send another alert if the change in Quantity exceeds thresholds. This I will implement with if statements later and do not require assistance with at the moment.  This alerts do need to be sent as UDP packets are received.
My questions are:
1)  Should I implement this Asynchronously, or on a different thread?
2) Should I be sending the UDP Data directly to a Queue of type byte[], and then Dequeue each byte[] into an object? or keep instantiating new objects (or updating the quantity for each product) on the fly as the UDP data is received?  Does Queue reduce the risk of dropped packets?
3)  What is the best way to store each packet? To a List (This would keep everything in memory), a database (A bit beyond my current needs), or append each object to a text file (easy to write to, and can eventually build a database from)?
4) Is 250k packets over 5 minutes, and creating objects for all those packets considered a lot for a computer to handle?
Please advise if I can clarify anything.  I apologize if any of my terminology is incorrect, I will learn and fix it.  The coding I should be able to figure out on my own, it is the design and proper implementation that I am asking for guidance on. Thank you.
Below is code for setting up the UDP connection, and the class.  I will be able to figure out the monitoring/messaging Quantity information after the UDP has been setup properly.  I do have a Product Class not shown, it has several properties including ProductId, Quantity, Initial Quantity, Change in Quantity, Time and Date.
class Program
    {
        static void Main(string[] args)
        {
            int port = 22486;
            var client = new UdpClient();
            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port);
            client.Client.Bind(localEp);

            while (true)
            {
                try
                {
                    byte[] data = client.Receive(ref localEp);
                    string text = Encoding.UTF8.GetString(data);
                    string[] message = text.Split(',', '=');
                    Product product = new Product();
                    product.ProductId = message[1];
                    product.Quantity = message[3];
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.ToString());
                }
            }
        }
    }

A: *

*If you need to do other things while listening on that port, make it a thread.

*queue it up in a byte array... a buffer of sorts.

*Are azure blobs an option for you? you can use the storage emulator and if you change your mind about storing a file in blob, you can switch to table storage (this is like a nosql approach where you provide a partition name.)

*No


text:
Q: why sklearn SelectFromModel estimator_.coef_ return a 2d-array I asked in Cross Validated before but it seems it should be proper to ask here.
My data df_X has 11 features, and y is the multi-class label (3,4,5,6,7,8 in samples). I used multi-class SVM to select the importance of features. estimator_.coef_ should return the score of each feature (a list of 11 scores). But why here it returns a list of scores? The same case occurred for multi-class LogisticRegression().
By the way, what's the difference between SelectKBest and SelectFromModel for feature selection in sklearn.

A: I tried to reproduce your case using iris dataset with 4 features; nevertheless, you can try to extend this experiment with diabetes dataset, which has 10 features close to your dataset, as shown below:
#Read and load sample dataset
from sklearn.datasets import load_iris, load_diabetes

X, y = load_iris(return_X_y=True)
iris = load_iris()
X, y = iris.data, iris.target

#Data Set Characteristics
#print(iris.DESCR)

#Fit SVC to data and extract results of feature selection
from sklearn.feature_selection import SelectFromModel
from sklearn.svm import SVC
from time import time

tic = time()
selector = SelectFromModel(estimator=SVC(kernel = 'linear')).fit(X, y)
toc = time()

#Plot the results
import matplotlib.pyplot as plt
import numpy as np
importance = np.abs(selector.estimator_.coef_)
feature_names = np.array(iris.feature_names)
print(f"Features selected by SelectFromModel: {feature_names[selector.get_support()]}")
#-->Features selected by SelectFromModel: ['petal length (cm)' 'petal width (cm)']
print(f"Done in {toc - tic:.3f}s") #-->Done in 0.002s
#print(X.shape) #-->(150, 4)
#print(selector.transform(X).shape) #-->(150, 2)
plt.bar(height=importance[1], x=feature_names)
plt.xticks(rotation=45, ha='right')
plt.title("Feature importances via coefficients")
plt.show()

So I inspired this post to reflect the results in plot:

print(selector.threshold_)
print(selector.estimator_.coef_)
print(selector.estimator_.coef_.shape) #-->(3, 4)

#2.1645593987132914
#[[-0.04625854  0.5211828  -1.00304462 -0.46412978]
# [-0.00722313  0.17894121 -0.53836459 -0.29239263]
# [ 0.59549776  0.9739003  -2.03099958 -2.00630267]]

Why sklearn SelectFromModel estimator_.coef_ return a 2d-array?

If you check the input and output of the selector model, both are 2-dimension arrays.  It makes sense for the output of selector.estimator_.coef_ since SelectFromModel() as a meta-transformer selects features based on importance weights estimation pairwisely in coef_ matrix.
print(X.ndim)                         #-->2d-array
print(selector.estimator_.coef_.ndim) #-->2d-array

Also based on this post, you can check if there is a zero vector in matrice or simply use get_support() to return a boolean array mapping the selection of each feature:
X_new = selector.transform(X)
print(X_new.shape)            #-->(150, 2)
print(selector.get_support()) #-->[False False  True  True]

By the way, what's the difference between SelectKBest and SelectFromModel for feature selection in sklearn.

Based on the documentation of
SelectKBest() it selects features according to the k highest scores. It "removes all but the k highest scoring features" Reference. It is used commonly with chi2() to "Compute chi-squared stats between eachfor non-negative feature and class." Here is good start point for comparison.
Edit:
I also found the workaround here about regularisation to remove non-important features from the dataset and played with coef. and updated the post:
selector.transform(X)
#print(selector.transform(X))

features = array(iris.feature_names)
print("All features:", features)
#All features: ['sepal length (cm)' 'sepal width (cm)' 'petal length (cm)' 'petal width (cm)']

print("Selected features:", features[status])
#Selected features: ['petal length (cm)' 'petal width (cm)']

# note here the absolute transformation before the mean
print("absolute transformation before the mean:", abs(selector.estimator_.coef_).mean()*1.25)
#absolute transformation before the mean: 1.3025301767884683

print('features with coefficients shrank to zero: {}'.format(np.sum(selector.estimator_.coef_ == 0)))
#features with coefficients shrank to zero: 0


text:
Q: How to return Specific Class types without a large Select/Switch I'm building a series of classes in an attempt to reduce the manual coding of specific class types from the mainline code.
Whichever way I look there is always somewhere that requires manual coding of the specific class type.
I was hoping that I could use reflection/activator etc to be able to use the work done in the constructor to be able to return the classtypes (of the correct type) without needing to do the large (although the example here has been reduced) select/switch statement that is in GetPacket.
I know this is VB.Net, but the project was already written in that language, I don't mind if you post C# examples I'll just convert them.
But please don't retag as a VB.Net question because it's not about language it's about how to do it within the framework.
Imports ProtoBuf

Public Class CompatiblePackets
    Inherits Dictionary(Of Packet.PacketType, Base)

    Public Sub New()
        Dim theAssembly As Assembly = Assembly.GetExecutingAssembly
        For Each t As Type In theAssembly.GetTypes
            If t.BaseType Is GetType(Base) Then
                Dim p As Base = CType(t.Assembly.CreateInstance(t.FullName), Base)
                Me.Add(p.PacketTypeIndicator, p)
            End If
        Next
    End Sub

    Public Function GetPacket(id As PacketType, data As Stream) As Base
        Dim activePacket As Base
        If Me.ContainsKey(id) Then
            activePacket = Me(id)
        Else
            activePacket = Me(PacketType.Generic)
        End If
        Try
            Select Case id
                Case PacketType.AcknowledgeBulk
                    Return GetPacket(Of AcknowledgeBulk)(activePacket, data)
                Case PacketType.Generic
                    Return GetPacket(Of Generic)(activePacket, data)
                Case PacketType.Identification
                    Return GetPacket(Of Identification)(activePacket, data)

    '''There are so far about 20 more packet types in the real code.

                Case Else
                    'unknown type "Computer says No!"
            End Select
        Catch ex As Exception
            If data.GetType Is GetType(MemoryStream) Then
                Debug.Print(Core.Text.OutputData(CType(data, MemoryStream).ToArray))
            End If
            Throw
        End Try
        Debug.Print("Wtf - " & id.ToString())

        Return New NoOperation
    End Function

    Private Function GetPacket(Of t)(activePacket As Packet.Base, data As Stream) As t
        Return Serializer.Deserialize(Of t)(data)
    End Function
End Class

A: If I understand the question correctly, it looks like you should be using Serializer.NonGeneric; this has various methods for passing the Type in manually and without using generics, including Serialize and Deserialize.
Note that for this scenario, Serializer.NonGeneric also has a specific API for heterogeneous header-marked messages, which you may find useful for a network-stream scenario:
static void Main() {
    // memory-stream only for example - would work fine with NetworkStream too
    using(var ms = new MemoryStream()) {
        // this is just to simulate an incoming network-stream
        Serializer.SerializeWithLengthPrefix(ms, new Foo { Name = "abc" },
           PrefixStyle.Base128, 1); // tag 1 for Foo
        Serializer.SerializeWithLengthPrefix(ms, new Bar { Value = 123 },
           PrefixStyle.Base128, 2); // tag 2 for Bar
        ms.Position = 0;

        // now we'll consume it

        //first setup some map of 1=Foo, 2=Bar - any mechanism will suffice
        var typeMap = new Dictionary<int, Type>{
            {1, typeof(Foo)},
            {2, typeof(Bar)}
        };
        Serializer.TypeResolver resolver = i => {
            Type type;
            return typeMap.TryGetValue(i, out type) ? type : null;
        };
        object obj;
        while(Serializer.NonGeneric.TryDeserializeWithLengthPrefix(
            ms, PrefixStyle.Base128,resolver,out obj))
        {
            Console.WriteLine(obj);
        }
        Console.WriteLine("<EOF>");

    }
}
[ProtoContract]
class Foo {
    [ProtoMember(7)]
    public string Name{ get; set; }

    public override string ToString() { return "Foo: " + Name; }
}
[ProtoContract]
class Bar {
    [ProtoMember(4)]
    public int Value { get; set; }

    public override string ToString() { return "Bar: " + Value; }
}

This outputs:
Foo: abc
Bar: 123
<EOF>

In v2, note that TypeModel exposes the non-generic API as the primary interface (the Serializer API simply acts as a proxy to the default model).

A: I haven't tested this, but I think your only option is a delightful hodgepodge of reflection goodness:
Private Function GetPacket(oPacketType As PacketType, data As Stream) As Base

    Dim oDeserializeMethod As System.Reflection.MethodInfo
    Dim oGenericMethod As System.Reflection.MethodInfo
    Dim oType As Type

    ' Fetch the System.Type for the current packet type.
    ' This assumes that the enum and the class names are the same
    oType = System.Reflection.Assembly.GetExecutingAssembly.GetType(oPacketType.ToString)

    ' Fetch the deserialize method from Protobuf Serializer
    oDeserializeMethod = GetType(Serializer).GetMethod("Deserialize")

    ' Create a generic method from the deserialize method
    oGenericMethod = oDeserializeMethod.MakeGenericMethod(oType)

    ' And finally, invoke the method
    Return TryCast(oGenericMethod.Invoke(Serializer, Data), Base)
End Function

Then you could call this without a need for a case statement:
Return GetPacket(id, data)


text:
Q: Android save Checkbox State in ListView with Cursor Adapter I cant find a way to save the checkbox state when using a Cursor adapter. Everything else works fine but if i click on a checkbox it is repeated when it is recycled. Ive seen examples using array adapters but because of my lack of experience im finding it hard to translate it into using a cursor adapter. Could someone give me an example of how to go about it. Any help appreciated.
private class PostImageAdapter extends CursorAdapter {

    private static final int s = 0;
    private int layout;
    Bitmap bm=null;
    private String PostNumber;
    TourDbAdapter mDbHelper;

    public PostImageAdapter (Context context, int layout, Cursor c, String[] from, int[] to, String Postid) {

        super(context, c);
        this.layout = layout;
        PostNumber = Postid;

     mDbHelper = new TourDbAdapter(context);
     mDbHelper.open();

    }

    @Override
    public View newView(Context context, final Cursor c, ViewGroup parent) {

     ViewHolder holder;

     LayoutInflater inflater=getLayoutInflater();
     View row=inflater.inflate(R.layout.image_post_row, null);

   holder = new ViewHolder();

   holder.Description = (TextView) row.findViewById(R.id.item_desc);
   holder.cb = (CheckBox) row.findViewById(R.id.item_checkbox);
   holder.DateTaken = (TextView) row.findViewById(R.id.item_date_taken);
   holder.Photo = (ImageView) row.findViewById(R.id.item_thumb);

   row.setTag(holder);

 int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE);
 String Date = c.getString(DateCol);

 int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION);
 String Description = c.getString(DescCol);

 int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME);
 final String FileName = c.getString(FileNameCol);

 int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID);
 String RowID = c.getString(PostRowCol);

 String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg";
 Bitmap bm = BitmapFactory.decodeFile(Path, null);

 holder.Photo.setImageBitmap(bm);
 holder.DateTaken.setText(Date);
 holder.Description.setText(Description);

 holder.cb.setOnClickListener(new OnClickListener() {
    @Override
 public void onClick(View v) {
    CheckBox cBox = (CheckBox) v;
    if (cBox.isChecked()) {

      mDbHelper.UpdatePostImage(FileName, PostNumber);

    }
    else if (!cBox.isChecked()) {
      mDbHelper.UpdatePostImage(FileName, "");

    }

  }
});
return row;

};

    @Override
    public void bindView(View row, Context context, final Cursor c) {

     ViewHolder holder;
     holder = (ViewHolder) row.getTag();

      int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE);
         String Date = c.getString(DateCol);

         int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION);
         String Description = c.getString(DescCol);

         int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME);
      final String FileName = c.getString(FileNameCol);

      int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID);
         String RowID = c.getString(PostRowCol);

      String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg";
         Bitmap bm = BitmapFactory.decodeFile(Path, null);

        File x = null;

         holder.Photo.setImageBitmap(bm);
         holder.DateTaken.setText(Date);
         holder.Description.setText(Description);

         holder.cb.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
         CheckBox cBox = (CheckBox) v;
         if (cBox.isChecked()) {

               mDbHelper.UpdatePostImage(FileName, PostNumber);

         }
         else if (!cBox.isChecked()) {
               mDbHelper.UpdatePostImage(FileName, "");

         }

        }
       });

    }

}

static class ViewHolder{
  TextView Description;
  ImageView Photo;
  CheckBox cb;
  TextView DateTaken;
}
}

A: I had the same issue myself: how to toggle multiple select CheckedTextView in a custom layout (i.e not using android.R.layout.simple_list_item_multiple_choice)
The following worked for me. The example I have is a custom view that is provided an adaptor extended from SimpleCursorAdapter.
My custom view (row_contact.xml):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="wrap_content" android:layout_width="fill_parent">

  <CheckedTextView
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    />

  <TextView
    android:text="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvNumber"
    android:layout_gravity="bottom"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
    />

</FrameLayout>

The adaptor is created in ListActivity.OnCreate, which calls setupViews():
  private void setupViews() {
    bOk       = (Button) findViewById(R.id.ButtonOK);
    bCancel   = (Button) findViewById(R.id.ButtonCancel);
    FListView = getListView();
    //
    bOk.setText("Select");
    //
    FListView.setItemsCanFocus(false);
    FListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    //
    bOk.setOnClickListener(this);
    bCancel.setOnClickListener(this);
    //
    ContentResolver content = getContentResolver();
    Cursor cursor = ApplicationHelper.MobilePhoneContacts(content);
    startManagingCursor(cursor);

    ListAdapter adapter = new CheckedCursorAdapter( SelectContacts.this, R.layout.row_contact, cursor,
        new String[] {People.NAME, People.NUMBER},
        new int[] {android.R.id.text1, R.id.tvNumber});
    setListAdapter(adapter);
  }

The Custom adaptor:
  public class CheckedCursorAdapter extends SimpleCursorAdapter {

    Activity context;
    Cursor c;

    public CheckedCursorAdapter(Activity context, int rowContact, Cursor cursor, String[] strings, int[] is) {
      super(context, rowContact, cursor, strings, is);
      this.context = context;
      this.c = cursor;

    }

    public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      ContactRowWrapper wrapper;

      if (row == null) {
        LayoutInflater inflater=context.getLayoutInflater();
        row = inflater.inflate(R.layout.row_contact, null);
        //
        wrapper = new ContactRowWrapper(row);
        row.setTag(wrapper);
      } else {
        wrapper = (ContactRowWrapper)row.getTag();
      }
      c.moveToPosition(position);
      wrapper.getTextView().setText( c.getString(c.getColumnIndex(Contacts.People.NUMBER)) );
      wrapper.getcheckBox().setText( c.getString(c.getColumnIndex(Contacts.People.NAME)) );
      wrapper.getcheckBox().setChecked(getListView().isItemChecked(position));
      //
      return row;
    }

  }

The crucial bit of code for for me was to get check boxes working was:
wrapper.getcheckBox().setChecked(getListView().isItemChecked(position));

Hope this helps you or anyone else who stumbles onto this question.
Also, pardon my Java noobness... I've only started Java a few weeks ago.

A: I would recommend you use Android's built-in support for multiple-choice lists (CHOICE_MODE_MULTIPLE).
The List11.java SDK sample demonstrates this. You can also find a project from one of my tutorials that uses it here.
You can still use this technique with your own layout, so long as you include a CheckedTextView with android:id="@android:id/text1" as shown in the android.R.layout.simple_list_item_multiple_choice resource, a copy of which ships with your SDK.
Also, see this question and this question and this question and this question.

A: Declare the CheckBox on getView Method and use this code
CheckBox  checkBtn =(CheckBox) convertView.findViewById(R.id.phCheckBox);
                 checkBtn.setChecked(Boolean.parseBoolean((vList.get(position).getCheckBtnStatus())));

             checkBtn.setOnClickListener(new OnClickListener()
              {

                  public void onClick(View arg0)
                  {

                      if(checkBtn.isChecked()==true)
                          {
                          vList.get(position).setCheckBtnStatus("true");

                        System.out.println("vList.get(position)---"+vList.get(position).getCheckBtnStatus()+" -"+position);
                          }
                      else
                      {
                          vList.get(position).setCheckBtnStatus("false");
                        System.out.println("else vList.get(position)---"+vList.get(position).getCheckBtnStatus()+"-"+position);
                      }

                  }
              });

After that on the main Activity u have to check which position of checkbox is true
save.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            for (int i = 0; i < newList.size(); i++) {
                UserData v1 = newList.get(i);
                status = Boolean.parseBoolean(v1.getCheckBtnStatus());

                if (status == true) {

                            //write ur code here
                }

            }});

A: 3. Code Code
Attach listeners inside your activity "onCreate()" method, to monitor following events :

If checkbox id : "chkIos" is checked, display a floating box with message "Bro, try Android".
If button is is clicked, display a floating box and display the checkbox states.
File : MyAndroidAppActivity.java

package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private CheckBox chkIos, chkAndroid, chkWindows;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnChkIos();
    addListenerOnButton();
  }

  public void addListenerOnChkIos() {

    chkIos = (CheckBox) findViewById(R.id.chkIos);

    chkIos.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
                //is chkIos checked?
        if (((CheckBox) v).isChecked()) {
            Toast.makeText(MyAndroidAppActivity.this,
               "Bro, try Android :)", Toast.LENGTH_LONG).show();
        }

      }
    });

  }

  public void addListenerOnButton() {

    chkIos = (CheckBox) findViewById(R.id.chkIos);
    chkAndroid = (CheckBox) findViewById(R.id.chkAndroid);
    chkWindows = (CheckBox) findViewById(R.id.chkWindows);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

          //Run when button is clicked
      @Override
      public void onClick(View v) {

        StringBuffer result = new StringBuffer();
        result.append("IPhone check : ").append(chkIos.isChecked());
        result.append("\nAndroid check : ").append(chkAndroid.isChecked());
        result.append("\nWindows Mobile check :").append(chkWindows.isChecked());

        Toast.makeText(MyAndroidAppActivity.this, result.toString(),
                Toast.LENGTH_LONG).show();

      }
    });

  }
}

A:

*CheckBox
Open "res/layout/main.xml" file, add 3 "CheckBox" and a button, inside the LinearLayout.

File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <CheckBox
        android:id="@+id/chkIos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_ios" />

    <CheckBox
        android:id="@+id/chkAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_android"
        android:checked="true" />

    <CheckBox
        android:id="@+id/chkWindows"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_windows" />

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />

</LinearLayout>


text:
Q: Implement GetRoleAsync method with field in the Database I need to implement the role retrieval method in identity. Currently I do GetRoleAsync (id) and I pull out all user roles.
But when I remove a role from the user, I don't want to delete it, but deactivate it.
So I would like to tell GetRoleAsync (id) to pull out all roles with ENABLED = true
How can I do?

A: I suggest you can use build-in RemoveFromRoleAsync method to remove role reference with current user:
//get current user
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _userManager.FindByIdAsync(userId);
//remove role from current user
await _userManager.RemoveFromRoleAsync(user, "TheRoleName");


text:
Q: webview consumes too much RAM memory? I am developing an android Reader application., in that i am using web view to load HTML pages. to load an HTML page in the web view take too much ram memory ie around 50-100 mb for a 1 mb html page. Is there any way to fix this issue?
Thanks


text:
Q: Why IE browser show "scanstyles does nothing in webkit/firefox internet explorer"? In IE browser show some time this script error scanstyles does nothing in webkit/firefox/opera.
Can we fix this issue on our code?

A: Locate curvycorners.js and comment out
curvycorners.alert("Scanstyles does nothing in ...");
See http://www.witti.ws/blog/2013/12/09/scanstyles-does-nothing-webkitfirefox for a more complete explanation.


text:
Q: draw rectangle on canvas between 2 points I'm new to javascript and trying to learn how to draw on a canvas. The task is to draw a rectangle between 2 clicked points on a canvas.

let rectangle = 0;

window.addEventListener("load", () => {
  const canvas = document.getElementById("myCanvas");
  const context = canvas.getContext("2d");
  let x;
  let y;
  canvas.addEventListener("click", (e) => {
    if (rectangle === 0) {
      x = e.clientX;
      y = e.clientY;
      ++rectangle;
    } else {
      xprim = e.clientX;
      yprim = e.clientY;

      context.beginPath();
      context.fillRect(x, y, xprim - x, yprim - y);
      context.stroke();
      rectangle = 0;
    }
  })
})
.canvas_for_rectangle{
    border: 1px solid black;
    height: 50%;
    width: 50%;
}
<canvas id="myCanvas" class="canvas_for_rectangle">

Nothing is being shown on the canvas and I have no idea of what is not being done correctly as I am extremely new to the language. What am I doing wrong and what do I have to research?

A: Do you need to make the canvas bigger? It's default size is only 300x150 if I remember right, so you might simply be drawing outside of that area. The size you give it with CSS isn't relevant for drawing. I would remove your CSS for now and do:
canvas.width = window.innerWidth
canvas.height = window.innerHeight


text:
Q: jquery+validation multiple dropdowns please advise me how one can validate multiple dropdowns in a form, validation should trigger if same value is selected in different dropdowns.
here, if i select same option from both the dropdown it should trigger validation.
(i am using jquery validation engine for form validations)
<select name="user[role_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

<select name="user[role_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

thanks

A: Easiest way is to map the selections and look for dupes.  There are better algorithms to look for dupes (i.e. exit as soon as you detect a duplicate), but I opted to use shorter code since the cost is very low: http://jsfiddle.net/rkw79/vqENk/
function HasDupe(){
    a = $('select').map(function(i,o) {
        return $(o).val();
    });
    return (a.length != $.unique(a).length);
}

A: <select name="user[role_id]">
   <option value="0">Please select</option>
   <option value="1" selected="selected">Administrator</option>
   <option value="2">User</option>
   <option value="3">Editor</option>
</select>

<select name="user[role_id]">
   <option value="0">Please select</option>
   <option value="1" selected="selected">Administrator</option>
   <option value="2">User</option>
   <option value="3">Editor</option>
</select>
<script type="text/javascript">
  $(document).ready(function(e){
          if ($('select[name="user[role_id1]"]').val() == $('select[name="user[role_id2]"]').val()) {
        alert('select different value');//validation msg
    }
 });
</script>


text:
Q: tk messagebox import confusion I'm just beginning to learn tkinter at the moment, and when importing messagebox I found that I must not really understand import statements.
The thing that confuses me is that:
import tkinter as tk

def text_box():
    if tk.messagebox.askokcancel("Quit", "Never Mind"):
        root.destroy()

root = tk.Tk()
button = tk.Button(root, text="Press the button", command=text_box)
button.pack()
root.mainloop()

compiles fine, but pressing the button gives the error 'module' object has no attribute 'messagebox', while the code:
import tkinter as tk
from tkinter import messagebox

...
    if messagebox.askokcancel("Quit", "Never Mind"):
...

...works without a hitch.
I get a similar error if I import with from tkinter import *.
The help for tkinter shows messagebox in the list of PACKAGE CONTENTS, but I just can't load it in the normal way.
So my question is, why...and what is it about importing that I don't understand?
Just thought I should mention—the code only works in Python 3, and in Python 2.x messagebox is called tkMessageBox and is not defined in tkinter.

A: tkinter.messagebox is a module, not a class.
As it isn't imported in tkinter.__init__.py, you explicitly have to import it before you can use it.
import tkinter
tkinter.messagebox  # would raise an ImportError
from tkinter import messagebox
tkinter.messagebox  # now it's available eiter as `messagebox` or `tkinter.messagebox`

A: try this
import sys

from tkinter import *

... and your code


text:
Q: How to apply read/write permissions to user-uploaded files in Django I have a "document" model, an upload system using dropzone.js and the register/login. Im now lost on how to apply permissions to each individual uploaded File so only the specified users can access them.
Basically:
File1->accessible_by = user1,user2
File2->accesible_by=user3,user5...
And so on.
Thanks to anyone for advice/help on my problem.
Edit with relevant code:
Create Document View:
class DocumentCreate(CreateView):
    model = Document
    fields = ['file', 'is_public']

    def form_valid(self, form):
        self.object = form.save()
        data = {'status': 'success'}
        response = JSONResponse(data, mimetype =
        response_mimetype(self.request))
        return response

I did the above to the view to handle dropzone.js file uploading.
This is my "document" model
class Document(models.Model):

    file = models.FileField(upload_to = 'files/')
                                #validators=[validate_file_type])
    uploaded_at = models.DateTimeField(auto_now_add = True)
    extension = models.CharField(max_length = 30, blank = True)
    thumbnail = models.ImageField(blank = True, null = True)
    is_public = models.BooleanField(default = False)

    uploaded_by = models.ForeignKey(User,
                                related_name='uploadedByAsUser', null=True)

    allowed_users = models.ManyToManyField(User,
                                related_name='allowedUsersAsUser')

    def clean(self):
        self.file.seek(0)
        self.extension = self.file.name.split('/')[-1].split('.')[-1]
        if self.extension == 'xlsx' or self.extension == 'xls':
            self.thumbnail = 'xlsx.png'
        elif self.extension == 'pptx' or self.extension == 'ppt':
            self.thumbnail = 'pptx.png'
        elif self.extension == 'docx' or self.extension == 'doc':
            self.thumbnail = 'docx.png'

    def delete(self, *args, **kwargs):
        #delete file from /media/files
        self.file.delete(save = False)
        #call parent delete method.
        super().delete(*args, **kwargs)

    #Redirect to file list page.
    def get_absolute_url(self):
        return reverse('dashby-files:files')

    def __str__(self):
        return self.file.name.split('/')[-1]

    class Meta():
        ordering = ['-uploaded_at']

A: You can add an allowed_user field into the document model, so that only those users specified can access the files. for example:
class Document(models.Model):
    file = FileField()
    uploaded_by = models.ForeignKey(User, related_name='uploadedByAsUser')
    allowed_users = models.ManyToManyField(User, related_name='allowedUsersAsUser')

This way, if you want a user to be added to the "allowed" list, you can just add them using something like this:
class DocumentCreate(CreateView):
    model = Document
    fields = ['file', 'is_public']

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.allowed_users.add(request.user)
        self.object.save()
        data = {'status': 'success'}
        response = JSONResponse(data, mimetype =
        response_mimetype(self.request))
        return response

Then to make the Admin look nice (admin.py):
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('uploaded_by', 'file')

    fields = ('id', 'file', 'uploaded_at', 'extension', 'thumbnail', 'is_public', 'uploaded_by', 'allowed_users')
    filter_horizontal = ('allowed_users',)

    readonly_fields = ('id',)

admin.site.register(Document, DocumentAdmin)

Then if you want to check if they're allowed, you can do:
if allowed_user in doc.allowed_users:
    print('We have liftoff')

A: You can set content_type on a HttpResponse. So you can do permission handling in your view and serve the file directly from Django:
return HttpResponse("Text only, please.", content_type="text/plain")

Note: Django isn't a web server. It is recommended to use a web server for serving static files!
The above method might be a good approach if you handle small amounts of data and only incidentally serve data. If you need a robust solution, you need to check permissions in Django and leave the serving of data to the web server.

*

*Lighthttpd X-Sendfile

*Apache mod_wsgi Internal redirects

*NGNIX X-Accel-Redirect

Have a look at Django file streaming packages: https://djangopackages.org/grids/g/file-streaming/


text:
Q: Factories {create(:user)} create every time new user in new it block My code for test case
RSpec.describe "Normal days ", type: :request do
  context 'User ' do
    before(:all) do
      DatabaseCleaner.strategy = DatabaseCleaner::NullStrategy
    end
    let(:user1) { create :user }
    let(:user2) { create :user }
    let(:user3) { create :user }

    it 'Check-In ' do
      check_in(user1)
    end

    it 'Check-Out ' do
      check_out
    end

    it 'get histories ' do
      get_histories
    end
  end
end

Note:
Gem list
gem 'rspec'
gem 'rspec-rails'
gem 'factory_bot_rails', '5.2.0'
gem 'faker', '~> 2.22'
gem 'database_cleaner', '~> 1.5.3'

**Rails verision: **
gem 'rails', '~> 5.2.1'

ruby verision:
ruby '2.6.5'

Actual result
when i run the test case then every case (means when call it class)  users (user1,user2,user3)  changed.

*

*When run check-in case

user1 = user.email => test1@gmail.com and user.id => 1
user2 = user.email => test2@gmail.com and user.id => 2
user3 = user.email => test3@gmail.com and user.id => 3

*When call check-in case call then

user1 = user.email => test4@gmail.com and user.id => 4
user2 = user.email => test5@gmail.com and user.id => 5
user3 = user.email => test6@gmail.com and user.id => 6

Excepted result
after run the all case user value same

*

*When run check-in case

user1 = user.email => test1@gmail.com and user.id => 1
user2 = user.email => test2@gmail.com and user.id => 2
user3 = user.email => test3@gmail.com and user.id => 3

*When call check-in case call then

user1 = user.email => test1@gmail.com and user.id => 1
user2 = user.email => test2@gmail.com and user.id => 2
user3 = user.email => test3@gmail.com and user.id => 3


text:
Q: A bounded subset $S$ of $\mathbb{R}^2$ and its interior $S^\circ$ have the same inner area Folland's Advanced Calculus Chapter 4 Section 2 Exercise 3:

Let $S$ be a bounded set in $\mathbb{R}^2$. Choose a rectangle $Q=[a,b]\times[c,d]$ which includes $S$. Let $P=\{x_0,x_1,\dots,x_{n_1};y_0,y_1,\dots,y_{n_2}\}$ be a partition of $Q$. For $i=1,\dots,n_1$, $j=1,\dots,n_2$, put
$$Q_{ij}=[x_{i-1},x_i]\times[y_{j-1},y_j]\text{,}$$
$$m_{ij}=\inf_{t\in Q_{ij}}\chi_{S}(t)\text{,}$$
$$L(P,\chi_S)=\sum_{i,j}m_{ij}(x_i-x_{i-1})(y_j-y_{j-1})\text{,}$$
where $\chi_S$ is the indicator of $S$. The inner area $\underline{A}(S)$ of $S$ is defined to as
$$\underline{A}(S)=\underline{\int\int_S}dA=\sup L(P,\chi_S)\text{,}$$
the supremum being taken over all partitions $P$.
Show that $\underline{A}(S)=\underline{A}(S^\circ)$.

Fix $\epsilon>0$. Suppose we can find a partition $P_0$ of $Q$ such that
$$|L(P_0,\chi_S)-L(P_0,\chi_{S^\circ})|<\epsilon\text{.}$$
Choose partitions $P_1$, $P_2$ so that
$$|\underline{A}(S)-L(P_1,\chi_S)|<\epsilon\text{,}$$
$$|\underline{A}(S^\circ)-L(P_2,\chi_{S^\circ})|<\epsilon\text{.}$$
Take $P^*=P_0\cup P_1\cup P_2$. We then have
$$|\underline{A}(S)-\underline{A}(S^\circ)|<3\epsilon\text{.}$$
It follows that  $\underline{A}(S)=\underline{A}(S^\circ)$.
How to find such a $P_0$? It is clear that any rectangle which lies in $S^\circ$ lies in $S$, and that any rectangle which lies in $S$ and consists of interior points of $S$ lies in $S^\circ$. Hence the difference between $L(P,\chi_S)$ and $L(P,\chi_{S^\circ})$ is the sum of areas of those rectangles which lie in $S$ and contain boundary point of $S$. How to make sure the sum is small enough?

A: Clearly $A(S)\ge A(S^o).$ We show $A(S^o)>A(S)-r$ for any $r>0$. Let $P=\{x_0,x_1,\dots,x_{n_1};y_0,y_1,\dots,y_{n_2}\}$ be a partition of $Q$ such that $L(P,\chi_S)>A(S)-r/2.$
Let $T=\{(i,j):Q_{i,j}\subset S\}.$ There exists  $\{a_i,b_i,c_j,d_j: (i,j)\in T$} such that whenever $(i,j)\in T$ we have  $x_{i-1}<a_i<b_i<x_i$ and $y_{j-1}<c_j<d_j<y_j$  and  also $(b_i-a_i)(d_j-c_j)>(x_i-x_{i-1})(y_i-y_{j-1})-r/(2n_1n_2).$
Let $|T|$ be the number of members of $T$.
Now we can expand $\{a_i,b_i;c_j,d_j:(i,j)\in T\}$ to a partition $P'$ of $Q.$ Since $(i,j)\in T\implies Q_{ij}\subset S\implies [a_i,b_i]\times [c_j,d_j]\subset S^o,$ and since $L(P,\chi_S)=\sum_{(i,j)\in T}(x_i-x_{i-1})(y_i-y_{i-1})$, we have therefore $$A(S^o)\ge L(P',\chi_{S^o})>L(P,\chi_S)-|T|\cdot (r/2n_1n_2)\ge L(P,\chi_S)-r/2>A(S)-r.$$


text:
Q: How To Reset Manual Mocks In Jest I have a manual mock of crypto that looks like this:
// __mocks__/crypto.js

const crypto = jest.genMockFromModule('crypto')
const toString: Function = jest.fn(() => {
  return {}.toString()
})
const mockStringable = {toString}
const update: Function = jest.fn(() => mockStringable)
const deciper = {update}
crypto.createDecipheriv = jest.fn(() => deciper)

export default crypto

Which is basically tested like this:
const crypto = require('crypto')
jest.mock('crypto')

describe('cookie-parser', () => {
  afterEach(() => {
    jest.resetAllMocks()
  })
  describe('decryptCookieValue', () => {
    it('should call the crypto library correctly', () => {
      const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
      expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
      expect(crypto.createDecipheriv).toHaveBeenCalled()
      // more tests, etc, etc, etc
      expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
      expect(result).toEqual({}.toString())
    })
  })

  ...

This works however if in that same test file, I test another method that invokes decryptCookieValue from within crypto.createDecipheriv no longer returns my mock decipher. Instead it returns undefined. For instance:
describe('cookie-parser', () => {
  afterEach(() => {
    jest.resetAllMocks()
  })
  describe('decryptCookieValue', () => {
    it('should call the crypto library correctly', () => {
      const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
      expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
      expect(crypto.createDecipheriv).toHaveBeenCalled()
      expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
      expect(result).toEqual({}.toString())
    })
  })
  ...
  ...
  describe('parseAuthenticationCookie', () => {
    it('should create the correct object', () => {

      // parseAuthenticationCookie calls decryptCookieValue internally

      const result = parseAuthenticationCookie('', '') // Fails because internal call to crypto.createDecipheriv stops returning mock decipher.
      expect(result).toEqual({accessToken: null})
    })
  })
})

I think this is an issue with resetting the manual mock because if I take that later test and move it into a file all by itself with the same surrounding test harness it works just fine.
// new test file
import crypto from 'crypto'
import { parseAuthenticationCookie } from './index'

jest.mock('crypto')

describe('cookie-parser', () => {
  afterEach(() => {
    jest.resetAllMocks()
  })
  describe('parseAuthenticationCookie', () => {
    it('should create the correct object', () => {

      // Works just fine now

      const result = parseAuthenticationCookie('', '')
      expect(result).toEqual({accessToken: null})
    })
  })
})

Is my assessment here correct and, if so, how do I reset the state of the manual mock after each test?

A: From Jest docs:
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
ref: https://jestjs.io/docs/en/mock-function-api#mockfnmockreset
In your example you are assuming that calling resetAllMocks will set your manual mock back and it's not.
The reason why your test works in a separate file is because jest runs each file isolated, which is nice since you can screw up only the specs living in the same file.
In your particular case something that might work is calling jest.clearAllMocks() (since this will keep the implementation and returned values).
clearMocks options is also available at the jest config object (false as default), if you want to clear all your mocks on every test, this might be handy.
Hope this help you or anyone else having having a similar issue.
Bonus tip (no quite related) If you are mocking a module that it's being used internally by other module and in some specific test you want to mock that module again with a different mock, make sure to require the module that it's using the mocked module internally again in that specific test, otherwise that module will still reference the mock you specified next to the imports statements.

A: Looks like the better way to test this is something on the lines of:
jest.mock('crypto')

describe('decrypt()', () => {
  afterEach(() => {
    jest.resetAllMocks()
  })
  it('returns value', () => {
    const crypto = require('crypto')
    const encryptedValue = 'encrypted-value'
    const update = jest.fn()
    const pbkdf2SyncResult = 'test result'
    crypto.pbkdf2Sync = jest.fn().mockImplementation(() => {
      return pbkdf2SyncResult
    })
    crypto.createDecipheriv = jest.fn().mockImplementation((format, key, iv) => {
      expect(format).toEqual('aes-256-cbc')
      expect(key).toEqual(pbkdf2SyncResult)
      expect(iv).toEqual(pbkdf2SyncResult)
      return {update}
    })
    decrypt(encryptedValue)
    const inputBuffer = Buffer.from(encryptedValue, 'base64')
    expect(update).toHaveBeenCalledWith(inputBuffer)
  })
})

This way I don't even have to have the manual mock and I can use mockImplementationOnce if I need to have the mock reset.


text:
Q: batch admin console - DispatcherServlet using InternalResourceViewResolver instead of FreeMarkerViewResolver I have an issue with integrating the spring batch admin console into my application.
The good news is that when i go to http://mymachine.com:8080/ReportingManager/batch/configuration I can get to the admin console.
But when I go to http://mymachine.com:8080/ReportingManager/batch/job-configuration i get a 404 and an error saying that /batch/jobs can't be found.
I've just gone through the exercise of comparing the difference in output of org.springframework.web logs between my application logs and the spring-batch-admin-sample application which I know is working.
After looking at the logs it looks like the URL mappings can be found for the spring batch admin console but the DispatcherServlet is trying to use InternalResourceViewResolver instead of the FreeMarkerViewResolver
My application logs below show the wrong ViewResolver is being used for /ReportingManager/batch/jobs...
    2014-05-27 20:16:22,770 DEBUG [DispatcherServlet] - DispatcherServlet with name 'Batch Servlet' processing GET request for [/ReportingManager/batch/jobs]
    2014-05-27 20:16:22,770 DEBUG [RequestMappingHandlerMapping] - Looking up handler method for path /jobs
    2014-05-27 20:16:22,770 DEBUG [RequestMappingHandlerMapping] - Returning handler method [public void org.springframework.batch.admin.web.JobController.jobs(org.springframework.ui.ModelMap,int,int)]
    2014-05-27 20:16:22,770 DEBUG [DispatcherServlet] - Last-Modified value for [/ReportingManager/batch/jobs] is: -1
    2014-05-27 20:16:23,598 DEBUG [DispatcherServlet] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'jobs'; URL [/WEB-INF/pages/jobs.jsp]] in DispatcherServlet with name 'Batch Servlet'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Added model object 'endJob' of type [java.lang.Integer] to request in view with name 'jobs'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Added model object 'jobs' of type [java.util.ArrayList] to request in view with name 'jobs'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Added model object 'startJob' of type [java.lang.Integer] to request in view with name 'jobs'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Added model object 'totalJobs' of type [java.lang.Integer] to request in view with name 'jobs'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Added model object 'jobName' of type [java.lang.String] to request in view with name 'jobs'
    2014-05-27 20:16:23,598 DEBUG [JstlView] - Forwarding to resource [/WEB-INF/pages/jobs.jsp] in InternalResourceView 'jobs'
    2014-05-27 20:16:23,598 DEBUG [DispatcherServlet] - Successfully completed request

Whereas when I look at the longs for the spring-batch-admin-sample I can see that /spring_admin_console/jobs is using AjaxFreeMarkerView...
[5/27/14 19:57:13:962 EST] 00000023 SystemOut     O 19:57:13,950 DEBUG WebContainer : 0 servlet.DispatcherServlet:693 - DispatcherServlet with name 'Batch Servlet' processing GET request for [/s
pring_admin_console/jobs]
[5/27/14 19:57:13:978 EST] 00000023 SystemOut     O 19:57:13,965 DEBUG WebContainer : 0 annotation.DefaultAnnotationHandlerMapping:221 - Mapping [/jobs] to HandlerExecutionChain with handler [or
g.springframework.batch.admin.web.JobController@52e052e0] and 3 interceptors
[5/27/14 19:57:14:000 EST] 00000023 SystemOut     O 19:57:13,988 DEBUG WebContainer : 0 servlet.DispatcherServlet:769 - Last-Modified value for [/spring_admin_console/jobs] is: -1
[5/27/14 19:57:14:045 EST] 00000023 SystemOut     O 19:57:14,031 DEBUG WebContainer : 0 support.HandlerMethodInvoker:155 - Invoking model attribute method: public java.lang.String org.spring
framework.batch.admin.web.JobController.getJobName(javax.servlet.http.HttpServletRequest)
[5/27/14 19:57:14:091 EST] 00000023 SystemOut     O 19:57:14,078 DEBUG WebContainer : 0 support.HandlerMethodInvoker:173 - Invoking request handler method: public void org.springframework.batch.admin.web.JobController.jobs(org.springframework.ui.ModelMap,int,int)
[5/27/14 19:57:14:125 EST] 00000023 SystemOut     O 19:57:14,113 DEBUG WebContainer : 0 servlet.DispatcherServlet:1045 - Rendering view org.springframework.batch.admin.web.freemarker.AjaxFreeMarkerView: name 'jobs'; URL [/layouts/html/standard.ftl]] in DispatcherServlet with name 'Batch Servlet'
[5/27/14 19:57:14:144 EST] 00000023 SystemOut     O 19:57:14,130 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'springMacroRequestContext' of type [org.springframework.web.servlet.support.RequestContext] to request in view with name 'jobs'
[5/27/14 19:57:14:158 EST] 00000023 SystemOut     O 19:57:14,144 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'startJob' of type [java.lang.Integer] to request i
n view with name 'jobs'
[5/27/14 19:57:14:172 EST] 00000023 SystemOut     O 19:57:14,159 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'totalJobs' of type [java.lang.Integer] to request
in view with name 'jobs'
[5/27/14 19:57:14:186 EST] 00000023 SystemOut     O 19:57:14,172 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'servletPath' of type [java.lang.String] to request
 in view with name 'jobs'
[5/27/14 19:57:14:200 EST] 00000023 SystemOut     O 19:57:14,186 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'jobName' of type [java.lang.String] to request in
view with name 'jobs'
[5/27/14 19:57:14:214 EST] 00000023 SystemOut     O 19:57:14,200 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'jobs' of type [java.util.ArrayList] to request in
view with name 'jobs'
[5/27/14 19:57:14:228 EST] 00000023 SystemOut     O 19:57:14,214 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'titleText' of type [java.lang.String] to request i
n view with name 'jobs'
[5/27/14 19:57:14:242 EST] 00000023 SystemOut     O 19:57:14,228 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'titleCode' of type [java.lang.String] to request i
n view with name 'jobs'
[5/27/14 19:57:14:255 EST] 00000023 SystemOut     O 19:57:14,242 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'endJob' of type [java.lang.Integer] to request in
view with name 'jobs'
[5/27/14 19:57:14:269 EST] 00000023 SystemOut     O 19:57:14,256 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:328 - Added model object 'body' of type [java.lang.String] to request in vie
w with name 'jobs'
[5/27/14 19:57:14:287 EST] 00000023 SystemOut     O 19:57:14,274 DEBUG WebContainer : 0 freemarker.AjaxFreeMarkerView:279 - Rendering FreeMarker template [/layouts/html/standard.ftl] in FreeMark
erView 'jobs'
[5/27/14 19:57:14:909 EST] 00000023 SystemOut     O 19:57:14,895 DEBUG WebContainer : 0 servlet.DispatcherServlet:674 - Successfully completed request

I've spent a while trying to find out what is happening and am not sure. I suspect maybe I am doing something wrong in my web.xml. Maybe relating to the order of the servlets.
I am going to post an excerpt from my web.xml in the hopes that someone will see something I am doing wrong.
Thanks in advance for having a look at this for me.
I've put my web.xml here.
http://pastebin.com/eBkHMe8g

A: In your web project make sure you have this folder structure: WEB-INF\classes\META-INF\spring\batch\override. And under this folder create a new .xml file. Name it whatever name you want. The content of the file should be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="resourceService" class="org.springframework.batch.admin.web.resources.DefaultResourceService">
        <property name="servletPath" value="/batch" />
    </bean>
</beans>

The value for the servletPath needs to match your servlet-mapping in your web.xml. I used /batch because this is what you have in yours.
More about this here. Also, it does help to have a look at the Spring Batch Admin source code. In that resources-context.xml you can see that a certain SPeL expression is used for various servletPath resources: <prop key="servletPath">#{resourceService.servletPath}</prop>. You need to search for the bean called resourceService, have a look at its source code and from there you can establish what property to change for DefaultResourceService in your custom .xml file.
LATER EDIT: As a general suggestion, your mvc-dispatcher DispatcherServlet is picking up automatically and by default the file located at /WEB-INF/mvc-dispatcher-servlet.xml. You'll have the beans under mvc-dispatcher-servlet.xml being picked up and loaded twice in two different app contexts because you have this file specified as one of the contextConfigLocation values. There is a hierarchy of contexts there, root one (defined by contextConfigLocation) being the parent. The idea is to place beans that are non-web (or that are to be used by web) in the root context and the web to be able to "use" these beans. Other way around doesn't quite make sense, because a DAO or Service class doesn't need access to web.


text:
Q: Apollo - Uncaught (in promise) Error: Network error: Cannot read property 'kind' of undefined I am writing a simple login form using GraphQL and Apollo. Each time after a user logged in, it will refetch the query to grab the user data.
import React, {Component} from 'react'
import AuthForm from './AuthForm'
import loginMutation from '../mutations/Login'
import { graphql } from 'react-apollo'
import userQuery from '../queries/CurrentUser'

//App.js

...
const networkInterface = createNetworkInterface({
  uri: '/graphql',
  opts: {
    credentials: 'same-origin',
  }
})

const client = new ApolloClient({
  dataIdFromObject: o => o.id,
  networkInterface
})
...

//Login.js
class LoginForm extends Component {

onSubmit({ email, password }) {
    this.props.mutate({
        variables: { email, password },
        refetchQueries: [{ userQuery, varibles: null }]
    })
}

render() {
    return (

Login

            <AuthForm onSubmit={ this.onSubmit.bind(this) }/>

    )
}
}

export default graphql(loginMutation)(LoginForm)
//userQuery.js
import gql from 'graphql-tag'

export default gql`
    {
        user{
            id
            email
        }
    }
`

The problem is the user can log in but the user query is not getting refetched. Instead I kept getting this error message:
Uncaught (in promise) Error: Network error: Cannot read property 'kind' of undefined  at new ApolloError (bundle.js:6231).
I could not find the cause of this issue. So, can anyone help me with this prob,

A: refetchQueries: [{ userQuery, varibles: null }]

Inside the array in the refetchQueries property you have an object userQuery which you're deconstructing which when deconstructed would be { userQuery: userQuery }. This property isn't recognised by Apollo Client, it should be { query: userQuery }. You also have a misspelling in varibles: null. It should be variables: null.
Corrected code:
onSubmit({ email, password }) {
    this.props.mutate({
        variables: { email, password },
        refetchQueries: [{ query: userQuery, variables: null }]
    })
}


text:
Q: Controlling the current through multiple LEDs linearily and efficiently I have around 100 infrared LEDs, each with an adjacent phototransistor to detect small differences in the distance of several objects (QRE1113).
As the objects materials differ, I want to be able to calibrate the intensity of every emitter separately to compensate for this.
As each phototransistor's output is measured with a very high sample rate (~50ksps), I cannot use a PWM controller, as those typically operate around 20kHz, and so need to directly control the current flow through each IR emitter.
As I would like to do this calibration phase over I2C, my idea was to use a digital potentiometer such as the MCP4451 as a rheostat. It has 4 channels and so I thought of using it as the current limiting resistor for 4 LEDs. While this is appealing on the one hand (low price, easy setup), I see two main problems:

*

*All affordable digitial potentiometers have a range of at least 5kΩ. I need a range of around 400Ω. By using a parallel resistor I could adjust the range, but the resulting range would is not be linear anymore. While perfect linearity is not required, I want to be able to do reasonable adjustments in all regions, and not just on the low amperage end.

*Efficiency. I am driving all these from a 5V source, and without calibration hardware I was able to put 3 LEDs in series with a resistor. Therefore, the average power consumption per LED was around 30mW, which is great.
With this approach, each LED would stand on its own with its resistor, resulting in additional 100mW heat for LED operation at 30mW.
In the following graph you can see the resulting relation from wiper setting of the MCP4415 to the resulting total resistance and LED forward current. The calculations are for using a parallel 680Ω resistor and a 68Ω in series (to set the maximum):

Related circuit:

simulate this circuit – Schematic created using CircuitLab
My main problem is definitely the non-linear wiper to resistance relation, the efficiency is only a secondary consideration. I'm open to any solutions, but I cannot afford a dedicated LED controller for each LED, as my budget is limited, which is why the MCP4415 appeared as an appealing solution to me (~25€ to control all LEDs).
EDIT:
I want to clarify some aspects:

*

*I would like to be able to control the current for each LED separately, and linearly, from 10mA to 30mA in at least 64 steps. I don't need absolute precision for any of these values, just a approximately uniform way to step through this range to adjust the brightness for the LED linearily.

*Efficiency is not my main goal. Functionality and cost are the most important factors.

*I was hoping to be able to use something similar to the MCP4415, as it is cheap and it does not need to be actively interfaced the whole time (it retains its value at least until shutdown).

*My calibration phase occurrs once at startup, where i will iteratively approximate the correct current by using the feedback from the phototransistor.

*The 5V network will mainly power these LEDs, and a few logic ICs. If required, I can switch to another voltage.

EDIT 2: Additional responses to questions from the comments.
Firstly, please let me clarify that this is not a commercial project, but just a personal project. Also, I am a computer scientist and not an electronics engineer, so please bear that in mind. (Therefore, there is no spec I need to follow) - I'm open to any suggestions.

Show application.
  And what distance and range of reflectivity?

Objects are made of wood, and cannot be painted or modified. Therefore the reflectance varies over different objects (dark spots, etc.).
Closest possible is around 3mm (+- 1mm), furthest is around 13mm (+-2mm). So the travel distance will be around 9-10mm for each object.
Everything is wood, therefore all measurements have these high tolerances.
The PCB is already at the furthest point from the objects. I probably can't change these distances (maybe -+ 1mm).
I have 12-bit ADCs measuring the phototransistors, and I just want to waste as little precision as possible. Therefore, I want to adjust the IR LED so that the near point (3mm) has roughly the same ADC value for all objects. Roughly equal is all I need - I just don't want one ADC to measure 3000 at the near point and another measure 3500. The far points are not important.

Fundamentally you have made some poor interpretations of datasheet, assumptions and thus poor choices. hFE=CTR (effective) = IcON/If varies from 0.2% to 0.9% at 10mA @ 1mm using a polished alum mirror.. What is your spec for error tolerance ?
  And what variation in Chip height? 0.1mm max? 0.05 mm?

I see, this is also the reason why I want to be able to do calibration. All tolerance information I could gather is listed above.
Regarding chip height: I have to hand-solder all chips, so assume a pessimistic 1 mm.

You say 3 IRs in series but then 1 R per IR LED ??? Showing none in series ?

Sorry if I have been unclear. I meant one resistor per 3 LEDs in series, this is the current design (below). What I meant was that I can't put them in series if I want to control them separately.
In total I have 90 sensors, so this pattern repeats 30 times.

A: How about an OPAMP current source fed by a modulated variable voltage from PWM?

simulate this circuit – Schematic created using CircuitLab
The idea is to make the OA1 regulate the current in a way that makes the voltage on Rsense equal to Vin, thus making current though the LED proportional to Vin. OA2 acts as a buffer amplifier for that variable voltage which can be generated by PWM and filtered to quasi-DC.
OA2 provides a way to modulate Vin with your digital signal Vmod. The modulation is inverted: When Vmod is high, Vin drops to zero, while Vmod=0 results in Vin being set proportionally to the PWM duty cycle.


text:
Q: Does Firebase still support Mac OS X - July 2016 I have an iOS App that uses the Firebase Realtime Database that I would like to create for Mac OS X. Does Firebase still support Mac OS X in the latest update as the Firebase console only shows the option to Add Firebase to an iOS, Android or web app.
If so, where can I find it?
Thank you

A: Thanks to the open source community, it's possible again to build a Firebase Realtime Database client on macOS. Details in the GitHub repo README.

A: As Paul said, you have to follow the instructions to get the pods right from the GitHub repository.
I added these lines to my Podfile
pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'
pod 'FirebaseStorage', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'

Then on the AppDelegate
import FirebaseCore
func applicationDidFinishLaunching(_ aNotification: Notification) {
        FirebaseApp.configure()
}

Hope this helps!


text:
Q: Easy counting problem I have been trying to learn combinatorics from a book. While doing so, I encountered a problem. Here it is:

A DNA chain is composed of blocks from four chemicals - $\mathrm{A}$, $\mathrm{T}$, $\mathrm{G}$ and $\mathrm{C}$. How many such chains of length three are present if repetitions are allowed?

So what I did was I assumed that I had $3~\mathrm{A}$'s, $3~\mathrm{G}$'s, $3~\mathrm{T}$'s and $3\mathrm{C}$'s. Now the problem is reduced to finding the number of ways to choose $3$ elements from $12$ which is equal to $[12~\mathrm{choose}~3]$. The answer for that is $220$.
However, the book says that there are $4$ ways to fill each of the three blocks so the answer is $4^3 = 64$.
I want to why my method is wrong in this problem.

A: You picked 3 A's, 3G's, etc. because you are thinking: OK, the first element can be an A, the second can be an A, and the third can be an A ... And the same goes for the other letters.  So that means that you are basically starting out with the following 12 objects: an A in the first place, an A in the second, an A in the third place ... And again the same for the other 3 letters. We can look at this as having 12 different objects $A_1, A_2$, etc.
But now, when you randomly choose 3 objects out of these 12, some possible outcomes would be something like $A_3, G_1, G_3$. But note, that is really not an allowed sequence, because you would have both an A and a G in the third position (and nothing in the second position). So, your method gets too many possibilities compared to what are the real possibilities.

A: In your counting argument, for example, $AGA$ is counted $3\times 3\times 2$ times: there are $3$ ways to pick $G$, $3$ ways to pick the first $A$, $2$ ways to pick the last $A$.
You've picked $3$ elements from $12$ elements: $A_1,A_2,A_3,G_1,G_2,G_3,T_1,T_2,T_3$ and $C_1,C_2,C_3$. That means you've included $A_1G_1A_2$ and $A_2G_1A_3$ in your counting but these are essentially the same and both are $AGA$.
EDIT: Wrong argument as pointed out below. $A_1G_1A_2,A_2G_1A_3$ could be $AGA,AAG,GAA$.

A: Your first assumption is wrong, if I got the question correctly, the question says you can use 4 chemicals and creat a chain of length 3. So , if repeatetion allowed 3 places can be filled 4*4*4 = 64.


text:
Q: Different optimizations in Math.Sum in Win32/64 I have the following code
const
  NumIterations = 10000000;
var
  i, j : Integer;
  x : array[1..100] of Double;
  Start : Cardinal;
  S : Double;
begin
  for i := Low(x) to High(x) do x[i] := i;

  Start := GetTickCount;
  for i := 1 to NumIterations do S := System.Math.Sum(x);
  ShowMessage('Math.Sum: ' + IntToStr(GetTickCount - Start));

  Start := GetTickCount;
  for i := 1 to NumIterations do begin
    S := 0;
    for j := Low(x) to High(x) do S := S + x[j];
  end;
  ShowMessage('Simple Sum: ' + IntToStr(GetTickCount - Start));
end;

When compiled for Win32 Math.Sum is considerably faster than the simple loop, as Math.Sum is written in Assembler and uses four-fold loop unrolling.
But when compiled for Win64, Math.Sum is considerably slower than the simple loop, because in 64-bit Math.Sum uses Kahan summation. This is an optimization for accuracy minimizing pile-up of errors during the summation process, but is considerably slower than even the simple loop.
I.e. when compiling for Win32 I get code optimized for speed, when compiling the same code for Win64 I get code optimized for accuracy. This is not exactly what I naively would expect.
Is there any sensible reason for this difference between Win32/64? Double is always 8 byte, so the accuracy should be identical in Win32/64.
Is Math.Sum still implemented identically (Assembler and loop unrolling in Win32, Kahan summation in Win64) in current versions of Delphi? I use Delphi-XE5.

A:
Is Math.Sum still implemented identically (Assembler and loop unrolling in Win32, Kahan summation in Win64) in current versions of Delphi? I use Delphi-XE5.

Yes (Delphi 10.3.2).

Is there any sensible reason for this difference between Win32/64? Double is always 8 byte, so the accuracy should be identical in Win32/64.

32-bit Delphi for Win32 uses the old FPU, while the 64-bit compiler uses SSE instructions. When the 64-bit compiler was introduced in XE2, many of the old assembly routines was not ported to 64-bit. Instead, some routines were ported with similar functionality as other modern compilers.

You can enhance the 64-bit implementation a bit by introducing a Kahan summation function:
program TestKahanSum;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,Math,Diagnostics;

function KahanSum(const input : TArray<Double>): Double;
var
  sum,c,y,t : Double;
  i : Integer;
begin
    sum := 0.0;
    c := 0.0;
    for i := Low(input) to High(input) do begin
      y := input[i] - c;
      t := sum + y;
      c := (t - sum) - y;
      sum := t;
    end;
    Result := sum;
end;

var
  dArr : TArray<Double>;
  res : Double;
  i : Integer;
  sw : TStopWatch;
begin
  SetLength(dArr,100000000);
  for i := 0 to High(dArr) do dArr[i] := Pi;
  sw := TStopWatch.StartNew;
  res := Math.Sum(dArr);
  WriteLn('Math.Sum:',res,' [ms]:',sw.ElapsedMilliseconds);
  sw := TStopWatch.StartNew;
  res := KahanSum(dArr);
  WriteLn('KahanSum:',res,' [ms]:',sw.ElapsedMilliseconds);
  sw := TStopWatch.StartNew;
  res := 0;
  for i := 0 to High(dArr) do res := res + dArr[i];
  WriteLn('NaiveSum:',res,' [ms]:',sw.ElapsedMilliseconds);
  ReadLn;
end.

64-bit:
Math.Sum: 3.14159265358979E+0008 [ms]:492
KahanSum: 3.14159265358979E+0008 [ms]:359
NaiveSum: 3.14159265624272E+0008 [ms]:246

32-bit:
Math.Sum: 3.14159265358957E+0008 [ms]:67
KahanSum: 3.14159265358979E+0008 [ms]:958
NaiveSum: 3.14159265624272E+0008 [ms]:277

Pi with 15 digits is 3.14159265358979
The 32-bit math assembly routine is accurate to 13 digits in this example, while the 64-bit math routine is accurate to 15 digits.

Conclusion:

*

*The 64 bit implementation is slower (by a factor of two compared to a naive summation), but more accurate than the 32-bit math routine.

*Introducing an enhanced Kahan summation routine improves performance by 35%.

A: Having the very same RTL function not behave the same when switching a compilation target is an awful bug. It should not change the behavior. Even worse, Win64/pascal Sum() over single or double does not behave the same! sum(single) is naive summing, whereas sum(double) uses Kahan... :(
You would better either use plain + operator, or create your own Kahan sum function.
I can confirm that the bug is still there in Delphi 10.3.


text:
Q: Заполнение многомерного массива методом array_push Заполняю массив перед выдачей в формате JSON таким образом:
$json_data = array('from_login'=>$rows[$j]['from_login'],
                               'message_enc_from_key'=>$rows[$j]['message_enc_from_key'],
                               'who_login'=>$rows[$j]['who_login'],
                               'message_enc_who_key'=>$rows[$j]['message_enc_who_key'],
                               'date_time'=>$rows[$j]['date_time']
                               );
echo json_encode($json_data);

Возник вопрос как можно заполнить данный массив методом array_push. Пытался так:
array_push($json_data, 'from_login'=>$rows[$j]['from_login']);

Но выдаёт ошибку 500. Что я упустил и делаю не так?

A: Функция array_push() не предназначена для заполнения ассоциативных массивов, в результате ее работы получаются только индексные массивы. Если вы хотите добавить новый элемент в ассоциативный массив, лучше поступить так
$json_data['from_login'] = $rows[$j]['from_login'];


text:
Q: When I run this code, I get a blank page <?php

  include("config.inc.php");

header("Cache-Control: no-cache, must-revalidate");
echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
echo "<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\"\"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">";
echo "";

    echo "";
    echo "<title>$stitle</title>";
    echo "<link rel=\"StyleSheet\" type=\"text/css\" href=\"theme/theme.css\" />";
    echo "";

?>

<META HTTP-EQUIV="Refresh" Content="10">

<?php

    echo "";

echo "
";

echo "Live Score:
---
";
$feed = "http://www.scorespro.com/rss/live-soccer.xml";
$fp = @fopen($feed,"r");
while(!feof($fp)) $raw .= @fgets($fp, 4096);
fclose($fp);
if( preg_match("/<item>(.*)<\/item>/", $raw, $rawitems ) ) {
$items = explode("<item>", $rawitems[0]);

  $p = 5;
  if ($npage == "")$npage = "1";
  $countfile= count($items);
  $countfile=$countfile-2;
  $first=($npage*$p)-$p;
  $npages = ceil($countfile / $p);
  $items = array_reverse($items);
  $next_arrays=($first+($p-1));
  if($next_arrays>$countfile)$next_arrays=$countfile;
  for ($i=($first); $i <= $next_arrays; $i++) {
    preg_match("<title>(.*)</title>",$items[$i+1], $title );
    preg_match("<link>(.*)</link>",$items[$i+1], $url );
    preg_match("<description>(.*)</description>",$items[$i+1], $description);

  $title[1] =  str_replace("'", "", $title[1]);
  $title[1] =  str_replace("& ", "&", $title[1]);
  echo $title[1].' ';

  }
}
// if ($npage <= $npages and $npage>1) $gline_rew = '[url="'.$_SERVER["]Prev[/url] ';
// if ($npages > 1 and $npage<$npages) $gline_next = ' [url="'.$_SERVER["]Next[/url]';
// echo "
// ---
// Page {$npage} of {$npages}
// ".$gline_rew.$gline_next."
// ---
// ";

echo "\n";
echo "
";
echo "";
echo "";
?>
<?php
public_static_function getInstance() {
  static $instance;
  $class = $title;

  if ( ! $instance instanceof $class) {
     $instance = new $class;
  }

  return $instance;
}

Hello!
I am making a live-score site using PHP.
But when I use this code and run it, I get a blank page.
I hope that I will find the mistake by myself but for now I can`t.
I would be happy if someone knows where the mistake is and help me.
Thank you in advance !!!

A: This is wrong
public_static_function getInstance() {

It should be
public static function getInstance() {

Also add error_reporting(E_ALL) when you have blank page(Which means you have errors)

A: Even when fixed, this will not work:
public static function getInstance() {
    static $instance;
    $class = $title;
    ...
}

Furthermore we have simpleXML_load_str() for handling RSS (or other XML) strings.
I think what you want is a decent way to handle an RSS feed.
Have a look at this post about RSS feeds
Good luck!


text:
Q: faster way to run a loop in r I have three dataframes A,B and C.
A has 18000 rows and 18000 columns and B has 150000 rows and 5 cols.
I want to fill elements of A by B.
the loop take a long time. how can I run this loop faster?
example of A
Entrez_Gene_Id 2324 34345 4345 1234 3453
1 Entrez_Gene_Id    0     0    0    0    0
2          23040    0     0    0    0    0
3           7249    0     0    0    0    0
4          64478    0     0    0    0    0
5           4928    0     0    0    0    0
6          58191    0     0    0    0    0

example of B
  head(B)
  V1 Gene1 Gene2      weight   newWeight
1  1  4171  4172  2.01676494 0.020420929
2  2  2237  5111 1.933298567 0.015300857
3  4   506   509 2.439170425 0.020577243
4  7  6635  6636 2.255316779 0.081088975
5  8  6133  6210 3.427969232 0.021132906
6 10 23521  6217 1.607247743 0.027792961

and this is my code :
B<- data.frame(lapply(C, as.character), stringsAsFactors=FALSE)

for(i in 1:nrow(B)){
  Rname=B[i,2]
  Cname=B[i,3]
  A[Rname,Cname]=B[i,5]
  print(i)
}

A: It seems as though you are trying to fill a full matrix with a matrix in sparse notation. You can use the dgCMatrix class from the Matrix package to do this:
library(Matrix)
b_mat <- sparseMatrix(i=B[,2],j=B[,3],x=B[,5])

This leaves the Matrix in sparse format. To convert to 18,000 x 18,000 form:
as.data.frame(as.matrix(b_mat))

EDIT: I would suggest leaving the as.data.frame call out here, as the matrix would be easier to work with considering the number of columns you have


text:
Q: SQL Server 2014 connection string with instance name My working SQL Server 2014 connection string is:
Data Source=localhost;Initial Catalog=myDb;Integrated Security=True;

I need to install a new instance of SQL Server 2016 on the same server. Therefore I need to modify the existing connection string and to add the instance name.
I was trying (MSSQLSERVER is the instance name):
"Data Source=localhost\MSSQLSERVER;Initial Catalog=myDb;Integrated Security=True;" providerName="System.Data.SqlClient"

AND:
"Server=localhost/MSSQLSERVER;Database=myDb;User Id=user; Password=password;" providerName="System.Data.SqlClient"

AND more but could not make it work.
The error I am getting is:

The network name cannot be found

A: If you have SQL Server 2014 as your default instance (with no instance name needed to connect to it - that's the MSSQLSERVER "instance", but that name must not be used in the connection string!), then you must use a separate, different instance name for your SQL Server 2016 installation, e.g. SQL2016.
In that case, your connection string will need to use .\SQL2016 or (local)\SQL2016 or localhost\SQL2016 as the server/instance name (defined by the server= or data source= settings in the connection string).
So your connection string for SQL Server 2016 should be something like:
Data Source=localhost\SQL2016;Initial Catalog=myDb;Integrated Security=True;

You can go to the SQL Server Configuration Manager to see what services are defined and thus what instances are present on your machine:

Look for the SQL Server services - the value in parenthesis is the instance name (where MSSQLSERVER stands for the default instance that doesn't need to be specified as such - just the machine name is enough for connecting to the default instance)


text:
Q: Is it possible to increment the maximum row size in AWS Athena? I'm running this query with AWS Athena:
SELECT
  t1.*
FROM "db"."tbl1" t1
INNER JOIN "tbl1"."ema" ea ON
  ea.id = concat(t1.numc,t1.nummt)
WHERE
  ea.cod1 = '23' and
  ea.cod2 = '776'

And getting this error:
Size of a single row or its columns cannot exceed 32 MB

The table is saved in AWS S3 in jsonl format.
It's possible to increase the maximun row size?

A: Unfortunately not. Athena does not currently let you configure any Presto details.


text:
Q: How to avoid this OperationError in Django? I'm trying to implement a Many to One relationship in Django.
This is my code:
models.py
class Entry(models.Model):

    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    content = models.TextField()
    date = models.DateTimeField(db_index=True, auto_now_add=True)
    category = models.ManyToManyField(Category)

    class Meta:

        ordering = ['-date']
        verbose_name_plural = 'Entradas'

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('blog_entries', None, {'slug': self.slug})

class Comment(models.Model):
    date = models.DateTimeField(db_index=True, auto_now_add=True)
    content = models.TextField()
    entry = models.ForeignKey(Entry, related_name='comments')
    #add image field
    username = models.SlugField(max_length=100, unique=True)

admin.py
from django.contrib import admin
from blog.models import Entry, Comment

class AdminEntry(admin.ModelAdmin):
    list_display = ('title', 'date', 'content','slug')
    #prepopulated_fields = {"slug": ("titulo",)}
    list_filter = ('title', 'date')
    ordering = ('-date',)
    search_fields = ('title',)

admin.site.register(Entry, AdminEntry)

class AdminComment(admin.ModelAdmin):
    list_display= ('username','content')

admin.site.register(Comment, AdminComment)

Then I do:
python manage.py syncdb
python manage.py runserver
When I go to the Comment section of the admin, I get this:
OperationalError at /admin/blog/comment/
no such column: blog_comment.content
Request Method: GET
Request URL:    http://localhost:8000/admin/blog/comment/
Django Version: 1.6.1
Exception Type: OperationalError
Exception Value:
no such column: blog_comment.content
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py in execute, line 450
Python Executable:  /usr/bin/python
Python Version: 2.7.3
Python Path:
['/home/boel/Dropbox/boeldev',
 '/usr/local/lib/python2.7/dist-packages/pip-1.1-py2.7.egg',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/python2.7/dist-packages/gst-0.10',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
 '/usr/lib/python2.7/dist-packages/ubuntuone-couch',
 '/usr/lib/python2.7/dist-packages/ubuntuone-installer',
 '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
Server time:    Thu, 6 Feb 2014 22:39:05 +0000

What I'm doing wrong?
Thanks in advance!

A: syncdb doesn't add columns on existing tables. Either drop your table and run it again, or use South to create migrations.


text:
Q: React - Overlap css files I have a theme feature in my web-app with two bootstarp css files, one for each theme. I wanna toggle between them but when the end result that they are overlapping.
handleThemeToggleClick(dark){
    var new_theme = !this.state.dark_theme
    if(new_theme)
    {
      import("./css/bootstrap-darkly.min.css");
      this.setState({
        dark_theme: new_theme,
      });
    }
    else{
      import("./css/bootstrap-simplex.min.css");
      this.setState({
        dark_theme: new_theme,
      });
    }
  }

Is there a way to un-import a file in react? Please Help me

A: Un-importing the css file wouldn't make a difference. The css styles would've been applied already so they won't just go away unless the user refreshes the browser.
Instead you can re-write all your CSS properties so that your styles don't clash.


text:
Q: Swift4.2 grab screenshot from Video in Swift 4.2 I am trying to grab screenshot from video
func thumbnailImageFor(fileUrl:URL) -> UIImage? {

        let asset = AVAsset(url: fileUrl)
        let assetImgGenerate = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true

        let time = CMTimeMakeWithSeconds(1.0, preferredTimescale: 600)
        do {
            let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
            let thumbnail = UIImage(cgImage: img)
            return thumbnail
        } catch {
            print(error)
            return nil
        }
 }

But getting error:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
  not be completed" UserInfo={NSLocalizedFailureReason=An unknown error
  occurred (-12792), NSLocalizedDescription=The operation could not be
  completed, NSUnderlyingError=0x600000f46580 {Error
  Domain=NSOSStatusErrorDomain Code=-12792 "(null)"}}

video's url:
https://firebasestorage.googleapis.com/v0/b/lailaichatapp.appspot.com/o/message_movies%2F8A61AC4E-4A08-4EC7-BC78-A5D861BE48C5.mov?alt=media&token=8906971d-59d7-4880-988e-135615c10f22
am I missing something?

A: I think it may be an issue with the filetype of the movie, as this works:
import UIKit
import AVFoundation

func thumbnailImageFor(fileUrl:URL) -> UIImage? {

    let video = AVURLAsset(url: fileUrl, options: [:])
    let assetImgGenerate = AVAssetImageGenerator(asset: video)
    assetImgGenerate.appliesPreferredTrackTransform = true

    let videoDuration:CMTime = video.duration
    let durationInSeconds:Float64 = CMTimeGetSeconds(videoDuration)

    let numerator = Int64(1)
    let denominator = videoDuration.timescale
    let time = CMTimeMake(value: numerator, timescale: denominator)

    do {
        let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        let thumbnail = UIImage(cgImage: img)
        return thumbnail
    } catch {
        print(error)
        return nil
    }
}

let url: URL = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4")!

let image: UIImage? = thumbnailImageFor(fileUrl: url)
print("Image: \(image)")


text:
Q: How to make a linear graph? I'm trying to make something that looks more or less like this. Any ideas? My code beneath is everything i could arrive at. Can someone help me?
 I'm trying to have 10 boxes of the following letters inside:
 B C H A J F E D G I
And if possible put chosen numbers outside every letter from under
So, for instance, the B comes at the most left and i would like to put the number 3 outside under it (instead of the current 1) and the C comes after with the number 6 (instead of the 2) and so on...

   \begin{table}[h]
       \centering
     \begin{tabular}{|c|l|r|r|r|r|r|r|r|}\hline
      & \multicolumn{1}{c|}{B} & {\hfill Text\hfill} & \multicolumn{1}{c|}{C} &
     \multicolumn{1}{c|}{H} & \multicolumn{1}{c|}{A} & \multicolumn{1}{c|}{J}  &
    \multicolumn{1}{c|}{F}  & \multicolumn{1}{c|}{E}  & \multicolumn{1}{c|}{D}  &
      \multicolumn{1}{c|}{G}  & \multicolumn{1}{c|}{I}   & \\ \hline

   \end{tabular}
   \end{table}

A: A PSTricks solution. Compile with latex-dvips-ps2pdf or xelatex.
\documentclass[pstricks,border=12pt]{standalone}
\def\N{9}
\begin{document}
\begin{pspicture}[dimen=m](1,-.5)(\numexpr\N+1,1)
    \foreach \i/\j in {1/0,2/0,3/1,4/0,5/1,6/0,7/0,8/0,9/0}{%
    \rput(\i,0){%
        \ifnum\j=1\relax
            \psframe[fillstyle=solid,fillcolor=green](1,1)
        \else
            \psframe(1,1)
        \fi
        \rput(.5,.5){\j}\rput(.5,-.5){\i}}}
\end{pspicture}
\end{document}

A: If you would like to keep the tabular format, you could use a TikZ matrix:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\tikzset{
    mymatr/.style={
        matrix of nodes,
        column sep=-1.2pt,
        inner sep=0pt,
        text width=1.5em,
        text centered,
        text height=2.6ex,
        text depth=.8ex,
        row 1/.style={nodes={font=\itshape,draw=gray, very thick}}
    },
}

\begin{document}
    \begin{tikzpicture}
        \matrix[mymatr] {
            B & C & H & A & J & F & E & D & G & I\\
            2 & 6 & 4 & 3 & 1 & 2 & 4 & 0 & 0 & 10\\
        };
    \end{tikzpicture}
\end{document}

A: You could do something like this using a tabular environment but, personally, I would write a macro for this using tikz so that the commands:
  \LinearGraph{0,0,1,0,1,0,0,0,0}

  \LinearGraph{0,1,0,1,1,1,0,0}

would produce:

Here is the full code:
\documentclass{article}
\usepackage{tikz}

% Usage: \LinearGraph{ comma separated list of 0's and 1s}
\newcommand\LinearGraph[1]{%
\begin{tikzpicture}[box/.style={rectangle,draw=gray, thick, minimum width=5mm}]
     \foreach \num [count=\c] in {#1} {% loop over numbers
        \ifnum\num=1% check number and shade 1's
          \node[box,fill=green, label=below:\c] at (\c/2,0){$\num$};
        \else
          \node[box,label=below:\c] at (\c/2,0){$\num$};
        \fi
     }
  \end{tikzpicture}%
}

\begin{document}

  \LinearGraph{0,0,1,0,1,0,0,0,0}

  \LinearGraph{0,1,0,1,1,1,0,0}

\end{document}

Edit
Here is a modification of the code above so that it meets the new
question specifications. The command
\LinearGraph{B/2, C/6, H/4, A/3, J/1, F/3, E/2, D/4, G/0, I/10}

now produces:

Here is the new code:
\documentclass{article}
\usepackage{tikz}

\newcommand\LinearGraph[1]{%
\begin{tikzpicture}[box/.style={rectangle,draw=gray, thick, minimum width=5mm}]
     \foreach \num/\lab [count=\c] in {#1} {
       \node[box,label=below:\lab] at (\c/2,0){$\num$};
     }
  \end{tikzpicture}%
}

\begin{document}

  \LinearGraph{B/2, C/6, H/4, A/3, J/1, F/3, E/2, D/4, G/0, I/10}

\end{document}


text:
Q: Intent filter for email attachments I want to open audio attachments in emails with my app. Currently my intent filter is like so:
<intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <action android:name="android.intent.action.EDIT" />
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
         <data android:mimeType="audio/wav" />
        <data android:scheme="http" android:host="*" android:pathPattern=".*\\.wav"/>
        <data android:scheme="https" android:host="*" android:pathPattern=".*\\.wav"/>
        <data android:scheme="content" android:host="*" android:pathPattern=".*\\.wav"/>
        <data android:scheme="file" android:host="*" android:pathPattern=".*\\.wav"/>
</intent-filter>

This works for everything I want it to except for email attachments. Currently if I'm sent a wav file, the only thing I can do is preview it, and that opens with Winamp (so clearly 3rd party apps have a way in). I can't find what I should be adding to do this though, does anyone have any idea?
Edit
Here's what LogCat has to say on the matter. When I click Preview I get
01-10 19:28:52.691: INFO/ActivityManager(109): Starting: Intent { dat=content://gmail-ls/messages/xxxxxxx%40gmail.com/439/attachments/0.1/BEST/false cmp=com.google.android.gm/.ViewAttachmentActivity } from pid 19483

What's bizarre is that Winamp automatically opens, and is not set as default. I'm given no choice...

A: Replacing audio/wav with audio/* makes it work, however this is obviously undesirable behaviour.

A: email clients seem to choose mimetypes for attachments in an arbitrary way, so intent filters to open them must contemplate all possibilities. searching the internet helps to find all the possible types and one should add a <data/> filter for each of them, if a wildcard like audio/* is not desired (as OP says).
anyway, filtering by mimetype is suggested as a first choice other than filtering by filename extension (see this thread on android-dev ml).
(thanks fredley)


text:
Q: Add several text files into one text file using Mathematica I have twenty data files each contains 1000 lines ("a1.txt, a2.txt....a20.txt"). Now I want to add all these files to a single file and keep the line sequence as followed by the input files (first 1000 from a1.txt, next 1000 from a2.txt and so on).
How can I do that?

A:
A: Do you need to do this in Mathematica? You can just use the shell command cat in Unix / Mac OS. (This question is the reverse of the question "Splitting a text file into smaller text files by line numbers using Mathematica", which I answered yesterday.)
X: I am learning Mathematica for data analysis (in Windows)

Direct commands
Unix paths are used below -- it is better to construct the file names with FileNameJoin for OS-independent behavior.
fnames = FileNames["~/Downloads/a*.txt"];
texts = Import /@ fnames;
Export["~/Downloads/allInOne.txt", StringRiffle[texts, "\n"], "Text"]

Unix / Mac OS
Mentioning this for completeness...
In Unix / Mac OS we can use the command cat. From within Mathematica we can make this call:
Run["cat ~/Downloads/a*.txt > ~/Downloads/allInOne.txt"]

A: OpenRead OpenWrite ReadStringWriteString
Module[
 {
  newfilename = "all.txt",
  wfile, rfile, str
  },
 wfile = OpenWrite[newfilename];
 Table[
  rfile = OpenRead[StringTemplate["File``.txt"][k]];
  str = ReadString[rfile];
  Close[rfile];
  WriteString[wfile, str];
  , {k, 1, 20}
  ];
 Close[newfilename]
 ]

Import and Export
Export[
 "All2.txt",
 StringJoin@Table[
   Import[StringTemplate["File``.txt"][k], "String"]
   , {k, 1, 20}
   ]
 , "String"
 ]

To test my answers I created some files like this
SystemOpen@SetDirectory[$TemporaryDirectory]

Array[
  Export[StringTemplate["File``.txt"][#], (# 1000 + Range[1000]),
    "CSV"] &
  , 20
  ];

Range[1001, 21000] == Flatten@Import["All.txt", "Table"]
(* True *)

Range[1001, 21000] == Flatten@Import["All2.txt", "Table"]
(* True *)