text:
Q: How to debug an Android runtime error? These is the problem again:
01-19 10:46:42.630: E/AndroidRuntime(819): FATAL EXCEPTION: main
01-19 10:46:42.630: E/AndroidRuntime(819): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.as400samplecode/com.as400samplecode.AndroidListViewCursorAdaptorActivity}: java.lang.ClassNotFoundException: Didn't find class "com.as400samplecode.AndroidListViewCursorAdaptorActivity" on path: DexPathList[[zip file "/data/app/com.as400samplecode-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.as400samplecode-2, /system/lib]]
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.os.Looper.loop(Looper.java:137)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread.main(ActivityThread.java:5103)
01-19 10:46:42.630: E/AndroidRuntime(819):  at java.lang.reflect.Method.invokeNative(Native Method)
01-19 10:46:42.630: E/AndroidRuntime(819):  at java.lang.reflect.Method.invoke(Method.java:525)
01-19 10:46:42.630: E/AndroidRuntime(819):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-19 10:46:42.630: E/AndroidRuntime(819):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-19 10:46:42.630: E/AndroidRuntime(819):  at dalvik.system.NativeStart.main(Native Method)
01-19 10:46:42.630: E/AndroidRuntime(819): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.as400samplecode.AndroidListViewCursorAdaptorActivity" on path: DexPathList[[zip file "/data/app/com.as400samplecode-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.as400samplecode-2, /system/lib]]
01-19 10:46:42.630: E/AndroidRuntime(819):  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
01-19 10:46:42.630: E/AndroidRuntime(819):  at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
01-19 10:46:42.630: E/AndroidRuntime(819):  at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
01-19 10:46:42.630: E/AndroidRuntime(819):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
01-19 10:46:42.630: E/AndroidRuntime(819):  ... 11 more

This is my MainActivity.java.
package com.example.bago;

import com.as400samplecode.R;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {

    private CountriesDbAdapter dbHelper;
     private SimpleCursorAdapter dataAdapter;

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

      dbHelper = new CountriesDbAdapter(this);
      dbHelper.open();

      //Clean all data
      dbHelper.deleteAllCountries();
      //Add some data
      dbHelper.insertSomeCountries();

      //Generate ListView from SQLite Database
      displayListView();

     }

     private void displayListView() {

      Cursor cursor = dbHelper.fetchAllCountries();

      // The desired columns to be bound
      String[] columns = new String[] {
        CountriesDbAdapter.KEY_CODE,
        CountriesDbAdapter.KEY_NAME,
        CountriesDbAdapter.KEY_CONTINENT,
        CountriesDbAdapter.KEY_REGION
      };

      // the XML defined views which the data will be bound to
      int[] to = new int[] {
        R.id.code,
        R.id.name,
        R.id.continent,
        R.id.region,
      };

      // create the adapter using the cursor pointing to the desired data
      //as well as the layout information
      dataAdapter = new SimpleCursorAdapter(
        this, R.layout.country_info,
        cursor,
        columns,
        to,
        0);

      ListView listView = (ListView) findViewById(R.id.listView1);
      // Assign adapter to ListView
      listView.setAdapter(dataAdapter);

      listView.setOnItemClickListener(new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> listView, View view,
         int position, long id) {
       // Get the cursor, positioned to the corresponding row in the result set
       Cursor cursor = (Cursor) listView.getItemAtPosition(position);

       // Get the state's capital from this row in the database.
       String countryCode =
        cursor.getString(cursor.getColumnIndexOrThrow("code"));
       Toast.makeText(getApplicationContext(),
         countryCode, Toast.LENGTH_SHORT).show();

       }
      });

      EditText myFilter = (EditText) findViewById(R.id.myFilter);
      myFilter.addTextChangedListener(new TextWatcher() {

       public void afterTextChanged(Editable s) {
       }

       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }

       public void onTextChanged(CharSequence s, int start,
         int before, int count) {
        dataAdapter.getFilter().filter(s.toString());
       }
      });

      dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
             public Cursor runQuery(CharSequence constraint) {
                 return dbHelper.fetchCountriesByName(constraint.toString());
             }
         });

     }
    }

Country.java
package com.example.bago;

public class Country {
    String code = null;
     String name = null;
     String continent = null;
     String region = null;

     public String getCode() {
      return code;
     }
     public void setCode(String code) {
      this.code = code;
     }
     public String getName() {
      return name;
     }
     public void setName(String name) {
      this.name = name;
     }
     public String getContinent() {
      return continent;
     }
     public void setContinent(String continent) {
      this.continent = continent;
     }
     public String getRegion() {
      return region;
     }
     public void setRegion(String region) {
      this.region = region;
     }

    }

CountriesDbAdapter.java
package com.example.bago;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class CountriesDbAdapter {
    public static final String KEY_ROWID = "_id";
     public static final String KEY_CODE = "code";
     public static final String KEY_NAME = "name";
     public static final String KEY_CONTINENT = "continent";
     public static final String KEY_REGION = "region";

     private static final String TAG = "CountriesDbAdapter";
     private DatabaseHelper mDbHelper;
     private SQLiteDatabase mDb;

     private static final String DATABASE_NAME = "World";
     private static final String SQLITE_TABLE = "Country";
     private static final int DATABASE_VERSION = 1;

     private final Context mCtx;

     private static final String DATABASE_CREATE =
      "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
      KEY_ROWID + " integer PRIMARY KEY autoincrement," +
      KEY_CODE + "," +
      KEY_NAME + "," +
      KEY_CONTINENT + "," +
      KEY_REGION + "," +
      " UNIQUE (" + KEY_CODE +"));";

     private static class DatabaseHelper extends SQLiteOpenHelper {

      DatabaseHelper(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
       Log.w(TAG, DATABASE_CREATE);
       db.execSQL(DATABASE_CREATE);
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
         + newVersion + ", which will destroy all old data");
       db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
       onCreate(db);
      }
     }

     public CountriesDbAdapter(Context ctx) {
      this.mCtx = ctx;
     }

     public CountriesDbAdapter open() throws SQLException {
      mDbHelper = new DatabaseHelper(mCtx);
      mDb = mDbHelper.getWritableDatabase();
      return this;
     }

     public void close() {
      if (mDbHelper != null) {
       mDbHelper.close();
      }
     }

     public long createCountry(String code, String name,
       String continent, String region) {

      ContentValues initialValues = new ContentValues();
      initialValues.put(KEY_CODE, code);
      initialValues.put(KEY_NAME, name);
      initialValues.put(KEY_CONTINENT, continent);
      initialValues.put(KEY_REGION, region);

      return mDb.insert(SQLITE_TABLE, null, initialValues);
     }

     public boolean deleteAllCountries() {

      int doneDelete = 0;
      doneDelete = mDb.delete(SQLITE_TABLE, null , null);
      Log.w(TAG, Integer.toString(doneDelete));
      return doneDelete > 0;

     }

     public Cursor fetchCountriesByName(String inputText) throws SQLException {
      Log.w(TAG, inputText);
      Cursor mCursor = null;
      if (inputText == null  ||  inputText.length () == 0)  {
       mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
         KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
         null, null, null, null, null);

      }
      else {
       mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
         KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
         KEY_NAME + " like '%" + inputText + "%'", null,
         null, null, null, null);
      }
      if (mCursor != null) {
       mCursor.moveToFirst();
      }
      return mCursor;

     }

     public Cursor fetchAllCountries() {

      Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
        KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
        null, null, null, null, null);

      if (mCursor != null) {
       mCursor.moveToFirst();
      }
      return mCursor;
     }

     public void insertSomeCountries() {

      createCountry("AFG","Afghanistan","Asia","Southern and Central Asia");
      createCountry("ALB","Albania","Europe","Southern Europe");
      createCountry("DZA","Algeria","Africa","Northern Africa");
      createCountry("ASM","American Samoa","Oceania","Polynesia");
      createCountry("AND","Andorra","Europe","Southern Europe");
      createCountry("AGO","Angola","Africa","Central Africa");
      createCountry("AIA","Anguilla","North America","Caribbean");

     }

    }

A: Hard to tell, but it looks like android is trying to load following activity

java.lang.ClassNotFoundException: Didn't find class "com.as400samplecode.AndroidListViewCursorAdaptorActivity"

maybe you  have AndroidListViewCursorAdaptorActivity in your manifest file but you dont have it in you classes?


text:
Q: What are some good resources for the history of time series analysis? I have checked out the answer to this question on stats.stackexchange: What are good resources providing a history of statistics?  Indeed, the Stigler book "Statistics on the Table" looks excellent and I'm looking forward to reading it.  But I'm more interested in the development of modern ARIMA models.
I think I remember hearing that much progress was stimulated in trying to predict random inaccuracies with artillery guns around WWII.  Also, of course, to some extent astronomers throughout the second half of the millennium were using some sort of time series for understanding the motion of heavenly bodies.  However, I can't remember where I heard about the artillery application of time series and I have a background in physics, and I don't really know what statistical methods the astronomers were working with.
So, I would love to hear what you think are the most pertinent historical influences on the development of time series methods, e.g., were they stimulated mainly by finance, defense, geology/geophysics, or some combination of all these and more? Are there informative books or websites on the history of ARIMA?

A: You might find Mary S. Morgan's History of Econometric Ideas interesting. Its focus is in on the history of economic cycle analysis from late 19th to mid 20th century. In particular, the story of the debate on the relationship between sunspots and agricultural output was fascinating.

A: On time series visualization, a good reference is Aigner, Miksch, Schumann and Tominski (2011) Visualization of Time-Oriented Data, Springer. Chapter 2 covers history.

A: Another source of the history of time series analysis is "The foundations of modern time series analysis" by Mills, Terence C.

A: This is quite good also. I'm not sure how it compares to the ones already mentioned.
Statistical Visions in Time (A History of Time Series Analysis, 1662-1938) by Judy L. Klein.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysqldump returning empty file My script is as following:
<?php

$database = 'database';
$user = 'user';
$password = 'pass';

$filename = 'database_backup_'.date( 'd-m-Y-h:i:s' ).'.sql';

$result = exec( 'mysqldump '.$database.' --password='.$password.' --user='.$user.' --single-transaction >/some-path/backups/'.$filename, $output );

?>

This script is creating a file but it is empty.


text:
Q: Character set in SQL Server 2005 I've run this code in MySQL, and it's succeeded. But when I run it in SQL Server 2005, this error occurred:

Incorrect syntax near the keyword
  'DEFAULT'

This is the code:
CREATE DATABASE mydb DEFAULT CHARACTER SET utf8

Anyone can explain why it couldn't run successfully in SQL Server 2005.
Thanks and sorry for my bad English!

A: SQL Server doesn't support the "default character set" on the "create database" statement: http://msdn.microsoft.com/en-us/library/ms176061(v=SQL.90).aspx


text:
Q: How to show label given value in Angular [ng-select] I recently used ng-select library in my project and it works great. One limitation i found is that the library expects a string to be inputed in order to render the label properly. With that, I realized that I'll have an issue if I want to show the label of an id given that the model only has the id stored.
As oppose to other libraries (which at this point I am not considering since this library answers most of my needs), the id of the element is being stored in the model. Hence in order to show the label somewhere else I need to translate this. This can be costly since I have dozens of catalogs to work with.
Take this example:
[{ 'id' : 'A', 'label': 'Apple'},
 { 'id' : 'B', 'label': 'Banana'},
 { 'id' : 'C', 'label': 'Cranberry'}]

The model stores:
{fruit: 'A'};

In order to show the label anywhere I need to translate 'A' to 'Apple' somehow.
I thought of creating a pipe but then I'll need to do so for each catalog I hold.
Any ideas on how to approach?


text:
Q: Can we change the Size of text which is written in values of putextra and assigned in next activity of textview? I am working on a project in which, I am exporting string value from one activity to 2nd activity but I just can't resize that string value which is assigned inside TextView in second activity.
Code of 1st activity:
  if (modelList.get(position).getJtitle().equals("Hello World"))
            {
                Intent intent = new Intent(mContext,CodeActivity.class);
                intent.putExtra("actionBarTitle","Hello World");
                intent.putExtra("contentTv","Class HelloWorld\n" +
                        "{\n" +
                        "public static void main(String args[])\n" +
                        "{\n" +
                        "System.out.println(\"Welcome to Hello World Program\");\n" +
                        "}\n" +
                        "}");
                mContext.startActivity(intent);
            }

2nd activity code :
    setContentView(R.layout.activity_jcode);

    ActionBar actionBar = getSupportActionBar();

    TextView codetv = findViewById(R.id.jtextview);
    Intent intent = getIntent();
    String mActionBarTitle = intent.getStringExtra("actionBarTitle");
    String mContent = intent.getStringExtra("contentTv");
    actionBar.setTitle(mActionBarTitle);
    codetv.setText(mContent);
}

The output looks like this, how can we change that textSize:

A: setContentView(R.layout.activity_jcode);

ActionBar actionBar = getSupportActionBar();

TextView codetv = findViewById(R.id.jtextview);
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
String mContent = intent.getStringExtra("contentTv");
actionBar.setTitle(mActionBarTitle);
codetv.setText(mContent);
codetv.setTextSize(10); //Replace 10 with whatever size you want.

}

A: Why don't you try setting TextSize programmatically to codetv
Or set textSize of TextView statically in .xml layout


text:
Q: Error at "unsigned" when creating table in MySQL? I can't tell what is wrong with this query.
create table roles
(
  id                int unsigned        not null   auto_increment
 ,name              varchar(32)         not null
 ,phone             varchar(256)        not null

 ,primary key   (id)
)
engine=innodb
default charset=utf8;

When I try to run it, I get:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'unsigned  not null    auto_increment ,role_id int unsigned ' at
  line 3

Using MySQL 5.7

A: Thanks for the advice, tadman
Turns out I had a tab between "int unsigned" instead of a space. Replaced the tab with a space and it worked just fine.
That was driving me crazy for almost 2 hours.


text:
Q: Creating array reset I flag? C++ / asm I've got a problem with interrupt flag being reset.
After setting the interrupt flag to 0 with asm cli, it comes to a line of code char* c = new char[size], and when it finishes initializing that array, it resets the I flag to 1. How can i make it that flag I stays on current value the whole time, because writing another asm cli after the new[] operator isn't the solution, giving that i have gap between those 2 instructions which enables the interrupts?
Thread::Thread(StackSize stackSize, Time timeSlice) {
#ifndef BCC_BLOCK_IGNORE
    DIS_INT // a macro: #define DIS_INT asm cli
#endif

    myPCB = new PCB(stackSize,timeSlice,this);

#ifndef BCC_BLOCK_IGNORE
    ENB_INT
#endif
}

this is where i set I flag to 0 and call the PCB constructor
PCB::PCB(StackSize stackSize, Time timeSlice, Thread* thread){
    time = timeSlice;
    myThread = thread;
    stack = createStack(stackSize);
    ...

char* PCB::createStack(StackSize stackSize){
    char* stek = new char[stackSize];         // after this line, IF = 1
#ifndef BCC_BLOCK_IGNORE                      // which is not desired
    newSS = FP_SEG(stek+stackSize);
    newSP = FP_OFF(stek+stackSize);
    asm{
        mov oldSS, ss
        mov oldSP, sp
        mov ss, newSS
        mov sp, newSP

        push ax
        push bx
        push cx
        push dx
        push es
        push ds
        push si
        push di
        push bp

        mov newSS, ss
        mov newSP, sp
        mov ss, oldSS
        mov sp, oldSP
    }
    this->stekp = MK_FP(newSS,newSP);
#endif
    return stek;
}


text:
Q: How are EX-Raid Passes Given Out? What are the rules by which EX Raid passes are given out in Pokemon Go? Is there some way to maximize my odds of being able to get one?
I got one last Community Day, and while I caught Mewtwo that time, I wanted to figure out how I could get another so I could get some more candy and/or a shiny version.

A: Your best bet on getting another one is to coordinate with a local group. The Silph Road subreddit has put together a map that will help you find the closest discord group to your area. These servers will typically have an EX Raid channel, as well as other channels, such as one for ditto spotting. I only learned about this map in the last two days, although I've been on two different discord groups in as many months (one in CA and one in PA).
However, we also know some of the rules by which Niantic uses to give out EX Raid passes, but there's still some guess work. Niantic themselves have said that battling and raiding at "sponsored gyms and gyms in parks" as well as having a high raid frequency and high gym badge ranking will increase your chances of getting an invite. How much this affects your odds, we still don't know.
What we do know:

*

*Head over to Pokemon Go Map dot info and click the settings in the top right, visual tab, and enable the level 12 S2 cell overlay (although one source I found said its level 13 cells, but all others agree that it's level 12).

*Only one gym inside each of these "super cells" can be EX-eligible in each "wave" of invites.

*

*This site has some information about waves. It does not appear to be regular, but it is roughly once a week with a rotating day-of-week.

*Gym must be located in a park (there's an overlay for this too, but moving and zooming the map causes a lot of requests and you can get timed out). The standard map view is usually accurate enough.

*You must participate in a raid at an EX-eligible gym

*

*It does not need to be a legendary raid

*That gym must have a certain number of raid participants.

*

*It still isn't clear how many or over what time period. The best guess is "about 20" but it doesn't need to be the same raid instance: multiple groups can raid separately and it still counts. One source lists as low as 14 unique players.

*The location of the EX Raid will be at the gym that made you eligible to receive the pass for and for a data and time 7 to 10 days in the future.

Even after all of this, not all trainers that participate in a raid at an EX-eligible gym will receive a EX Raid pass. The statistics work being done on the influence of gym badges and so forth doesn't yet have enough data, and that data collection may be flawed (as people who do not receive an invite are less likely to report).
Different strategies are around, but the one that makes sense to me is to just raid every gym within a given "super cell" at least once. However, coordinating with your local group will be important. They will likely already know which gyms can be EX eligible and have a strategy for raiding successfully.
One interesting side note: if you ever get a shiny raid boss, the catch rate is 100%. Toss a pinap at it and throw clean; easy 6 candies.
Other sources:
Pokemon Go Press
Pokemon Go Hub
Pokemon Go Hub (more comprehensive)


text:
Q: Dependency injection for Dialog classes Should dependency injection be used for the dialog class?
For example, is this code principled?
How about Intent, Navigate, Binding and...?
@Module
@InstallIn(FragmentComponent::class)
object FragmentModule {
    @FragmentScoped
    @Provides
    fun provideDialog()=
     SampleDialog()
}


text:
Q: Unable to bind function on dynamically created element I'm creating a simple shopping cart with javascript, and what would a shopping cart without a button to remove an item be?
The cart is created on-the-fly with javascript, so the elements won't exist on page load. However, this shouldn't be a problem with this?
$(".removeFromCart").on("click",function(e){
    alert("GO AWAY PLEASE..");
    var tuoteID = $(this).attr("data-id");
    deleteFromCart(tuoteID);
});

The element (created on the fly) simply looks like this:
×

But it won't trigger. If I replace .replaceFromCart with, for example, p, it will trigger every time I click on a paragraph.
This isn't the first time I'm having problems with .on() and it always takes half of my hair to solve, so maybe someone with more experience could point me what I'm doing wrong.

A: You need event delegation, using other version of the jQuery on() function. You have to give the static parent that is present the time the binding code is executed or you can delegate to body or document.
$(document).on("click",".removeFromCart", function(e){
    alert("GO AWAY PLEASE..");
    var tuoteID = $(this).attr("data-id");
    deleteFromCart(tuoteID);
});

Delegated events have the advantage that they can process events from
  descendant elements that are added to the document at a later time. By
  picking an element that is guaranteed to be present at the time the
  delegated event handler is attached, you can use delegated events to
  avoid the need to frequently attach and remove event handlers, jQuery doc.


text:
Q: Xamarin iOS TableView Checkmark row checks other row too I have a TableView where the user can check multiple rows.
Now I have the problem that when I select e.g. the 5th element the 27th element in the list is automatically checked too, but I cant explain why.
I´m using the following Code for the TableViewSource base class:
public abstract class BaseChecklistTableViewSource : UITableViewSource
{
    protected int checkCount;

    public BaseChecklistTableViewSource()
    {
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        var cell = tableView.CellAt(indexPath);

        if (indexPath.Row >= 0)
        {
            if (cell.Accessory == UITableViewCellAccessory.None)
            {
                cell.Accessory = UITableViewCellAccessory.Checkmark;
                checkCount++;
            }
            else if (cell.Accessory == UITableViewCellAccessory.Checkmark)
            {
                cell.Accessory = UITableViewCellAccessory.None;
                checkCount--;
            }

            CheckCheckCount();

        }
    }

    protected void CheckCheckCount()
    {
        if (checkCount > 0)
        {
            EnableDoneButton();
        }
        else if (checkCount == 0)
        {
            DisableDoneButton();
        }
    }

    protected abstract void EnableDoneButton();
    protected abstract void DisableDoneButton();
}

This is the code of the concrete class of "BaseChecklistTableViewSource":
public partial class CheckunitTableViewSource : BaseChecklistTableViewSource
{
    ListCheckunitController controller;
    private IEnumerable<Checkunit> existingCheckunits;

    public CheckunitTableViewSource(ListCheckunitController controller)
    {
        this.controller = controller;
        this.existingCheckunits = new List<Checkunit>();
    }

    public CheckunitTableViewSource(ListCheckunitController controller, IEnumerable<Checkunit> existingCheckunits) : this(controller)
    {
        if (existingCheckunits == null || !existingCheckunits.Any())
        {
            throw new ArgumentNullException(nameof(existingCheckunits));
        }

        this.existingCheckunits = existingCheckunits;
        checkCount = this.existingCheckunits.Count();

        CheckCheckCount();
    }

    // Returns the number of rows in each section of the table
    public override nint RowsInSection(UITableView tableview, nint section)
    {
        if (controller.Checkunits == null)
        {
            return 0;
        }
        return controller.Checkunits.Count();
    }
    //
    // Returns a table cell for the row indicated by row property of the NSIndexPath
    // This method is called multiple times to populate each row of the table.
    // The method automatically uses cells that have scrolled off the screen or creates new ones as necessary.
    //
    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        var cell = tableView.DequeueReusableCell("checkunitViewCell") ?? new UITableViewCell();
        int row = indexPath.Row;
        var element = controller.Checkunits.ElementAt(row);

        if(existingCheckunits.FirstOrDefault(e => e.Id == element.Id) != null)
        {
            cell.Accessory = UITableViewCellAccessory.Checkmark;
        }

        //if(cell.Accessory == UITableViewCellAccessory.Checkmark)
        //{
        //    checkCount++;
        //}

        cell.TextLabel.Text = $"{element.Order}. {element.Designation}";
        cell.Tag = element.Id;
        return cell;
    }

    protected override void EnableDoneButton()
    {
        controller.EnableDoneButton();
    }

    protected override void DisableDoneButton()
    {
        controller.DisableDoneButton();
    }
}

I tried to use a breakpoint in the RowSelected method, but the breakpoint will only be hit once!
This is the Code for the TableViewController:
public partial class ListCheckunitController : BaseTableViewController
{
    private ImmobilePerpetration masterModel;
    private LoadingOverlay loadingOverlay;
    public IEnumerable<Checkunit> Checkunits { get; set; }

    public IEnumerable<Checkunit> existingCheckunits;
    public IEnumerable<CheckpointAssessment> existingAssessments;
    public static readonly NSString callHistoryCellId = new NSString("checkunitViewCell");
    UIRefreshControl refreshControl;
    private UIBarButtonItem doneButton;

    public ListCheckunitController(IntPtr handle) : base(handle)
    {
        existingCheckunits = new List<Checkunit>();
        existingAssessments = new List<CheckpointAssessment>();
    }

    public void Initialize(ImmobilePerpetration masterModel)
    {
        if (masterModel == null)
        {
            throw new ArgumentNullException(nameof(masterModel));
        }

        this.masterModel = masterModel;
    }

    public void Initialize(ImmobilePerpetration masterModel, IEnumerable<CheckpointAssessment> existingAssessments, IEnumerable<Checkunit> existingCheckunits)
    {
        Initialize(masterModel);

        if(existingAssessments == null || !existingAssessments.Any())
        {
            throw new ArgumentNullException(nameof(existingAssessments));
        }

        if (existingCheckunits == null || !existingCheckunits.Any())
        {
            throw new ArgumentNullException(nameof(existingCheckunits));
        }

        this.existingAssessments = existingAssessments;
        this.existingCheckunits = existingCheckunits;
    }

    async Task RefreshAsync(bool onlineSync)
    {
        InvokeOnMainThread(() => refreshControl.BeginRefreshing());
        try
        {
            var syncCtrl = new SynchronizationControllerAsync();
            Checkunits = await syncCtrl.SynchronizeCheckUnitAsync(onlineSync).ConfigureAwait(false);
        }
        catch (Exception e)
        {
            InvokeOnMainThread(() => { AlertHelper.ShowError(e.Message, this);});
        }

        InvokeOnMainThread(() =>
        {
            ListCheckunitTable.ReloadData();
            refreshControl.EndRefreshing();
        });

    }

    void AddRefreshControl()
    {
        refreshControl = new UIRefreshControl();
        refreshControl.ValueChanged += async (sender, e) =>
        {
            await RefreshAsync(true).ConfigureAwait(false);
        };
    }

    public override async void ViewDidLoad()
    {
        var bounds = UIScreen.MainScreen.Bounds;
        loadingOverlay = new LoadingOverlay(bounds);
        View.Add(loadingOverlay);

        AddRefreshControl();
        await RefreshAsync(false).ConfigureAwait(false);

        InvokeOnMainThread(() =>
        {
            doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (s, e) =>
            {
                PerformSegue("ListCheckpointsSegue", this);
            });

            doneButton.Enabled = false;

            CheckunitTableViewSource source = null;
            if(existingCheckunits.Any())
            {
                source = new CheckunitTableViewSource(this, existingCheckunits);
            }
            else
            {
                source = new CheckunitTableViewSource(this);
            }

            ListCheckunitTable.Source = source;
            ListCheckunitTable.Add(refreshControl);

            loadingOverlay.Hide();

            this.SetToolbarItems(new UIBarButtonItem[] {
                  new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) { Width = 50 }
                , doneButton
            }, false);

            this.NavigationController.ToolbarHidden = false;
        });
    }

    public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
    {
        if (segue.Identifier == "ListCheckpointsSegue")
        {
            var controller = segue.DestinationViewController as ListCheckpointController;

            IList<Checkunit> markedCategories = new List<Checkunit>();

            for (int i = 0; i < ListCheckunitTable.NumberOfRowsInSection(0); i++)
            {
                var cell = ListCheckunitTable.CellAt(NSIndexPath.FromItemSection(i, 0));

                if(cell != null)
                {
                    if(cell.Accessory == UITableViewCellAccessory.Checkmark)
                    {
                        var originalObject = Checkunits.Where(e => e.Id == cell.Tag).SingleOrDefault();

                        if(originalObject != null)
                        {
                            markedCategories.Add(originalObject);
                        }
                        else
                        {
                            //TODO: Handle error case!
                        }
                    }
                }
            }

            if (markedCategories.Any())
            {
                if (controller != null)
                {
                    if(existingAssessments.Any() && existingCheckunits.Any())
                    {
                        controller.Initialize(masterModel, markedCategories, existingAssessments, existingCheckunits);
                    }
                    else
                    {
                        controller.Initialize(masterModel, markedCategories);
                    }

                }
            }
            else
            {
                //TODO: Print out message, that there are no marked elements!
            }
        }
    }

    public void DisableDoneButton()
    {
        doneButton.Enabled = false;
    }

    public void EnableDoneButton()
    {
        doneButton.Enabled = true;
    }
}

The used base class only handles a common sidebar view nothing more.
Does anyone have an idea what is going wrong here?

A: Well, I ended up in creating a bool Array that stores the checked elements.
I tried a demo app from Github from Xamarin and I had the exact same problem.
This leads me to the conclusion that this must be a Xamarin Bug!


text:
Q: PHP Order by multiple columns I need an SQL query that orders a column by a ranking system, but if the ranks are the same, use the id as only a secondary, last resort order. Can anyone help me accomplish this? I have the system working with ORDER BY, but if rankings are the same, it screws up the system. I only need the primary, secondary ORDER BY code and not a whole query.

A: You just need to specify two conditions (separated by commas) in your ORDER BY clause:
ORDER BY ranking, id


text:
Q: How to mock an array containing objects using mockito? In my Mockito unit test I am trying to mock an array containing instances of the object Message. To do this I try to mock it like normal objects so like:
private var messagesMock = mock(Array<Message>::class.java)
This gives the following error/exception:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class [Lrobot.fsrt.robotguest.common.data.Message;
Mockito cannot mock/spy because :
 - VM does not not support modification of given type

How to mock an array the right way using Mockito?

A: A distinct non-answer: you (almost) never mock objects that represent containers!
An array is just that: a container.
You create the container with the size you need, and then you put your mocked objects into that ordinary container, and make sure that container with your prepared content gets used by your production code.
It is as simple as that: you don't mock arrays, or lists, or maps: you create them as is, and manipulate their content!


text:
Q: Existe diferença entre usar "return" ou "exit()" para encerrar a função "main()"? A função exit() encerra a execução da aplicação imediatamente. O comando return faz sair da função, mas quando está dentro do main() ele também sairá da aplicação, inclusive o valor usado nele será devolvido para quem chamou a aplicação como um código de erro (zero é ok), assim como a função de saída.
Claro que há a diferença em outras funções, onde o exit() encerra aplicação imediatamente e o comando voltará o fluxo de execução para a função chamadora.
Se ambas fazem a mesma coisa na situação descrita, tanto faz usar um ou outro?

A: Há uma diferença semântica importante em C++. O return encerrará o escopo e chamará todos os destrutores pendentes. Se for o encerramento da aplicação mesmo, raramente a chamada dos destrutores produzirá um resultado diferente, mas tecnicamente é possível que algum deles faça algo que seja importante para o fim da aplicação, nem que seja imprimir uma informação relevante para o usuário ou log.
Mesmo que a ação pareça a mesma, a função exit() provoca uma saía prematura da aplicação. Então a execução é encerrada quase imediatamente. O exit() finaliza os objetos estáticos, mas não os destrutores. Já o abort()  e _Exit() nem isso faz e encerra na hora.
Há diferença mesmo em C se tiver funções registradas com atexit(). Essas funções sempre serão executadas não importa como a aplicação está sendo encerrada. Mas haverá comportamento indefinido se uma das funções vinculadas em atexit() tiver referência para algum dado na stack. Ocorre algo parecido com setbuf() e setvbuf(). Isso é importante principalmente em C.documentação
Note que a função main() não é especial e pode ser chamada dentro da aplicação. Nesse caso haverá uma diferença importante já que um return não encerrará a aplicação, ainda que no contexto da pergunta isso não aconteceria. Mas entenda que se o que você escreveu não for chamado pelo sistema operacional (de uma forma ou de outra) e esse main() faz parte de um módulo que será carregado e usado em outra aplicação, o seu módulo encerrará a aplicação e não só o seu código se usar o exit(), o return então será o mais adequado na maioria das situações.
Uma chamada ao main() pode ser recursiva, ainda que não deva. Claro que há diferença nesse caso, mas cai no que eu falei no parágrafo anterior.
Por isso que sempre tem que escolher o jeito mais semanticamente correto. Se quer encerrar a aplicação imediatamente use o exit(), caso contrário use o return. Muitas pessoas dizem que se o main() está encerrando a aplicação, o exit() é o mais adequado. Nem todo mundo concorda, principalmente em C++. Por isso que é bom entender o funcionamento, as implicações de cada um e não seguir regras cegamente.
Não sei se conta como diferença, por ser uma função, para usá-la precisa usar um #include para ela estar disponível, e se a unidade de código que ela está contida não entraria na aplicação, o executável ficará um pouco maior. O comando está sempre disponível.
Coloquei no GitHub para referência futura.


text:
Q: D = r * t based on a boy running up and down a hill Jack is three times as fast running down a hill than running up the hill. If it takes Jack an hour longer to run up the hill than run down the hill, how long, in hours, does it take Jack to run up the hill?

I don't even know where to start because when I plug in the information into D = r * t I always get a two variable equation. One variable is the rate - x and the other is the time - y.
Any help would be appreciated.

A: Guide:
$$t_{up}=3t_{down}$$
$$t_{up}=t_{down}+1$$
Solve for $t_{up}$.

A: One unit of time to run down the hill.
Three units of time to run up the hill.
That's two more units to run up than down.
From the problem, those two units are equal to one hour.
So a unit of time is half an hour.

A: $v_0$ is Jack's speed running up the hill
$v_1$ is Jack's speed running down the hill
$v_1$ = 3 * $v_0$
D = $v_0$ * $t_0$
D = $v_1$ * $t_1$
$t_1$ = $t_0$ - 1
Now set the equations equal to each other and substitute $v_1$ with $v_0$ and $t_1$ with $t_0$
$v_0 * t_0 = 3 * v_0 * (t_0 - 1)$
$t_0 = 3 * t_0 - 3$
$t_0 = 3/2$ hours


text:
Q: How to include own css on wordpress tinymce editor? I have added some text on tinymce editor on load.
(Every time you click on Add new the tinymce editor load with this text.)
but problem is how to enable css class which are using in default text.
Thanks

A: add_editor_style is recommended for theme.
You can mce_css filter in plugin. The following sample code is from here
function plugin_mce_css( $mce_css ) {
  if ( !empty( $mce_css ) )
    $mce_css .= ',';
    $mce_css .= plugins_url( 'editor.css', __FILE__ );
    return $mce_css;
  }
add_filter( 'mce_css', 'plugin_mce_css' );

A: Nothing I found worked. Took me half a day on Google, but finally stumbled upon this script that works:
function kwh_add_editor_style( $mceInit ) {

  $custom_css = get_theme_mod( 'custom_css' );
  $styles = '.mce-content-body { EDIT YOUR CUSTOM CSS HERE ' . $custom_css . '; }';

  if ( !isset( $mceInit['content_style'] ) ) {
    $mceInit['content_style'] = $styles . ' ';
  } else {
    $mceInit['content_style'] .= ' ' . $styles . ' ';
  }
  return $mceInit;
}
add_filter( 'tiny_mce_before_init', 'kwh_add_editor_style' );

Source of snippet.

A: Use add_editor_style
e.g.: functions.php
add_editor_style('custom-editor-style.css');

http://codex.wordpress.org/Function_Reference/add_editor_style


text:
Q: Differentiation. I am unable to differentiate the following,
$$y=\frac{1}{x+1}+x$$
I obtained the expression for $$\frac{dy}{dx}= \frac{-(x^2+x+1)}{(x+1)^2} $$
The actual answer stated for an expression in my textbook $$\frac{dy}{dx}= \frac{(x^2+2x)}{(x+1)^2} $$
I require assistance.

A: $$\dfrac{dy}{dx}=\dfrac{d\dfrac1{(x+1)}}{dx}+\dfrac{dx}{dx}=-\dfrac1{(x+1)^2}+1=?$$

A: $$y=(x+1)^{-1}+x$$
$$y'=-1(x+1)^{-2}+1$$
$$y'=\frac{-1}{(x+1)^2}+1=\frac{(x^2+2x)}{(x+1)^2}$$

A: first we simplify to $$\frac{1}{x+1}+x=\frac{x^2+x+1}{x+1}$$ applying the quotient rule we get $$y'=\frac{(2x+1)(x+1)-(x^2+x+1)}{(x+1)^2}$$
can you simplify this?

A: We begin by simplifying $y$ as $y=\frac{1+x(x+1)}{(x+1)}$.
We then compute $y'$ using the quotient rule for differentiation which is:
$h(x)=\frac{f(x)}{g(x)} \rightarrow h'(x)=\frac{g(x)f'(x)-f(x)g'(x)}{g(x)^2}$
Thus, $y'=\frac{(x+1)(2x+1)-(x^2+x+1)(1)}{(x+1)^2}$
Hence, $y'=\frac{x^2+2x}{(x+1)^2}$.

A: As we know that derivative of $\frac{1}{x}$ is $\frac{-1}{x^2}$ :
So, now finding derivative of  $\frac{1}{(x+1)}$ +$x$ is:
$\frac{d}{dx}$ $\frac{1}{(x+1)}$ +$\frac{dx}{dx}$
= -$\frac{\frac{d(x+1)}{dx}}{(x+1)^2}$ +1
= -$\frac{\frac{d(x)}{dx} + \frac{d(1)}{dx}}{(x+1)^2}$ +1
= 1 - $\frac{1 + 0}{(x+1)^2}$
= $\frac{(x+1)^2-1}{(x+1)^2}$
= $\frac{x^2 + 2x + 1 - 1}{(x+1)^2}$
= $\frac{x^2 + 2x}{(x+1)^2}$
 Hence the answer..
I hope this helps.


text:
Q: Ruby on Rails Tutorial: How to edit user information without confirming the password I've been working through the Ruby on Rails Tutorial by Michael Hartl.  Currently, in order to edit any of the User attributes, the user must confirm their password.  Is there any way to update the user attributes without having to do this?
My form looks like this:
    <%= form_for @user do |f| %>

        <%= f.label :course1 %>

        <%= f.text_field :course1 %>

        <%= f.submit "Update" %>

    <% end %>"

and my update definition in users_controller.rb looks like this:
def update

    if @user.update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
    else
        @title = "Edit user"
        render 'edit'
    end
end

Currently, the update_attributes action fails.
Thanks!

A: To slightly refine Dylan's answer, you need to define that password_changed method which was giving you the error. I used a different name, as I don't care if the password has been changed.
 validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 },
                       :unless => :already_has_password?

  private

    def already_has_password?
      !self.encrypted_password.blank?
    end

A: On your User model, you probably have something along the lines of:
validates_presence_of :password_confirmation

Add an if clause as follows, that way it only checks for the confirmation when the password is actually being changed:
validates_presence_of :password_confirmation, :if => :password_changed?

A: If you are using bcrypt to encrypt the password, here is the code that worked for me on Rails 4
#--Code for User method
validates :password, presence: true, confirmation: true, :unless => :already_has_password?
#
private
    def already_has_password?
      !self.password_digest.blank?
    end


text:
Q: Validation in modal form I have a simple modal form in which I have to check user entered data. But after validation the form gets closed. It behaves like this because of not empty DialogResult property but I need this value for other purposes (in a parent form)
Any ideas?
A little code to clear things up

//This method creates and calls a modal form.
public static Definition edit(Definition w)
{
    EditForm ed = new EditForm();
    DialogResult dr = ed.ShowDialog();
    if (dr == DialogResult.OK)
    {
       //update some fields of passed object
    }
    //other code
}

private void btnSave_Click(object sender, EventArgs e)
{
       if (validateForm())
       {
           DialogResult = DialogResult.Yes;
           Close();
       }
}

A: I would do it this way:
private void btnSave_Click(object sender, EventArgs e)
{
       if (validateForm())
       {
           DialogResult = DialogResult.Yes;
           Close();
       }
       else
       {
           DialogResult = DialogResult.None;
       }
}

I.e. as you said, clear the DialogResult.

A: Add a FormClosing event handler and then if the validation fails set e.Cancel = true:
private void EditForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.DialogResult == DialogResult.OK)
    {
        e.Cancel = !ValidateInput();
    }
}

This will leave you sub form open and let the user correct the mistakes. You can check whether the "OK" or "Cancel"/Window Close button has been clicked by checking the DialogResult and only performing the validation if it's OK.


text:
Q: Decision Tree in haskell defining >>= and return I'm trying to make a Decision Tree for a game and I have:
data DecisionTree a
   = Result a
   | Decision [DecisionTree a]
   deriving (Eq,Show)`

furthermore, I have
instance Functor DecisionTree where
    fmap = liftM

now I have to define
instance Monad DecisionTree where
-- return :: a -> DecisionTree a
   return = ...
-- (>>=) :: DecisionTree a -> (a -> DecisionTree b) -> DecisionTree b
   (>>=) = ...

Now I'm kinda confused how to fill in the definitions.
To define >>= I tried splitting the definition into two cases:
(>>=) (Result a) f    = f a
(>>=) (Decision ys) f = Decision (fmap (>>= f) ys)

As for return I thought at least something like
return = Result

but this only builds Result a and no Decision [DecisionTree a].
Am I completely off or am I close?

A: This is the free monad for []. As such, while there may be multiple ways to define a monad instance (per @leftroundabout), there is one canonical way to define a free monad instance, which is the one you have chosen. (You can compare your implementation to that of Free and see that they are equivalent. The only difference is that you fix the choice of f to [].)

but this only builds Result a and no Decision [DecisionTree a].

I'm not sure what this means, but an arrow a -> DecisionTree b that produces a Decision will produce a Decision. return will always produce a Result, but that is expected.


text:
Q: C# Form2 chamando o Form1 Boa noite estou desenvolvendo uma aplicação de cadastros de produtos, porém preciso chamar o form2 primeiro do que o form1. Vocês poderiam me auxiliar de como fazer isso?

A: Vá no arquivo Program.cs e lá achará a seguinte linha
Application.Run(new Form1());

Mude para o formulário que quer utilizar. Em seu caso:
Application.Run(new Form2());


text:
Q: How to change the pictures' shape to circle? I had a list of users who has birthday on this month and it is being shown out by using Lightning Web Component card, however, I want to make the shape of their profile picture to be circle (like Facebook profile picture). How can I do that? Also, if possible, how can I erase all the square border of all the picture above. Thanks in advance !
}
Here is my code:
CSS:
.casedt{
    overflow-y: auto;
}
.imgBox {
    width: 100%;
    height: 100%;
    border-radius: 30%;
}

a{
    color: black;
}
.slds-m-around_x-small{
    border-radius: 4px;
}
.slds-box{
    margin-top: 100%;
}

HTML:
<template>
    <lightning-card title="This Month Birthday" icon-name="custom:custom11">
       <lightning-layout multiple-rows="true">
          <lightning-layout-item class="slds-p-around_xx-small" size="12">
             <lightning-layout>
                <lightning-layout-item class="slds-p-around_xx-small" size='12'>

                      <lightning-layout class='casedt'>
                         <template for:each={data} for:item="item">
                            <lightning-layout-item size="3" class="slds-m-around_x-small slds-border_top slds-border_left slds-border_bottom slds-border_right" key={item.id} >
                               <lightning-tile label='' type="media" variant="Narrow">

                               </lightning-tile>
                            </lightning-layout-item>
                         </template>
                      </lightning-layout>

                </lightning-layout-item>
             </lightning-layout>
          </lightning-layout-item>
       </lightning-layout>
    </lightning-card>
</template>

JS :
import { LightningElement,wire,track } from 'lwc';
import getRecords from '@salesforce/apex/BirthdayNotiController.getRecords';

export default class BirthdayNotification extends LightningElement {
    @track data = [];
    recordId;
    recordPageUrl;
    wiredActivities;

    @wire(getRecords)
    wiredclass({error,data}){
      // this.wiredActivities = value;
      // const { data, error } = value;
      if (data) {
        // let lstdata = JSON.parse(JSON.stringify(data));
        console.log("data:" +data);
          this.data = data;
          this.error = undefined;
      } else if (error) {
          this.error = error;
          this.data = undefined;
      }
    }
}

A: Use lightning-avatar to get the desired effect.
Here's an update for your code:
<lightning-tile label='' type="media" variant="Narrow">
  <lightning-avatar variant="circle" src={item.AvatarUrl__c}></lightning-avatar>
</lightning-tile>

You may need to remove additional surrounding markup or make other tweaks, but this is the intended design pattern of making avatar images that are rounded.
Another tip: You can use lightning-carousel to create a list of images to display in a Salesforce branded way.


text:
Q: Sharing an SSIS Package between multiple projects I've run into a scenario at a client where we have a single generic ssis package that needs to be used by multiple SSIS projects. Normally, we would copy the SSIS package in question and add it to each of the projects that need it. The trouble is that as this generic packages gets developed, the changes need to be added to all of the SSIS projects that use this generic package.
The ideal situation would be to put the package in a DLL and load that DLL to all of the projects so that we could just update the DLL version in the SSIS projects, but I haven't found a way for SSIS to interface with a DLL.
An alternative would be to combine all of these projects into a single folder with different dtproj files for each project, but this is not an ideal solution since we will have multiple developers making changes on these packages and it will increase the number of merge conflicts between otherwise unrelated projects.
Anyone have a suggestion here?

A: Could you use an EXE instead of a DLL? You could then use an Execute Process Task.

A: Ended up going the route where I would either deploy a project as packages and external reference these packages in my project, or to keep the common project and run the packages using a sql script. Details here for anyone else interested.


text:
Q: Send large string to controller using ajax post I'm working on a ASP.NET MVC application, in which I need to send data stored in sessionStorage to a Controller. This storage has a key-value pair, in which the key is 'confirmed'. The value is an array with numbers, like [1,2,3,4,5].
I need to send this array to my controller, and everything works fine, except when this array is too long. I've tried changing the config with:
 <appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="1000000" />
 </appSettings>

and
<system.web.extensions>
    <scripting>
         <webServices>
             <jsonSerialization maxJsonLength="1000000" />
         </webServices>
    </scripting>
</system.web.extensions>

but nothing seems to work. It only works fine when the array is not so long.
Here's my code:
Script:
$(".enviar").click(function () {
        getSelectedItems();

        var seleccion = sessionStorage.confirmed;

        $.ajax({
            url: "/Controller/Action",
            type: "POST",
            //data: { confirm: JSON.stringify(seleccion) },
            data: JSON.stringify({ confirm: seleccion }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (returndata) {
                window.location = "@Url.Action("SomeAction","Controller")";
            },
            error: function (returndata) {
                window.location.href = "@Url.Action("AnotherAction","Controller")";
            }
        });

        //sessionStorage.clear();
    });

Controller:
[HttpPost]
    public ActionResult Action(string confirm)
    {
        if (!String.IsNullOrEmpty(confirm))
        {
            confirm = confirm.Substring(1, confirm.Length - 2);
            var confirmadas = confirm.Split(',');

            foreach (var id in confirmadas)
            {
                //change things in DB
            }

            return Json(new { ok = true, newurl = Url.Action("SomeAction", "Controller") });

        }
        return Json(new { ok = false, newurl = Url.Action("SomeAction", "Controller") });
    }

Please help, I've tried nearly everything and it works sometimes, but other times it doesn't.
Thank you.

A: 1.join the array to a string :
var str=seleccion .join(",");

2.just pass it to the data object
data: { confirm: str}


text:
Q: Mail not displaying message body content The Mail app on my Mac stopped displaying message body once the message is opened.
I can still see the message body in the message preview in each mailbox, but when I click (or double click) on a specific message, the message body is blank in the new window.

This happened to me a while ago, some time after updating to El Capitan. It affects all my email accounts on my Mac, Mail works properly on my iPhone. I don't remember changing any settings.
How to resolve it?

A: Rebuild the Mailbox
Try rebuilding the affected mailbox:

*

*Select the Inbox or affected mailbox.

*Select Mail.app > Mailbox (menu) > Rebuild
Rebuilding the mailbox will cause Mail.app to read all the messages again from the server. Rebuilding often fixes problems and restores missing or malformed messages.
From Apple's support document Mail: Rebuild mailboxes:

You may need to rebuild a mailbox to update the list of messages it contains. For example, if messages appear to be missing or garbled, or if you can't find all relevant messages when you search using the Entire Message search option.


text:
Q: Does Android have IsHitTestVisible like WPF? Does Android have IsHitTestVisible (The property which make elements not hittable by mouse or touch) like WPF?
http://msdn.microsoft.com/library/windows/apps/system.windows.uielement.ishittestvisible(v=vs.105).aspx


text:
Q: In bash, how can I get a URL from a markup file without using regex lookarounds? I want to grep the URL out of a .asx file. The file would normally look like this.
<ASX VERSION="3.0">
<ENTRY>
<TITLE>Blah Blah</TITLE>
<AUTHOR>Someone</AUTHOR>
<COPYRIGHT>(C)2014 Someone Else</COPYRIGHT>
<REF HREF="mms://www.example.com/video/FilmName/FilmName.wmv"/>
</ENTRY>
</ASX>

I want to get the URL without the quotes, and stripping off the mms://
I came up with a regex that uses lookarounds that does this successfully:
((?<=\/\/).*?).(?=\")

but of course I can't use this with grep. So what is another approach that would be flexible to capture whatever comes between the mms:// and the " that I could put into a grep -o command?

A:
but of course I can't use this with grep.

Why not? Modern grep versions supports -P switch for PCRE regex support.
Try this:
grep -oP '((?<=//).*?).(?=")' file
www.example.com/video/FilmName/FilmName.wmv

A: Like this:
awk -F '[:"]' '/REF HREF/ {print substr($3,3)}' file
www.example.com/video/FilmName/FilmName.wmv

A: With BASH, you can use the left/right pattern matching:
url='<REF HREF="mms://www.example.com/video/FilmName/FilmName.wmv"/>'
url=${url#<REF HREF=\"}
url=${url%\"/>}
echo "URL is '$url'"   # Prints URL is 'mms://www.example.com/video/FilmName/FilmName.wmv'

${VAR#pattern} strips off of $VAR the shortest left hand side glob that matches pattern. ${VAR##pattern}strips off of $var the largest left hand side glob that matches pattern. And, ${VAR%pattern} and ${VAR%pattern} do the same for the right hand side of $VAR.
An easy way to remember is that # is to the left of % on the keyboard. David Korn taught me that.

A: Solution for OSX users, where grep (as of OSX 10.9) doesn't support -P and look-arounds are therefore not an option:
egrep -o '"[a-z]+://[^"]+' file | cut -d '/' -f 3-


text:
Q: How can you show multiple alert dialogs, one after the other, in SwiftUI? The following code shows a "Delete file" button. When the user presses it, a confirmation alert dialog appears. When the user presses "Delete" on that first dialog, I want to show a second alert dialog confirming that the file has been deleted. However, it never shows up, even though debugging the code confirmed that the second "return Alert..." statement is actually being executed as expected. Is there a way to make the second alert show up too?
import SwiftUI

enum alertShownType {
    case alertNone, alertDeleteFile,alertFileDeleted
}

struct ContentView: View {

    @State var showingAlert = false
    @State var alertShown: alertShownType = alertShownType.alertNone

    var body: some View {
        Button(action: {
            self.alertShown = alertShownType.alertDeleteFile
            self.showingAlert = true
        })
        {
            Text("Delete file")
        }.padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing:0))
        .alert(isPresented: $showingAlert, content: {
            if (alertShown == alertShownType.alertDeleteFile)
            {
                return Alert(title: Text("Delete file"),
                      message: Text("Are you sure?"),
                      primaryButton: .destructive(Text("Delete")) {

                        // Delete the file

                        ....

                        // Show the next alert
                        alertShown = alertShownType.alertFileDeleted
                        showingAlert = true
                      },
                      secondaryButton: .cancel())
            }
            else // alertFileDeleted
            {
                return Alert(title: Text("File deleted"), message:
                            Text("Done!"),
                      dismissButton: .default(Text("OK")))
            }
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: You just need
public func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert)

Not required @State var showingAlert = false flag.
Setup you code like this
enum alertShownType : Identifiable {
    case alertNone,
    alertDeleteFile,
    alertFileDeleted

    var id : Int { get {
        hashValue
    }}
}

struct ContentViewAlerts: View {

    @State var alertShown: alertShownType?

    var body: some View {
        Button(action: {
            self.alertShown = alertShownType.alertDeleteFile
        })
        {
            Text("Delete file")
        }.padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing:0))
        .alert(item: $alertShown, content: { alertType in
            if (alertShown == alertShownType.alertDeleteFile)
            {
                return Alert(title: Text("Delete file"),
                             message: Text("Are you sure?"),
                             primaryButton: .destructive(Text("Delete")) {

                                // Delete the file

                                //                                ....

                                // Show the next alert
                                alertShown = alertShownType.alertFileDeleted
                             },
                             secondaryButton: .cancel())
            }
            else // alertFileDeleted
            {
                return Alert(title: Text("File deleted"), message:
                                Text("Done!"),
                             dismissButton: .default(Text("OK")))
            }
        })
    }
}


text:
Q: Extra double-quote character when C/P'ing out of Excel Stackoverflow folk!
I am having a funny double-quote issue with Excel.  I am attempting to generate some XML code in a cell that I then copy/paste into a plain-text editor to save (in this case, Notepad).
So, these work as expected:
="hello ""world"", folks!"
and
="hello "&CHAR(34)&"world"&CHAR(34)&", folks!"
each output hello "world", folks! as expected, and copy/paste into Notepad just fine.
However, as soon as I add a line break, as in the following two examples:
="hello ""world"", folks!"&CHAR(13)
or
="hello "&CHAR(34)&"world"&CHAR(34)&", folks!"&CHAR(13)
The output looks fine in Excel, but upon copy/paste into Notepad, I get a problematic result
"hello ""world"", folks!"
I obviously can't have random extra double-quotes floating around in my final XML, but I can't see a way to get my output without them.  Does anyone have any ideas?
Thanks in advance!


text:
Q: How to control when UIView should display updates I have a UIButton with an image as a background.
Because of the way i've structured the flows in my program, there's a certain moment when I have to update a couple of properties sequentially (including the background image) which causes the button to blink for a millisecond.
I want to get rid of that blinking of course, and that's the part that's bugging my brain since a couple of days:
I don't know how to prevent these updates from displaying until I'm ready to display them.
Ideally I'd like to do something like:

// the view "freezes" in its current state
[UIView stopDisplayingUpdates];

// many updates happen here
// without being displayed

// now everything is ready and the view should be repainted
[UIView refreshDisplay];


text:
Q: How to let users backup their posts to Google drive from Rails app? Is it possible to let individual users backup their posts to their google drive from a Rails app?
Is there anyone who has done something like this.
User should be able to backup their posts at an interval of their choice(daily, weekly, etc). And also can restore their backups from the Rails app itself, in case of data loss.

A: Yes, it is possible.
Define "something like this". Do you mean saved something to Google Drive from a rails app? Sure, there's a gem for that. Do you mean saved posts to Google Drive? If so, that's not so different than saving anything else to Google Drive. You just need to serialize the records into a document then upload.
For automated backup look into background and cron jobs. If during load to Google Drive you've serialized the records effectively, restore should be relatively trivial.


text:
Q: How to make VBA code to loop via multiple sheets and copy selected (6) cells How to make VBA code to loop via multiple sheets and copy selected (6) cells, and pasted into summary excel sheet with heading format cells made via the VBA code, including sheets numbers, the summary sheet is created via the code ..

A: Surely you can use the record button to record the macro doing exactly that, after which look at code and you can neaten if needed. There should be no problem doing this at all!
Please review below link.
http://office.microsoft.com/en-gb/excel-help/record-and-use-excel-macros-HA001054837.aspx


text:
Q: Chat: Wikipedia images In chat, when you post a link ending in .gif, the system tries to import the image. This doesn't work for Wikipedia links like File:Linguistic_map_Southwestern_Europe.gif.
Solution: Wikipedia links which end in .gif but have File: in the right place should have a special import method.

A: If you want the image to be displayed, link to the image (http://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Linguistic_map_Southwestern_Europe.gif/800px-Linguistic_map_Southwestern_Europe.gif) and not to some page that contains the image.


text:
Q: Integrating Amazon & eBay orders into Woocommerce I have been racking my head for the last couple of days and can't seem to think how this would work. I am trying to integrate our eBay and Amazon store to Woocommerce to send any eBay and Amazon orders directly into Woocommerce.
I am trying not to use any third party products to do this.
Can anyone help me or give me any pointers?

A: If you want full integration (products, stock, orders etc.) of woocommerce and ebay amazon marketplaces, I don't think there is "really" no free solution out there. There are two plugins (one for each marketplace): WP-Lister for eBay comes in free and pro(paid) versions, and WP-Lister Pro for Amazon only paid version, but I have not tried either of them.
Instead, I opted for CODISTO, recommended by woocommerce but it is a SAAS, costing around $50 per month. So far it looks good. I will test it out further within the 1 month trial, and post the results here if anyone still interested.

A: There is no such option available right now.
The API for the orders is available but for that, you will need an expert developer to manage all this.
If you want we can do this for you and help you out in overcoming from this issue.
Thanks


text:
Q: Turning off the camera in the OnNavigatedFrom() method in WP8 I want to ensure that when the user navigates away from a particular page, the camera is disposed of.
To turn on the camera I make a call to await AudioVideoCaptureDevice.OpenAsync(). If however the OnNavigatedFrom() method is called before the OpenAsync() method finishes, I have no way to dispose of the camera, and it will remain turned on.
What is the correct way to tackle this problem?

A: From here: https://github.com/slodge/BallControl/blob/master/Cirrious.Sphero.WorkBench/Cirrious.Sphero.WorkBench.UI.WindowsPhone/Views/SpheroView.xaml.cs
private AudioVideoCaptureDevice _cam;
...
     protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            _isNavigatingFrom = true;
            if (CameraIsRecording)
            {
/*
var task = DoStopRecording();
task.Start();
task.Wait();
*/
            }
            TheMoveJoystick.StopJoystick();
            ViewModel.AccelMovement.EnsureAccelerometerIsOnCommand.Execute(false);
            ViewModel.Speech.EnsureSpeechIsOn.Execute(false);
            ViewModel.AccelMovement.PropertyChanged -= AccelMovementOnPropertyChanged;
            _hackTimer.Stop();
            if (_cam != null)
            {
                _cam.Dispose();
                _cam = null;
            }
            _isNavigatingFrom = false;
            base.OnNavigatingFrom(e);
        }

A: I would use a singleton, or an static manager class for that kind of operations, so you can call that class to initialize the camera, and to close it whenever you want. Then there you can keep a flag on that class that you use to say if the camera was cancelled, or something like that, so that way it can check after the async method, if the camera was cancelled.
I hope this helps.


text:
Q: Python Pyinstaller GUI Tkinter Selenium I did not know how to create an executable python program before I asked here. Thankfully I received a fast answer and was able to convert my script to an executable program. The executable works perfect but only on my computer.
These are the two error's I am receiving, I feel like I need to modify the script in order to locate the chrome driver I am not sure where Pyinstaller saved everything.
Exception in Tkinter callback
Traceback (most recent call last):
File "site-packages\selenium\webdriver\common\service.py", line 76, in start
File "subprocess.py", line 775, in __init__
File "subprocess.py", line 1178, in _execute_child
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "tkinter\__init__.py", line 1705, in __call__
File "MarijuanaDoctors.py", line 25, in search
File "site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
File "site-packages\selenium\webdriver\common\service.py", line 83, in start
selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
executable needs to be in PATH. Please see
https://sites.google.com/a/chromium.org/chromedriver/home

A: You can bundle your "chromedriver.exe" along with your script using Pyinstaller like this:
pyinstaller --add-binary="localpathtochromedriver;." myscript.py

This will copy the "chromedriver.exe" file in the same folder as your main .exe(Or in case of single file option of pyinstaller, this fill will be extracted in temp folder while using exe program).
In your script you can check if you are running the script normally or from bundled(exe file) mode, and choose path to chromedriver.exe accordingly.(This change in script can be common for Single file/folder bundle option of pyinstaller)
import sys
if getattr(sys, 'frozen', False ):
    #Running from exe, so the path to exe is saved in sys._MEIPASS
    chrome_driver = os.path.join(sys._MEIPASS, "chromedriver.exe")
else:
    chrome_driver = 'localpathtochromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_driver)

You can read about this in docs here.
Limitation:
The user of your .exe should have Chrome installed on their system and Chrome version should work with the chromedriver which is bundled.


text:
Q: Can I create a new generation EC2 instance from an old generation AMI? I need to upgrade my EC2 hosts to new memory optimized ones.  When I try to create a new generation type instance from an old AMI the new generation types are X'd out, ie unavailable.
Am I missing something?


text:
Q: Is it possible to stop using async and await where required I'm implementing code from a developer that are using async functions.
Example:
public async Task<string> GetDataAsync(string jsonString = "")
{
    string url = $"{this.url}";

    using (HttpClient httpClient = new HttpClient())
    {
        using (StringContent body = new StringContent(jsonString, Encoding.UTF8, "application/json"))
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessToken);

            using (HttpResponseMessage response = await httpClient.PostAsync(url, body))
            {
                switch (response.IsSuccessStatusCode)
                {
                    case true:

                        return await response.Content.ReadAsStringAsync();

                    default:

                        throw new Exception($"Error calling url: {url}. HTTP status: {response.StatusCode}");

                }
            }
        }
    }
}

And I don't need, nor do I want, to call anything asynchronously. But the problem is that async functions is bubbling all the way up through my functions and so I can't just stop using it, and since HttpClient doesn't have a Post() function to use instead of PostAnync() then I feel stuck in this asynchronous cage.
Is there a trick or whatever to call an async function normally, stopping threading from bubbling up through all parent functions?
Or is the only solution to find a package without async functions?

A: The short answer is - no, there's no generic way to make a synchronous function out of a a task-based asynchronous one.
The problem is that you don't know how it is implemented internally. Say, the asynchronous function is implemented using async and it's running (partially) in the context of the primary thread. Then, if the caller code is trying to block the primary thread by a blocking call, then the async function is blocked, too, which is causing a deadlock.
But, in your particular case you can try to create a new task, call the async function from that task and take its result. There are good chances that it will work, but no guarantee (as mentioned above).
The code would look like this:
using (var response = Task.Run(() => httpClient.PostAsync(url, body).Result).Result)
{
    ...
}


text:
Q: ios8 Hide/Show Navigation Bar and Toolbar iOS 8.2 - iPad or iPhone.
I'm creating a basic Master-Detail app in Xcode to test the UISplitViewController.  I'm selecting my detail-navigation controller from the storyboard and selecting that I want to show the toolbar. This appears in the storyboard.
I'm also selecting Hide Bars on Tap in the properties window (as shown).

However, when I run the app, only my Navigation bar appears/disappears. The toolbar remains static at the bottom of the screen. Even if I set this in code, my toolbar is still static.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let splitViewController = self.window!.rootViewController as UISplitViewController
    let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
    navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
    splitViewController.delegate = self

    navigationController.hidesBarsOnTap = true;
    return true
}

Yet the documentation suggests both bars should be hidden/shown on tap.

Discussion When the value of this property is YES, the navigation
  controller toggles the hiding and showing of its navigation bar and
  toolbar in response to an otherwise unhandled tap in the content area.
  The default value of this property is NO.

Does this property actually work on the toolbar? If so, is there anything else I should be doing? Thanks

A: The toolbar will only hide if you have put a bar button item inside.


text:
Q: "Projection of metric" vs. "projection of curvatures" Suppose we have a submanifold $M^n$ which is embedded in manifold $M^{n+2}$ and $g_{\mu \nu}$ denotes the metric of $M^{n+2}$. We know that the induced metric on the submanifold is defined by
\begin{equation} g_{ab}=\partial_a X^\mu \partial_b X^\nu g_{\mu\nu} \end{equation}
which in my opinion can be imagined as a projection of $g_{\mu\nu}$ onto the submanifold. Now by this metric and also using a normal vector on $M^n$ , we can calculate the intrinsic and extrinsic curvatures.
On the other hand, suppose we first find intrinsic curvature of $M^{n+2}$ and then by constructing
\begin{equation}
h_{\mu\nu}=g_{\mu\nu}-n_\mu \cdot n_\nu
\end{equation}
where $n_\mu$ is the normal vector, we project it onto the submanifold.
And the third case is we know the metric of $M^n$, which we call it $G_{ab}$, and by using it find the curvatures of $M^n$.
Now the question is whether the results of these three procedures are the same or not. By the way, am I right that $G_{a b}$ is different from $g_{ab}$?


text:
Q: Why training error varies with value of K in KNN? Why does the training error increases with value of K in KNN algorithm?
For k=1, training error is zero because if we take a point and determine 1st nearest neighbour it will be same point in the training dataset so error is zero.
The same concept should be true for k=2, 3.... so on.
Then how come training error increases with value of K

A: For k=1, the algorithm will choose a training sample which is closest to the test sample, since test sample is there in the training sample it will choose itself, and error will be zero, also overfitted model.
Whereas when k = 2, k=3 or greater it will look for those many numbers of neighbors which can belong to different groups, and hence error rate increases.


text:
Q: Customize Amcharts v4 tooltip border color I've applied code like this:
var series = chart.series.push(new am4charts.LineSeries());
series.tooltip.getFillFromObject = false;
series.tooltip.background.fill = am4core.color("#fff");
series.tooltip.border.fill = am4core.color("#000");
series.tooltip.label.fill = am4core.color("#000");
series.tooltipText = "{date.formatDate('d MMM, yyyy')}: [bold]{value}";
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";

But somehow tooltip is not loaded with border color.

A: In amcharts the field for the border color is stroke. You can set it eiter on the tooltip itself, on the tooltip.background or on the tooltip.label. For example like this:
series.tooltip.background.stroke = am4core.color("#000");

You also can change the border width using strokeWidth:
series.tooltip.background.strokeWidth = 2;

Here is a working code pen.


text:
Q: index.cache.field.max_size unable to limit field data cache in elasticsearch I am trying to limit the field caching(resident) by setting index.cache.field.max_size: NUMBER in config/elasticsearch.yml file. I have around 1 million records, and a faceting operation is performed on 7 fields(all of them contain lots of text data), to construct a "word cloud".
curl -X POST 'http://localhost:9200/monitoring/mention_reports/_search?&pretty=true' -d '
{
  "size":"0",

  "query": {
    "filtered":{
      "query":{
        "text": {
          "positive_keyword": {
            "query": "quora"
          }
        }
      },
      "filter":{

                    . . .

      }
    }
  },

  "facets": {
    "tagcloud": {
      "terms": {
        "fields":["field1","field2","field3","field4","field5","field6","field7"],
        "size":"300"
      }
    }
  }
}
'

The heap memory(15gb allocated) gets eaten up all the time irrespective of whatever value(1000 or 100000) is specified for index.cache.field.max_size. What am I doing wrong?
Also is there a better way to build a word cloud, instead of performing faceting on such huge amount of text data?
Mapping:
 curl -XPOST http://localhost:9200/monitoring/ -d '
{
  "settings":{
    "index":{
      "number_of_shards":5,
      "number_of_replicas":1
    },
    "analysis":{
      "filter":{
        "myCustomShingle":{
          "type":"shingle",
          "max_shingle_size":3,
          "output_unigrams":true
        },
        "myCustomStop":{
          "type":"stop",
          "stopwords":["a","about","abov ... ]
        }
      },
      "analyzer":{
        "myAnalyzer":{
          "type":"custom",
          "tokenizer":"standard",
          "filter":[
            "lowercase",
            "myCustomShingle",
            "stop",
            "myCustomStop"
          ]
        }
      }
    }
  },
  "mappings":{
    "mention_reports":{
      "_source":{
        "enabled":true
      },
      "_all":{
        "enabled":false
      },
      "index.query.default_field":"post_message",
      "properties":{
      "id":{
        "type":"string",
        "index":"not_analyzed",
        "include_in_all" : "false",
        "null_value" : "null"
      },
      "creation_time":{
        "type":"date"
      },
      "field1":{
        "type":"string",
        "analyzer":"standard",
        "include_in_all":"false",
        "null_value":0
      },
      "field2":{
        "type":"string",
        "index":"not_analyzed",
        "include_in_all":"false",
        "null_value":"null"
      },

            . . .

        "field7":{
          "type":"string",
          "analyzer":"myAnalyzer",
          "term_vector":"with_positions_offsets",
          "null_value" : "null"
        }

      }
    }
  }
}
'


text:
Q: cloudformation output section validation error I'm creating an instance with Elastic IP and the security group.Everything works fine until I add the outputs section.
I'm getting invalid templateBody error after adding the outputs section to the existing template.
The template works fine without the Outputs section.
Below is the relevant code:
    "Resources": {
        "InstanceProfile" : {
            "Type" : "AWS::IAM::InstanceProfile",
            "Properties" : {
              "Path" : "/",
              "Roles" : ["TEST_Role"]
            }
          },
        "Instance": {
            "Properties": {
                "IamInstanceProfile" : {"Ref" : "InstanceProfile"},
                "BlockDeviceMappings": [
                    {
                        "DeviceName": "/dev/sda1",
                        "Ebs": {
                            "VolumeSize": {
                                "Ref": "EBSVolumeSize"
                            }
                        }
                    }
                ],
                "ImageId": {
                    "Ref": "AMI"
                },
                "InstanceType": {
                    "Ref": "InstanceType"
                },
                "KeyName": {
                    "Ref": "KeyName"
                },
                "SecurityGroupIds": [
                    {
                        "Ref": "SecurityGroup"
                    }
                ],
                "SubnetId": {
                    "Ref": "Subnet"
                }
            },
            "Type": "AWS::EC2::Instance"
            },
        "EIPAddress": {
            "Type": "AWS::EC2::EIP"
        },
        "IPAssoc": {
            "Type": "AWS::EC2::EIPAssociation",
            "Properties": {
                "InstanceId": {
                    "Ref": "Instance"
                },
                "EIP": {
                    "Ref": "EIPAddress"
                }
            }
        },
    },
    "Outputs" : {
        "PublicIP": {
            "Value": { "Fn::GetAtt": [ "Instance", "PublicIp"]},
            "Description": "Public IP of the machine"
        }
    }

}

A: I think the reason is that you have extra comma:
        }, # <---- here
    },
    "Outputs" : {
        "PublicIP": {
            "Value": { "Fn::GetAtt": [ "Instance", "PublicIp"]},
            "Description": "Public IP of the machine"
        }
    }

Also, if your instance is not public, the template will fail, because private instances don't have PublicIp, thus you can't output it.
Update on the full template (tested in us-east-1 and default VPC):


text:
Q: Update form Cakephp 3 I am currently working on a project using cakephp 3.
I have a form to add clients which works using this in my controller :
    public function add(){

        $clients = $this->Clients->newEntity();
        if($this->request->is('post')){
            $clients = $this->Clients->patchEntity($clients, $this->request->data);
            if($this->Clients->save($clients)){
                $this->Flash->success(__('Client has been created.'));
                return $this->redirect(['controller'=>'Clients','action'=>'index']);
            }
            $this->Flash->error(__('Client hasnt been created.'));
        }
        $this->set('clients',$clients);

    }

Then I want to have the possibility to modify one of my client.
I have a table of clients and when I click on of them, I have a modify button coming (jQuery).
Then I'm on my modify page. I did some test with the doc from cake but it seems I don't understand how it works and what tools should I use.
For the moment, I have this on my Controller:
public function modify($id = null){
            if(empty($id)){
                throw new NotFoundException;
            }
            $clients = $this->Clients->get($id);
            /* there should be the modify code */
            $this->set('clients', $clients);

        }

I don't really know what to use as I said...  Any help pls?

A: The code for editing a record is quite straight forward:
public function modify($id = null){
        if(empty($id)){
            throw new NotFoundException;
        }
        $client = $this->Clients->get($id);
        if ($this->request->is(['post', 'put']) {
            $client = $this->Clients->patchEntity($client, $this->request->data);
            if ($this->Clients->save($client)) {
                return $this->redirect($someURL);
            }
        }
        $this->set('client', $client);

}


text:
Q: When do queries with very large "WHERE x IN" clauses perform badly? I have always been under the impression that queries with large WHERE x IN clauses perform  badly.
For example, let's say I have the following table
psql> \d examples

| Column  | Type                  | Modifiers
| id      | integer               | not null default nextval('id_seq'::regclass)
| flag    | boolean               | not null
| date    | timestamp             | not null
| comment | character varying(16) | not null
Indexes:
   "example_pkey" PRIMARY KEY, btree (id)

If I query this table using a WHERE id IN clause with 100k ids it actually returns fairly quickly (there are 100ks rows in the table):
EXPLAIN ANALYSE SELECT * FROM examples WHERE id IN (1, 2, ...., 100000);

Index Scan using examples_pkey on examples  (cost=0.15..15012.60 rows=610 width=104) (actual time=18.380..18.380 rows=0 loops=1)
   Index Cond: (id = ANY ('{1, 2, ... 100000}'::integer[]))
 Planning time: 45.832 ms
 Execution time: 42.708 ms

The planner has rewritten the query to use id = ANY with my list of IDs so I assume this is just equivalent or the planner knows that's faster.
I have had other queries before where replacing large WHERE IN clauses with a subquery has greatly improved the speed of the query. My query here is very simple, so the question is:
Is it true that queries with large WHERE IN clauses actually perform badly? If so in which cases is that the case (assuming columns are indexes etc).

A: The parser transforms IN expressions with more than one element in the list into =ANY expressions.
If there is a B-tree index on the column, it can always be used.
The only performance problem I can imagine is that the optimizer may estimate the number of result rows wrongly and choose a sequential scan when an index scan would actually be faster.
Experiments show that the optimizer estimates one result row per list entry for unique columns, with a maximum of the number of rows in the table. This is a reasonable estimate, but if there are many elements in the list that do not match or there are duplicates, the estimate can easily be too high.


text:
Q: Where is /etc/inittab in Ubuntu?
Possible Duplicate:
Where is the /etc/inittab file or how to set the default runlevel

I have Ubuntu LTS 12.04 32 bit operating system on my laptop. But I could not find /etc/inittab.  Where is it moved? Do we have something new instead?

A: There is no such thing in Debian/Ubuntu.
All major distribution is moving away from SysV init and adopting systemd. Ubuntu now uses upstart.


text:
Q: dropping all the columns after a matching value without using the index I have the below data frame

and i have a variable as ID = 1052107168068132864
How I can filter all the values to drop it after that column and can get the result like below. In a way i want to drop all the column after that Id including it as well.

and then update the value of ID as 1052121282324692992 as the current value.
i want to repeat this in a loop so that every time i get a new data frame the same operation will keep going and if that is the top value then nothing should happen.
I am having two solutions but they only works when index are in serial way :-
df.iloc[:df[df.ID == '1052121282324692992'].index.item()]

or

idx = (df['ID'] == ID).idxmax()
new_df = df.iloc[:idx, :]


text:
Q: Fix point iteration, rate of convergence Determine whether iterations based on the following formulae converge toward the fixed point $x=\sqrt a$, $a>0$ and for each iteration that converges , find the rate of convergence (i.e. linear, quadratic etc.)
(a) $\phi(x) = {a\over x}$
(b) $\phi(x) = 2x-{a\over x}$
(c) $\phi(x) = {1\over2}\Big( x+{a\over x} \Big)$

When I look at the first one, I can see $x_1=\phi(x_0)={a\over x_0}$, and $x_2=\phi(x_1)= {a\over{a\over x_0}}=x_0$, so it is not convergence, but I am not sure if I am right. and (b), (c), seems i should use the formula $$\lim_{x\to \infty}{|\phi(x_{n+1})-\sqrt a |\over |\phi(x_n)-\sqrt a |^\alpha}=\lambda$$
but i dont know how to do it and what exactly is the rate of convergence.


text:
Q: WPF TextBlock binding deactivate & detach I have started seeing an unusual issue with some of the binding on my textblocks:
XAML
  <TextBlock Text="{Binding PartCount,FallbackValue=1, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}" Foreground="Black" Margin="-3"/>

I know for sure that my binding path resolution is correct because if I change this block to a label with content instead of text then it works just fine.
I have the diagnostic logger enabled for the binding and I can see it initialise correctly and set the initial value from its source:
DEBUG LOG

System.Windows.Data Warning: 67 : BindingExpression (hash=40999308):
Resolving source  (last chance) System.Windows.Data Warning: 70 :
BindingExpression (hash=40999308): Found data context element:
TextBlock (hash=5477191) (OK) System.Windows.Data Warning: 78 :
BindingExpression (hash=40999308): Activate with root item LoadStack
(hash=22395825) System.Windows.Data Warning: 107 : BindingExpression
(hash=40999308):   At level 0 using cached accessor for
LoadStack.PartCount: RuntimePropertyInfo(PartCount)
System.Windows.Data Warning: 104 : BindingExpression (hash=40999308):
Replace item at level 0 with LoadStack (hash=22395825), using accessor
RuntimePropertyInfo(PartCount) System.Windows.Data Warning: 101 :
BindingExpression (hash=40999308): GetValue at level 0 from LoadStack
(hash=22395825) using RuntimePropertyInfo(PartCount): 'Infinity'
System.Windows.Data Warning: 80 : BindingExpression (hash=40999308):
TransferValue - got raw value 'Infinity' System.Windows.Data Warning:
84 : BindingExpression (hash=40999308): TransferValue - implicit
converter produced '∞' System.Windows.Data Warning: 89 :
BindingExpression (hash=40999308): TransferValue - using final value
'∞'

But then, when I navigate to the window that shows this text box I get this:
DEBUG LOG

System.Windows.Data Warning: 79 : BindingExpression (hash=40999308):
Deactivate System.Windows.Data Warning: 103 : BindingExpression
(hash=40999308): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 63 : BindingExpression (hash=40999308):
Detach

So after this point the visual element does not update, but I do still get information in the log when the source changes like so:
DEBUG LOG

System.Windows.Data Warning: 95 : BindingExpression (hash=53188122):
Got PropertyChanged event from LoadStack (hash=22395825)
System.Windows.Data Warning: 101 : BindingExpression (hash=53188122):
GetValue at level 0 from LoadStack (hash=22395825) using
RuntimePropertyInfo(PartCount): '50' System.Windows.Data Warning: 80 :
BindingExpression (hash=53188122): TransferValue - got raw value '50'
System.Windows.Data Warning: 84 : BindingExpression (hash=53188122):
TransferValue - implicit converter produced '50' System.Windows.Data
Warning: 89 : BindingExpression (hash=53188122): TransferValue - using
final value '50'

So something is causing that "deactivate" & "detach" which means that it no longer updates the view. I have checked that the data context is consistent, which it is.
Is there anything that can cause the binding to respond in this way?

A: Detachment behavior usually occurs when a value is set outside of the data binding.
The way to go is to check if you're setting TextBlock.Text somewhere else (e.g. in the code behind or in your XAML).
Another possibility is that your viewmodel instance gets replaced by another one.


text:
Q: Building Android OS using Cygwin (Win7) I am trying to build the latest version of Android OS from source. I'm on Windows 7 x64, and am using Cygwin to do this.
I get the following errors:
$ make -j8
============================================
PLATFORM_VERSION_CODENAME=AOSP
PLATFORM_VERSION=3.1.4.1.5.9.2.6.5
TARGET_PRODUCT=full
TARGET_BUILD_VARIANT=eng
TARGET_SIMULATOR=false
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a
HOST_ARCH=x86
HOST_OS=windows
HOST_BUILD_TYPE=release
BUILD_ID=OPENMASTER
============================================
libpng: Ignoring gcc flag -fvisibility=hidden  on Cygwin
find: `frameworks/base/frameworks/base/docs/html': No such file or directory
find: `out/target/common/docs/gen': No such file or directory
find: `frameworks/base/frameworks/base/docs/html': No such file or directory
find: `out/target/common/docs/gen': No such file or directory
find: `frameworks/base/frameworks/base/docs/html': No such file or directory
find: `out/target/common/docs/gen': No such file or directory
find: `frameworks/base/frameworks/base/docs/html': No such file or directory
find: `out/target/common/docs/gen': No such file or directory
find: `frameworks/base/frameworks/base/docs/html': No such file or directory
find: `out/target/common/docs/gen': No such file or directory
make: *** No rule to make target `/cygdrive/c/Program', needed by `out/target/common/docs/doc-comment-    check-timestamp'.  Stop.

It looks like it could be a path problem, maybe my Java path since this is in Program Files? My current path does not have any spaces.

A: Even if it is not supported to build AOSP under cygwin, the particular error here looks unrelated to that. It looks to me like you've got it somewhere under c:\program files. If you put it in a path without a space it will likely at least go further than this.

A: Googling for "frameworks/base/frameworks/base/docs/html" shows you're not the only one who's seen this.
According to this thread, it's a harmless warning. A response in this thread, by the same Android developer, seems to suggest a workaround to avoid the warning.
The first thread seems to be about building the SDK, rather than the OS itself. I'm not sure if it's equally harmless in building the OS.

A: You cannot build Android OS on Windows. The can do this only using Linux or Mac, because there  are some tools absent in Cygwin.

A: Windows is case insesitive, some files will appear as duplicate to Windows.
This will prevent you from building a Android system