text:
Q: Change Height of a Listview dynamicallyAndroid The format of my XML file is as following:
 LinearLayout

     ScrollView

         RelativeLayout

             LinearLayout

             <ListView
               android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="fill_parent"
               android:layout_margin="5dip"
               android:layout_weight="30" >
             </ListView>

             LinearLayout

Here is my BaseAdapter class
public class APIQuickCheckoutProductProvider extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;

public APIQuickCheckoutProductProvider(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    return data.size();
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.product_item, null);

    TextView brand = (TextView) vi.findViewById(R.id.brands);
    TextView quantity_name = (TextView) vi.findViewById(R.id.quantity_name);

    TextView price = (TextView) vi.findViewById(R.id.price);

    HashMap<String, String> product = new HashMap<String, String>();
    product = data.get(position);

    // Setting all values in listview
    brand.setText(product.get(APIQuickCheckout.KEY_BRAND));
    quantity_name.setText(product.get(APIQuickCheckout.KEY_QUANTITY_NAME));
    price.setText(product.get(APIQuickCheckout.KEY_PRICE));

    return vi;
}
}

Here is the main class where I set the adapter:
adapter = new APIQuickCheckoutProductProvider(APIQuickCheckout.this, productList);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();

And finally here is the each individual row which i set to the listview
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dip"
    android:layout_weight="7"
    android:weightSum="6" >

    <TextView
        android:id="@+id/brands"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="3" />

    <TextView
        android:id="@+id/quantity_name"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="3" />
  </LinearLayout>

  <LinearLayout
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dip"
    android:layout_weight="2"
    android:weightSum="6" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="3" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="3" />
   </LinearLayout>

 </LinearLayout>

However, when I am trying the above mentioned code it displays the first product, and I can see only the top of the second product.And I can see nothing from then and on. So, how can I change the height of the ListView dynamically when I add a new product? In order to display all of them.

A: import android.view.ViewGroup.LayoutParams;

 ListView mListView = (ListView)   findViewById(R.id.listviewid);
 LayoutParams list = (LayoutParams) mListView.getLayoutParams();
   list.height = set the height acc to you;//like int  200
   mListView.setLayoutParams(list);

A: Try this answer,
public static void setListViewHeightBasedOnChildren(final ListView listView) {
    listView.post(new Runnable() {
        @Override
        public void run() {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
            int listWidth = listView.getMeasuredWidth();
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(
                        View.MeasureSpec.makeMeasureSpec(listWidth, View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

                totalHeight += listItem.getMeasuredHeight();
                Log.d("listItemHeight" + listItem.getMeasuredHeight(), "___________");
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = (int) ((totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))));
            listView.setLayoutParams(params);
            listView.requestLayout();

        }
    });
   }

A: If you want to change the height of list view dynamically, you could use,
list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));

A: Its not recommended to use ListView inside of a ScrollView

A: You can use below method to set the height of listview programmatically:
<ListView
        android:id="@+id/lvMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        />

Method used for setting height of listview:
public static boolean setListViewHeightBasedOnItems(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter != null) {

            int numberOfItems = listAdapter.getCount();

            // Get total height of all items.
            int totalItemsHeight = 0;
            for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
                View item = listAdapter.getView(itemPos, null, listView);
                float px = 500 * (listView.getResources().getDisplayMetrics().density);
                item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                totalItemsHeight += item.getMeasuredHeight();
            }

            // Get total height of all item dividers.
            int totalDividersHeight = listView.getDividerHeight() *
                    (numberOfItems - 1);
            // Get padding
            int totalPadding = listView.getPaddingTop() + listView.getPaddingBottom();

            // Set list height.
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalItemsHeight + totalDividersHeight + totalPadding;
            listView.setLayoutParams(params);
            listView.requestLayout();
            return true;

        } else {
            return false;
        }

    }

Then set it like below code:
 MenuAdapter menuAdapter = new MenuAdapter(context, R.layout.menu_item);
            lvMenu.setAdapter(menuAdapter);
            setListViewHeightBasedOnItems(lvMenu);

A: public class Utility {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}

A:

 <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <ListView
                android:id="@+id/lv_premimum_upgrade"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/custom_margin"
                android:minHeight="48dp">
            </ListView>
        </LinearLayout>

</ScrollView>

int list_cell_size=188;    // cell_size is varible
ViewGroup.LayoutParams list;
list = (ViewGroup.LayoutParams) listView.getLayoutParams();
list.height = list_cell_size*response.size();  // response is list items size
listView.setLayoutParams(list);


text:
Q: How to get verbatimTextOutput inline with regular text in Shiny app? When running this simple app, I come across a problem where the - between the verbatimTextOutput for scores is not aligned properly with the output text boxes (or potentially vice versa).  I know that verbatimTextOutput includes the text in an HTML pre tag and when I inspect element I can see that it is allocating some sort of bottom margin to the text box output.  When I remove the margin for this pre tag using inspect element the text boxes line up perfectly with the -.  How can I make this happen as the default?
Essentially how can I go from this:
To this?
library(shiny)

A <- c(1,2,3,4,5,6,7)
B <- c(1,2,3,4,5,6,7)

uiMatchup <- fluidPage(
  fluidRow(
    column(3,
           selectInput(
             inputId = "Away",
             label = h3("Away Team"),
             choices = c(A, B)),
           align="center"),
    column(3,
           selectInput(
             inputId = "Home",
             label = h3("Home Team"),
             choices = c(A,B)
           ),
           align="center",
           offset=6)
  ),

  br(),

  fluidRow(
    column(5,
           verbatimTextOutput("Team1Score"),
           align="center"),
    column(2,
           h3("-"),
           align="center"),
    column(5,
           verbatimTextOutput("Team2Score"),
           align="center")
  )
)

serverMatchup <- function(input, output) {

  output$Team1Score <- renderPrint({

      return(cat(paste0(input$Away)))
    })

  output$Team2Score <- renderPrint({

    return(cat(paste0(input$Home)))
    })

}

shinyApp(ui = uiMatchup, server = serverMatchup)

A: I have finally answered my own question.  I simply created a renderText output that is just a dash and then created a tag for the Dash textOutput where I manually set the position of the dash to be horizontally and vertically aligned with the other inputs.
library(shiny)

A <- c(1,2,3,4,5,6,7)
B <- c(1,2,3,4,5,6,7)

uiMatchup <- fluidPage(
    fluidRow(
        column(3,
               selectInput(
                   inputId = "Away",
                   label = h3("Away Team"),
                   choices = c(A, B)),
               align="center"),
        column(3,
               selectInput(
                   inputId = "Home",
                   label = h3("Home Team"),
                   choices = c(A,B)
               ),
               align="center",
               offset=6)
    ),

    br(),

    fluidRow(
        column(5,
               verbatimTextOutput("Team1Score"),
               align="center"),
        column(2,
               textOutput("Dash"),
               align="center"),
        column(5,
               verbatimTextOutput("Team2Score"),
               align="center")
    ),
    tags$style(type='text/css', "#Dash { width:100%; margin-top:-10px; font-size: 40px;
                                 font-style: bold;}")
)

serverMatchup <- function(input, output) {

    output$Team1Score <- renderPrint({

        return(cat(paste0(input$Away)))
    })

    output$Team2Score <- renderPrint({

        return(cat(paste0(input$Home)))
    })

    output$Dash <- renderText({"-"
    })

}

shinyApp(ui = uiMatchup, server = serverMatchup)

redpajama_set_name: RedPajamaStackExchange


text:
Q: calculating differences between timestamps and storing in a dictionary I have a dictionary called times containing a datetime timestamp as the key and tuple as the value. Example formatting is as follows:
{datetime.datetime(2019, 11, 4, 20, 2): ('A', 'B'),
datetime.datetime(2019, 11, 4, 19, 59): ('C', 'D'),
datetime.datetime(2019, 11, 4, 19, 55): ('E', 'F'), …, }

I am trying to sort the timestamps in a list in ascending order, loop through the list to calculate the difference between consecutive timestamps, and then store the starting time in a new dictionary if the delta is greater than a 10 minute threshold (with the corresponding tuple as the value).
This is what I have for code so far. I believe I need to first store the difference between timestamps in the list time_with_breaks then use an if statement store deltas that are greater than the threshold in the dictionary but I'm not sure how to do this.
deltas = {} # store timestamp and seconds until next entry
time_with_breaks = [] # store timing information of breaks
# sorted list of time stamps (ascending order)
timelist = sorted(playlist_dict.keys(), reverse=False)
for i in timelist:

How can I do this? Thanks in advance for any help.

A: The following should work
# This will return an ordered list of the timestamps
times_sorted = list(sorted(playlist_dict.keys()))
time_with_breaks = []
# "zipping" the list with itself offset by 1 will give you an iterable
# of each timestamp and the next timestamp in the list
for time_1, time_2 in zip(times_sorted, times_sorted[1:]):
    # datetime - datetime results in a timedelta
    # 600 seconds is 10 minutes
    if (time_2 - time_1).seconds > 600:
        # Append the datetime where the next datetime in the list is more than
        # 10 minutes away
        time_with_breaks.append(time_1)


text:
Q: How to use pivot in SQL Server to make a table like this? So let's say I have a table like this

Code
Name
Budget

1111
ABC
1500

1111
DEF
2000

1111
QWE
3000

2222
ABC
1800

2222
DEF
1000

3333
QWE
1500

How can I display the results this way? I know you can use PIVOT but I don't understand how to build the sentence.

Code
ABC
DEF
QWE

1111
1500
2000
3000

2222
1800
1000
0

3333
0
0
1500

I tried using different PIVOT examples but couldn't get one structured the same way as my data
EDIT: There will be many more codes, and could also have many more names other than ABC, DEF & QWE

A: You can achieve that by using Pivot and dynamic query together:
DECLARE @cols AS NVARCHAR(MAX)

        ,@query AS NVARCHAR(MAX);

    SET @cols = STUFF((
                SELECT ',' + QUOTENAME(c.[Name])
                FROM (
                    SELECT DISTINCT [Name]
                    FROM Budget
                    ) c
                ORDER BY [Name]
                FOR XML PATH('')
                    ,TYPE
                ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

                SELECT @cols

                SET @query = N'SELECT *
from
(SELECT Code,Name,Budget FROM budget )
AS source
PIVOT
(
 sum(Budget)
  FOR [Name] IN ( '+@cols+')
)AS PivotTable
';

EXECUTE (@query)


text:
Q: Rails 4 scope models : only Parents who have Children I have a 2 models in Rails 4
 course.rb
 has_many :reviews

 review.rb
 belongs_to :course

What is the best way to scope only the courses which have been reviewed? Here are two ways:
 1. scope :with_reviews, -> { joins(:reviews).where(:reviews => { :id => !nil }) }

counter_cache: true in review.rb and
 2. scope :with_reviews, -> { where('reviews_count > ?', 0) }

Is there another better way to do so?
Thx

A: try this
Course.joins(:reviews).group('reviews.course_id').having('count(reviews.id) > 0')

A: scope :with_reviews, -> { joins(:reviews).select("DISTINCT courses.*")}


text:
Q: Converting floating point to fixed point In C++, what's the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)?
EDIT: For clarification, fixed-point values have two parts to them: an integer part and a fractional part.  The integer part can be represented by a signed or unsigned integer data type.  The fractional part is represented by an unsigned data integer data type.
Let's make an analogy with money for the sake of clarity.  The fractional part may represent cents -- a fractional part of a dollar.  The range of the 'cents' data type would be 0 to 99.  If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts.
I hope that clears things up.

A: **** Edit** : My first comment applies to before Kevin's edit,but I'll leave it here for posterity. Answers change so quickly here sometimes!
The problem with Kevin's approach is that with Fixed Point you are normally packing into a guaranteed word size (typically 32bits). Declaring the two parts separately leaves you to the whim of your compiler's structure packing. Yes you could force it, but it does not work for anything other than 16:16 representation.
KPexEA is closer to the mark by packing everything into int - although I would use "signed long" to try and be explicit on 32bits. Then you can use his approach for generating the fixed point value, and bit slicing do extract the component parts again. His suggestion also covers the 24:8 case.
( And everyone else who suggested just static_cast.....what were you thinking? ;) )

A: Here you go:
// A signed fixed-point 16:16 class
class FixedPoint_16_16
{
    short          intPart;
    unsigned short fracPart;

public:
    FixedPoint_16_16(double d)
    {
        *this = d; // calls operator=
    }

    FixedPoint_16_16& operator=(double d)
    {
        intPart = static_cast<short>(d);
        fracPart = static_cast<unsigned short>
                    (numeric_limits<unsigned short> + 1.0)*d);
        return *this;
    }

    // Other operators can be defined here
};

EDIT: Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out):
template <class BaseType, size_t FracDigits>
class fixed_point
{
    const static BaseType factor = 1 << FracDigits;

    BaseType data;

public:
    fixed_point(double d)
    {
        *this = d; // calls operator=
    }

    fixed_point& operator=(double d)
    {
        data = static_cast<BaseType>(d*factor);
        return *this;
    }

    BaseType raw_data() const
    {
        return data;
    }

    // Other operators can be defined here
};

fixed_point<int, 8> fp1;           // Will be signed 24:8 (if int is 32-bits)
fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)

A: A cast from float to integer will throw away the fractional portion so if you want to keep that fraction around as fixed point then you just multiply the float before casting it. The below code will not check for overflow mind you.
If you want 16:16
double f = 1.2345;
int n;

n=(int)(f*65536);

if you want 24:8
double f = 1.2345;
int n;

n=(int)(f*256);

A: I gave the answer to the guy that wrote the best answer, but I really used a related questions code that points here.
It used templates and was easy to ditch dependencies on the boost lib.

A: This is fine for converting from floating point to integer, but the O.P. also wanted fixed point.
Now how you'd do that in C++, I don't know (C++ not being something I can think in readily). Perhaps try a scaled-integer approach, i.e. use a 32 or 64 bit integer and programmatically allocate the last, say, 6 digits to what's on the right hand side of the decimal point.

A: There isn't any built in support in C++ for fixed point numbers. Your best bet would be to write a wrapper 'FixedInt' class that takes doubles and converts them.
As for a generic method to convert... the int part is easy enough, just grab the integer part of the value and store it in the upper bits... decimal part would be something along the lines of:
for (int i = 1; i <= precision; i++)
{
   if (decimal_part > 1.f/(float)(i + 1)
   {
      decimal_part -= 1.f/(float)(i + 1);
      fixint_value |= (1 << precision - i);
   }
}

although this is likely to contain bugs still


text:
Q: Using web.py on Appengine I am looking for a simple python web framework which runs both as standalone and on Appengine.
I would like to write the app in such a way that i can switch between standalone and Appengine based on the deployment configuration. Standalone will be using RDBMS.
When i checked web.py looked simple and promising. I have the following questions:

*

*Does web.py work well on Appengine?

*Is there any major known gotchas?

*Can you share your experience with using web.py on Appengine?

*Any suggestions to achieve the above mentioned goal is appreciated.

A:
Does web.py work well on Appengine?

Yes it does work pretty well, it's compact and very easy to use.

Is there any major known gotchas?

Web.py does not offer any Data Abstraction Layer compatible with GAE; that means that in order to switch from a RDBMS to a NoSQL database, you have to create by yourself a layer above both the web.db database API and the Google App Engine datastore API.

Can you share your experience with using web.py on Appengine?

I have deployed a couple of simple applications with web.py on top of GAE and other several pet projects with Sqlite as database; here a mini review.

Any suggestions to achieve the above mentioned goal is appreciated.

If the switch from Appengine to RDBMS is your primary concern, have a look to web2py.
Although with some limitations, to the best of my knowledge is the only one Python web framework GAE friendly that offers a DAL above the App Engine Datastore and other several RDBMS solutions.
Switching from one db to another is just a matter of initializing the DAL with the proper connection string:
db = DAL('sqlite://storage.db')
db = DAL('mysql://username:password@localhost/test')
db = DAL('gae')

A: No webapp framework on its own is going to be able to do this - the App Engine environment consists of a lot more than just a database interface and a CGI environment. Even if it could, any DAL that supports both the datastore and a relational DB is likely to sacrifice most of the flexibility of both in pursuit of that.
Your best option, if you want to take advantage of more than just the datastore, is to write your app for App Engine, and use AppScale or TyphoonAE to run your app outside the App Engine environment.

A: Consider using webapp2. It is similar to web.py, provides basically the same featureset, and runs outside of App Engine out-of-the-box. Besides, you get stellar compatibility with App Engine SDK and libraries (I explain it better here).
You'd only need to add a relational database library. But this is an easy choice: SQLAlqchemy is pretty much the standard in Python land, with lots of documentation and a thriving community.

A: I would also suggest web2py. Great framework, great community, plays out-of-the-box outside of AppEngine. It also supports a lot of databases (SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, and Google App Engine).
On top of that, it's trivial to install it on Linux, Windows, Mac.


text:
Q: Banker's algorithm - can I allocate resources to a process if Work is less than Need I'm reading about Banker's algorithm from here, I know that one condition to check if we can allocate available resource to a process is that check whether Work > Need, my wonder is that can we do so if Work < Need but Work + Allocation > Need.
For example, there are three resources R1, R2, R3 and we have already allocated P1 (0,0,4), it still needs (2,3,1) to finish its job. Now we have (2,3,0) resources available. Is it safe to give these resources to P1 and make sure there is no deadlock?

A:
For example, there are three resources R1, R2, R3 and we have already allocated P1 (0,0,4), it still needs (2,3,1) to finish its job. Now we have (2,3,0) resources available. Is it safe to give these resources to P1 and make sure there is no deadlock?

No, it's not safe because the system has 0 resources of type 3 (last argument in (2,3,0)), while P1 needs 1 resource of this type - (2,3,1).
If your process P1 demands all the resources, the system puts such a request on a waiting list (it lacks a resource of type 3). Then, all of your other processes demand additional resources too, and so the system adds their requests to the queue.
So, neither of the processes can finish and release resources because they all are waiting for other processes to complete. Since, the request from P1 wants more than what is possible, it never completes, and so do the other requests. Hence, you have a deadlock situation.


text:
Q: How to store data of different type in C? I want to store some data, that can be of a different type that is only known in runtime. I do not want to waste any memory and I want to read all data as float values. In C++ I would have done something like this
struct IA {
  virtual float value(int index) = 0;
};

template<class T>
struct A : public IA {
  A(T* bytes, uint32_t size) {
    values.resize(size);
    memcpy(values.data(), bytes, size*sizeof(T));
  }
  float value(int index) override {
      return static_cast<float>(values[index]);
  }
  std::vector<T> values;
};

int main() {
  uint16_t bytes[] = {1, 2, 3, 4, 5 };
  IA *a = new A<uint16_t>(bytes, 5);
  float value = a->value(0);
  delete a;
}

My question is how this would be done using C instead of C++. I could store the data in an uint8_t array and store nr of bits and a signed value. Then use a switch case and a cast every time I read a value from the array. But that would be expensive if the array is large and if there are many reads.
I also want to be able to pass the array around without having to do any special if cases?

A: You can mimic virtual method with function pointer:
typedef struct
{
    void* userData;
    float (*value)(void*, int);
} IA;

float get_float_from_uint16(void* userData, int index)
{
    return ((uint16_t*) userData)[index];
}

int main()
{
    uint16_t bytes[] = {1, 2, 3, 4, 5 };
    IA a = {bytes, &get_float_from_uint16};

    int index = 0;
    float f = a.value(a.userData, index);
}

Demo

A: Sure, that's plain and easy (spoiler alert: no, it's not easy, it's very hard). The following code I believe does the same as C++, but is written in C like.
So what happens:

*

*At first I define struct IA_s that is an interface for accessing IA like objects. The structure holds only a virtual table for accessing the objects. The AI object has one accessor IA_value that does the same as IA::value in your code. I also added the objects destructor to the virtual table and IA_fini function that is a destructor. It's missing in your code and your code leaks memory.

*Then I create two big macros A_C and A_H. A_H is intented to be used in header files. A_C is intended to be used inside sources files. They define a generic implementation of A object for any type. The first macro argument is the prefix to be used to prefix all exported symbols. The second is the type. The A object holds a dynamic array of some type elements.

*Then I instantiate the generic macros on uint16_t type with uint16_ prefix.

*Then in main function I allocate memory for A object, call it's constructor, cast it to IA object, get the value for the 2nd index and call all destructors.

Notes:

*

*constructors are named *_init, destructors are named *_fini, all functions that touch an object are named object_*.

*that was fun to do

*I think I would never use such code in production

*All heaps freed in valgrind

#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* IA object ---------------------------------------------- */

// forward definition for IA__vtable_s
struct IA_s;

// the virtual table of the object
struct IA__vtable_s {
    float (*value)(struct IA_s *ctx, size_t index);
    void (*fini)(struct IA_s *ctx);
};

// The structure, holds only the vtable
struct IA_s {
    const struct IA__vtable_s *vtable;
};

/**
 * Get the value holded in index index
 * @param t
 * @return the value
 */
float IA_value(struct IA_s *t, size_t index) {
    assert(t != NULL);
    assert(t->vtable != NULL);
    assert(t->vtable->value != NULL);
    return t->vtable->value(t, index);
}

/**
 * Call the destructor of IA object
 */
void IA_fini(struct IA_s *t) {
    assert(t != NULL);
    assert(t->vtable != NULL);
    assert(t->vtable->fini != NULL);
    t->vtable->fini(t);
}

/* A object ---------------------------------------------- */

/**
 * Header template of A object
 */
#define A_H(NAME, TYPE)  \
/* A object */ \
struct NAME##A_s { \
\
   /* pointer to allocated array */ \
   TYPE *arr; \
\
   /* elements in the array. */ \
   size_t cnt; \
\
   /* I think we have to have that. */ \
   struct IA_s ia; \
\
}; \
\
/* Initializes A object. The *bytes are copied into the object */ \
/* @param t */ \
/* @patam bytes pointer to size count of objects */ \
/* @param size */ \
/* @returns negative errno value on error, 0 on success */ \
int NAME##A_init(struct NAME##A_s *t, TYPE *bytes, size_t size); \
\
/* Deinitializes A object. */ \
void NAME##A_fini(struct NAME##A_s *t); \
\
/* Converts A object in IA object */ \
struct IA_s *NAME##A_to_IA(struct NAME##A_s *t);
// end of A_H

#define A_C(NAME, TYPE) \
\
/* A to IA interface ----------------------------------------------------- */ \
\
/* Convert pointer to IA_s to pointer to A_s */ \
static \
struct NAME##A_s *NAME##A__pnt_from_ia(struct IA_s *t) { \
    return (void*)( ((unsigned char*)(void *)t) - offsetof(struct NAME##A_s, ia) ); \
} \
\
/* this is our value function inside IA interface */ \
static \
float NAME##A__IA_value(struct IA_s *ia, size_t index) { \
    struct NAME##A_s *t = NAME##A__pnt_from_ia(ia); \
    assert(t != NULL); \
    /* UB happens, as in case of vector::operator[] */ \
    assert(index <= t->cnt); \
    return t->arr[index]; \
} \
\
/* this is our destructor inside IA interface */ \
static \
void NAME##A__IA_fini(struct IA_s *ia) { \
    struct NAME##A_s *t = NAME##A__pnt_from_ia(ia); \
    assert(t != NULL); \
    NAME##A_fini(t); \
} \
\
static const struct IA__vtable_s NAME##A__IA_vtable = { \
    .value = NAME##A__IA_value, \
    .fini = NAME##A__IA_fini, \
}; \
\
int NAME##A_init(struct NAME##A_s *t, TYPE *bytes, size_t cnt) { \
    assert(t != NULL); \
    assert(bytes != NULL); \
    if (cnt == 0) {  \
       /* malloc(0) happens to be nonportable */ \
       t->arr = NULL; \
       t->cnt = 0; \
       return 0; \
    } \
    if (SIZE_MAX / sizeof(*t->arr) < cnt) { \
    /* multiplication overflow */ \
    return -EOVERFLOW; \
    } \
    t->arr = malloc(cnt * sizeof(*t->arr)); \
    if (t->arr == NULL) { \
        return -ENOMEM; \
    } \
    t->cnt = cnt; \
    memcpy(t->arr, bytes, cnt * sizeof(*t->arr)); \
    t->ia.vtable = &NAME##A__IA_vtable; \
    return 0; \
} \
void NAME##A_fini(struct NAME##A_s *t) { \
    assert(t != NULL); \
    free(t->arr); \
    t->arr = NULL; \
    t->cnt = 0; \
} \
struct IA_s *NAME##A_to_IA(struct NAME##A_s *t) { \
     assert(t != NULL); \
     return &t->ia; \
}

// A<uint16_t>
A_H(uint16_, uint16_t)
A_C(uint16_, uint16_t)

int main() {
    uint16_t bytes[] = {1, 2, 3, 4, 5 };

    // new()
    struct uint16_A_s *temp = malloc(sizeof(*temp));
    if (temp == NULL) {
        // destructors
        abort();
    }

    // A::A(bytes, 5)
    int ret = uint16_A_init(temp, bytes, 5);
    if (ret != 0) {
        // destructors
        free(temp);
        abort();
    }

    // IA *ia = A;
    struct IA_s *ia = uint16_A_to_IA(temp);
    if (ia == NULL) {
        // destructors
        uint16_A_fini(temp);
        free(temp);
        abort();
    }

    // finally call IA::value(2)
    float value = IA_value(ia, 2);
    printf("%f\n", value);

    // destructors
    IA_fini(ia); // or uint16_A_fini(temp) depending on which you call delete on

    free(temp);
}


text:
Q: How on/live event in JQuery actually works? I am trying to write a plugin, that will bind some loading animation to pictures before they are loaded from the server. It works fine, except some cases. I mean changing of the DOM structure. The logic of my plugin is:
(function( window ){

'use strict';

var $ = window.jQuery;
var console = window.console;
var hasConsole = typeof console !== 'undefined';

var methods = {
    // plugin initialization
    init : function( options ) {
        return this.each(function(){
            methods._applyImagepreloader.apply( this, options);
        });
    },
    // working with each object
    _applyImagepreloader: function() {
        // if has class imagepreloader, do nothing
        if ($(this).hasClass('imagepreloader'))
            return;
        // if the image has determined size
        var width = $(this).width();
        var height = $(this).height();
        $(this)
            .clone()
            .attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
            .attr('width', width)
            .attr('height', height)
            .addClass('imagepreloader')
            .insertAfter(this);
        $(this).hide();
        $(this).load(function(){
            $(this).next('.imagepreloader').remove();
            $(this).fadeIn();
        });
    }
};

$.fn.imagepreloader = function( options ) {
    return methods.init.apply( this, options );
};

})( window );

Now, when the page is being updated by AJAX and new image tags appear, my plugin does not work. I made an investigation and learned, that the DOM mutation events can help me, but, as I understood, they are not supported by all browsers. Moreover, I can catch changin of DOM structure, using setinterval, but I guess It is not the best practice. So, maybe the issue has been already solved in JQuery on/live events. I wonder, how they work. How they can catch an appearance of new DOM elements?

A: When you use event delegation with on, event is always attached to a static element which is not going to be loaded dynamically
$("#Container").on('click','#dynamicallyAddedChildOfContainer',function(){...});

For example #Container in above example is the container which is present in DOM and you are adding #dynamicallyAddedChildOfContainer dynamically, Now when you click on dynamically added element, the event bubble's up to the container and that is where the event is triggered.
More on event delegation -

*

*http://learn.jquery.com/events/event-delegation/


text:
Q: Hybrid apps fullScreen I've fouded this plugin to get the Immersive Android view on a Hybrid app (GitHub)
But the navbar is attached into the StatusBar

i've tried with css ..
.platform-android.has-translucent-status-bar.app-header-bar{ padding-top:25px!important; }

Any suggestion?

A: If you want to completely hide the status bar:
$ionicPlatform.showStatusBar(false);

Make sure to inject $ionicPlatform to the service/controller. Also make sure to install the Cordova Statusbar Plugin.
ionic plugin add cordova-plugin-statusbar
If you only want to push the content down a bit, you can do this:
body {
    padding-top: 25px !important;
}


text:
Q: LogicApps Web API making it Asynchronous I had to write a Web API to insert data into custom on-premise DB and then call a stored procedure for LogicApps to use.  The LogicApps' call timeouts when passing large amopnts of data.  So I'm trying to use this solution I found here:
LogicAppsAsyncResponseSample
So I would basically put all my code into the doWork like this:
foreach (var record in records)
{
  ...
  //Insert record
  cmd.ExecuteNonQuery();
}
...
//Call SP
cmd.ExecuteNonQuery();

runningTasks[id] = true;

My question is should I make my code in doWork, asynchronous?  Use Await as needed and ExecuteNonQueryAsync instead of ExecuteNonQuery and add AsynchronousProcessing to my connection string?
Alternatively, too I was actually considering writing this to be "Fire and Forget".  Meaning I would start a thread in my API to call doWork as in the sample and return OK instead of Accepted right away. Then I wouldn't need to store thread statuses or have the chekcStatus method. This is OK for me since the API can send alerts if anything fails. The only advantage to the noted sample is I can eventually return something to LogicApps indicating success or not and show it in my LogicApps' log (one place to see all). Is "Fire and Forget" a sound practice?
FYI: the call to dowork in the sample is:
new Thread(() => doWork(id)).Start();


text:
Q: Identify "Not Determined" case for Local Notifications settings As of iOS8 you to need to register and prompt the user for the use of Local Notifications. Therefore I'd like to implement a way to double check these permissions.
How can I check for the case of Local Notifications settings being not determined/not set yet? So far I only know how to check for Local Notifications being granted or denied, like this …
    var currentStatus = UIApplication.sharedApplication().currentUserNotificationSettings()
    var requiredStatus:UIUserNotificationType = UIUserNotificationType.Alert

    if currentStatus.types == requiredStatus {
     … //GRANTED
     } else {
     … //DENIED
     }

The problem using this is I also get a Denied if there is nothing set so far. How can I differentiate all 3 cases?

*

*Granted (Notification, Alert Type)

*Denied (Notification, Alert Type)

*Undefined/Not set yet (therefore local notification app settings not created yet)

As an alternative solution it would be helpful to have a comparable delegate method to CoreLocation's authorization didChangeAuthorizationStatus in order to react on the user's selection on the permissions alert. Is there something like this in order to get the state of user interaction with the privacy alert for local notifications?

A: The solution I implemented :
In app delegate, I detect when didRegisterUserNotificationSettings is shot. And I save in userdefaults a bool to true :
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notificationsDeterminedKey")
        NSUserDefaults.standardUserDefaults().synchronize()
}

And when I need to know the status :
if NSUserDefaults.standardUserDefaults().boolForKey("notificationsDeterminedKey") {
    let grantedSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
    if grantedSettings.types == UIUserNotificationType.None {
        // Denied
    } else {
        // Granted
} else {
    // Not Determined
}

A: I just found an appropriate UIApplication delegate method that helps to solve this:
- (void)application:(UIApplication *)application
    didRegisterUserNotificationSettings:
    (UIUserNotificationSettings *)notificationSettings {

You can find more details on this in WWDC14 Session 713 "What's New in iOS Notifications".


text:
Q: Contour Integration and Branch Cuts I have a embarrassingly simple question. For some reason I haven't really studied complex before and I'm suffering under this now. I need to evaluate contour integrals of multi-valued functions and I'm confused about a few details (the standard examples in the textbooks avoid the difficulties I encounter with my integrals). Let me take some examples from the paper arXiv:1008.5194 (see pages 53-54).
There they want to evaluate the integral
$$\oint_{|\omega|=x}d\omega\:(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4}$$

where $x\in]0,1[$ and they get
$$(-1+e^{-i\frac{3\pi}2})\int_0^xd\omega\:(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4}.$$
(Which is essentially the integral representation of hypergeometric functions). Since the integrand is multi-valued and has branch points at $\omega = 0, x, 1$ we should probably make a branch cut on the positive real axis. If I naively deform the contour into a line from $x$ to $0$ above the real axis and a line from $0$ to $x$ below the real axis, I seem to get the right result. But that can't be correct; due to the branch cut the circle is not closed and we need to cross the cut several times to get back to the original Riemann sheet and close the contour. But when I do this, taking into account the phases accumulated while going around the Riemann surface, I don't get the correct result. How is this done right?
Another example is
$$\oint_{|\omega|=1}d\omega\:(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4} = (1-e^{-i\frac{3\pi}2})\int_1^{\infty}d\omega\:(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4}.$$
Here I don't get the result, even with the "naive way" and I don't understand why the integration should be over the interval $]1,\infty[$.

UPDATE: Sasha gave a very good answer and his solution seems to be correct, it agrees with numerical calculation. But it's different from what the paper finds and I think the paper is correct, so is there another non-equivalent way of interpreting the contour? Or might there be a problem in this (and lots of other) papers...?

A: Consider  $f(\omega) = \omega^{-3/4} (x-\omega)^{-3/4} (1-\omega)^{-3/4}$  and $ I(x) = \oint_{\vert \omega \vert = x} f(\omega) \mathrm{d} \omega$.
The function $f(\omega)$ is discontinuous at $\omega = -x$ along $\vert \omega \vert = x$ and has integrable singularity at $\omega = x$. Making a change of variables, $\omega = x z$:
$$
  I(x) = \frac{1}{\sqrt{x}} \oint_{\vert z \vert = 1} z^{-3/4} (1-z)^{-3/4} (1-x z)^{-3/4} \mathrm{d} z = \frac{1}{\sqrt{x}} \oint_{\vert z \vert = 1} h\left(z\right) \, \mathrm{d} z
$$
Let $\mathcal{C}$ denote the circle $\vert z \vert = 1$. Let $C_{-1, \delta}$ denote segment of $\mathcal{C}$ which crosses the negative axis and of length $2 \pi \delta$, with $\pi \delta$ above and $\pi \delta$ below the negative axis.
It is clear that integral along $\mathcal{C}_{-1,\delta}$ is vanishing as $\delta  \to 0$:
$$ \begin{eqnarray}
   \left\vert \int_{\mathcal{C}_{-1,\delta}} z^{-3/4} (1-z)^{-3/4} (1-x z)^{-3/4} \mathrm{d} z \right\vert &\le& (2(1+x))^{-3/4} \left\vert \int_{\mathcal{C}_{-1,\delta}} z^{-3/4} \mathrm{d} z \right\vert \\
 &=& \left(2 (1+x) \right)^{-3/4} \frac{8\sqrt{2}}{7} \sin\left(\frac{7 \delta}{8}\right) \left( \cos\left(\frac{7 \delta}{8}\right) - \sin\left(\frac{7 \delta}{8}\right)  \right)
\\ &\le& \sqrt{2} \delta \left(2 (1+x) \right)^{-3/4}
 \end{eqnarray}
$$
Let's complete $\mathcal{C} \backslash \mathcal{C}_{-1,\delta}$ with integration along $(-1,0)$ above the axis and then along $(0,-1)$ below the axis so as to complete the contour, and call the completed contour $\mathcal{L}$. Then
$$
\begin{eqnarray}
   \oint_{\mathcal{C}} h\left(z\right) \, \mathrm{d} z &=& \oint_{\mathcal{L}} h\left(z\right) \, \mathrm{d} z + \int_0^1 \left( h\left(-y - i \epsilon \right) - h\left(-y + i \epsilon \right) \right)\, \mathrm{d} y \\
  &=& \oint_{\mathcal{L}} h\left(z\right) \, \mathrm{d} z + \left( \mathrm{e}^{i \frac{3 \pi}{4}} - \mathrm{e}^{-i \frac{3 \pi}{4}} \right) \int_0^1 y^{-3/4}(1+y)^{-3/4}(1+x y)^{-3/4} \mathrm{d} y
\end{eqnarray}
$$
The claim is that the principal value of $\oint_\mathcal{L} h(z) \mathrm{d} z = 0$, so we get
$$
  I(x) = \frac{2 i \sin\left( 3/4 \pi \right)}{\sqrt{x}} \int_0^1 y^{-3/4}(1+y)^{-3/4}(1+x y)^{-3/4} \mathrm{d} y
$$
Now, let's check this with quadratures:

Notice that the purported answer you gave in your post can not be correct, as it is not purely imaginary.

A:
I think the authors get the answer just by contour deformation from the circle to the green line. Suppose above the branch cut $(0,x)$, the integrated function is
$$(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4}$$
When the contour rotates around $\omega=0$, we have
$$\omega\rightarrow \omega e^{2\pi i}$$
and the integrated function becomes
$$e^{-3\pi i/2}(1-\omega)^{-3/4}(x-\omega)^{-3/4}\omega^{-3/4}$$


text:
Q: Reconstructing set of points from one-dimensional images Consider a set of $N$ points in $n$-dimensional space, i.e.
\begin{align*}
   \{x_1, \dots, x_N\} \subset \mathbb R^n.
\end{align*}
Let us be given a finite family of non-injective matrices
\begin{align*}
   \{M_j \in \mathbb R^{m \times n} : j = 1, \dots, J\},
\end{align*}
e.g. $m<n$.
In a nutshell, the problem I would like to address is the following: For any $j = 1, \dots, J$ we are given the set of points (i.e. no knowledge about ordering!)
\begin{align*}
   \{M_j x_1 , \dots, M_j x_N\}
\end{align*}
which can be seen as a projection of the set $\{x_1, \dots, x_N\}$.
My question is: Under which conditions on the family of projection matrices we can uniquely reconstruct the set $\{x_1, \dots, x_N\}$? Intuitively I would say that $J$ has to be large enough (dependend on $N$) and that the matrices should fullfill some assumption like
\begin{align*}
   \bigcap_{j = 1,\dots, J} \ker M_j = \{0\}.
\end{align*}

A: Denote by $S$ your finite collection of $N$ points in $\newcommand{\bR}{\mathbb{R}}$ $\bR^n$.   Here is how you can recover $S$  from the knowledge of its  images via a finite collections of linear maps of rank $<n$.  More precisely one can use a universal family consisting of roughly $\frac{N^4}{2}$ matrices of type $(n-1)\times n$ and  $n+2$  matrices of type  $1\times n$.  This may not be optimal but at least it is polynomial in $N$. (For a precise statement you can skip to the highlighted portion at the end of my answer.)
Pick a  finite collection $\newcommand{\eL}{\mathscr{L}}$ $\eL$ of  linear maps  $\bR^n\to\bR$ in general position, i.e.,  any $n$ of them are linearly independent. Denote by $\nu$ the cardinality of $\eL$. The number $\nu$ is $> n$ and will be specified later.  For any collection $C\subset \eL$   we  obtain a  linear map
$$L_C:\bR^n\to\bR^C. $$
Denote by $\binom{\eL}{n-1}$ the collection of subsets of $\eL$ of cardinality $n-1$.There are $\binom{\nu}{n-1}$ such subsets.  If $C$ is such a collection, then the linear map $L_C:\bR^n\to\bR^{n-1}$ is surjective and it has a one-dimensional kernel.   The general position assumption shows that if $C_0,C_1\in \binom{\eL}{n-1}$,  then
$$ C_0=C_1\iff \ker L_{C_0}=\ker L_{C_1}. $$
A. Suppose we know $L_C(S)$ for any collection $C\in\binom{\eL}{n-1}$.
Assume $\nu$ is large enough so that
$$\binom{\nu}{n-1}>\binom{N}{2}. $$
Since the $N$ points in $S$  determine  at most $\binom{N}{2}$ lines, we deduce that at least one of the linear maps $L_C$, $C\in\binom{\eL}{n-1}$, restricts to an injective map $S\to \bR^C$.  In particular we deduce that
$$ N=\# S= \max_{\# C=n-1} L_C(S). $$
Choose $C_0\in\binom{\eL}{n-1}$ such that $\# L_{C_0}(S)=\# S=N$.  Without loss of generality we can assume that  $L_{C_0}$ is the  projection
$$P_0:\bR^n\to \bR^{n-1},\;\;(x_1,\dotsc,x_n)\mapsto (x_1,\dotsc, x_{n-1}). $$
For each point $s\in S$ we set $s':=P_0(s)$. Now we have complete knowledge of the  set
$$ S'=\bigl\lbrace\; s';\;\;s\in S\;\bigr\}=P_0(S). $$
The set $S'\subset \bR^{n-1}$ has the same cardinality as  $S$.  Moreover any point $s'\in S'$ determines a vertical line, i.e., a line parallel with $\ker P_0$,
$$ \ell_{s'}=P_0^{-1}(s')=\bigl\{\; (s', t)\in\bR^n;\;\;t\in\bR\;\bigr\}. $$
We now have determined $N$ vertical lines and each one of them  contains exactly one point in $S$.
B. Suppose that we know $L(S)\subset \bR$ for any $L\in\eL$.
Choose a linear functional $L\in \eL\setminus C_0$.  The set $L(S)$  has $m\leq N$ elements $r_1<\cdots <r_m$.   We obtain  $m$-hyperplanes
$$H_j(L)=\{ L(x)=r_j\},\;\;j=1,\dotsc, m, $$
and a set  $X(S,L)$ consisting of $Nm$ points
$$ H_j(L)\cap \ell_{s'},\;\;j=1,\dotsc, m,\;\;s'\in S'.  $$
Clearly $S\subset  X(S,L)$.  Thus $S$ can only be one of the $\binom{Nm}{N}$ subsets of $X$ of cardinality $Nm$.   Doing this with any $L\in \eL\setminus C_0$  we  deduce
$$ S\subset \bigcap_{L\in\eL\setminus C_0} X(S,L). $$
Fix a linear map $L_0\in \eL\setminus C_0$ and set $X_0=X(S, L_0)$. We know that
$$ S\subset X_0,\;\; \# X_0\leq N^2. $$
Suppose that $\nu$ is large enough so that
$$\binom{\nu}{n-1}>\binom{N^2}{2} +2.  $$
We can  then find  a collection $C_1\in\binom{\eL}{n-1}$ such that $C_1\neq C_0$ and $L_{C_1}$ and the restriction of $L_{C_1}$ to $X_0$ is injective.   We know know exactly   $L_{C_1}(X_0)$ and $S_1:=L_{C_1}(S)\subset L_{C_1}(X_0)$.  Note that $\# S_1=\# S=N$.
For each point $s_1\in S_1$ we get a line $\ell_{s_1}= L_{C_1}^{-1}(s_1)$.    Let us observe that  each line $\ell_{s_1}$ intersects  exactly one of the lines  $\ell_{s'}$, $s'\in S'$,  because
$$\ell_{s_1}\cap\ell_{s'}\subset X_0, $$
and the restriction of $L_{C_1}$ to $X_0$ is one-to-one.

To conclude, if $\eL\subset  {\rm Hom}\;(\bR^n,\bR)$ is a finite
  collection in general position whose cardinality  $\nu$ satisfies
$$\binom{\nu}{n-1}>\binom{N^2}{2}+2, \tag{$\nu$}$$
and we know   $L_C(S)$  $\forall C\subset \eL$ of
  cardinality $1$ or $n-1$, then we can  completely recover  $S$.

Remark. We can relax  assumption  B to
B'. We know $L(S)$ for any $L$  in  a family $F\subset \eL$ of cardinality $n+2$.
Update. Let me explain how the above  procedure can be used to recover multisets.  First, let me define  a discrete weight distribution or d.w.d. in $\bR^n$ to be a pair $(S, w)$ where $S$ is a finite subset of $\bR^n$ and $w$ is a function $w:S\to (0,\infty)$. We say that $S$ is the support of the d.w.d.
Given a d.w.d. $(S,w)$ in $\bR^n$ and a map $f:\bR^n\to\bR^m$ we obtain a d.w.d. $f_*(S,w)$ in $\bR^m$ given by
[
$$ f_*( S, w)= \bigl(\; f(S),  f_* w)\;\bigr), $$
where for any $y\in f(S)$ we set
$$ f_* w(y)=\sum_{x\in f^{-1}(y)\cap S} w(x). $$
Suppose  that $(S,w)$ is  a d.w.d. in $\bR^n$  $\DeclareMathOperator{\Hom}{Hom}$ such that $|S|=N$, and $\eL\subset \Hom(\bR^n,\bR)$ of cardinality $\nu$  constrained by the inequality ($\nu$) above.  I claim that if we know the d.w.d.'s $(L_C)_*(S,w)$ for any subset $C\subset \eL$ of cardinality $1$ and $n-1$, then we can completely  determine $(S,w)$.
To see this, note that  the above discussion shows that this information  can be used to determine the  support $S$ of the  unknown d.w.d. $(S,w)$.  To determine $w$ choose a subset $C_0\in \binom{\eL}{n-1}$ such that the restriction of $L_{C_0}$ to $S$ is  injective. Let $x\in S$ and set $y=L_{C_0}(x)\in\bR^{C_0}$. In this special case we have
$$ w(x)= (L_{C_0})_*w(y). $$
From our assumption, the quantity  in the right hand side of the above equality is known.

A: I don't provide an actual answer (I don't have one), but do provide some musings that might be helpful to others who would like to consider this problem.
First, if there is only one point, then the condition
$$\bigcap_{j = 1,\dots, J} \ker M_j = \{0\}$$
is both necessary and sufficient. It is clearly necessary even if there are more points.
Consider the two-dimensional case, i.e. the situation $n=2 =m$, and suppose the matrices are projections to one-dimensional subspaces. For any two projections it seems possible to place three points so that they can't be distinguished from four points - for example, suppose the two projections are coordinate projections, and take the three or four points to be corners of a square.
By drawing additional pictures it seems that, in the plane, $J$ maps are not enough (in the sense that one can select $J+2$ points so that omitting specific one of them does not change the set of projections) but $J+1$ projections to different lines do seem to suffice. Actually proving this would presumably be a matter of linear algebra, but I have not done it.
In two dimensions the strategy seems to be to consider projections to arbitrary and different lines. In higher dimensions it might be useful to first consider projections to one-dimension or $n-1$-dimensional subspaces, and only after getting some grip on those try to consider a situation with projections onto subspaces of mixed dimensions.


text:
Q: Powershell/Exchange Management Console I am attempting to, due to a user request, change the ExternalDsnMaxMessageAttachSize attribute from the exchange management shell. When I run the following command:
set-transportconfig -ExternalDsnMaxMessageAttachSize 20 MB

It works perfectly.
When I run the same command as an admin in powershell, it won't run, and ultimately no changes are made.
I am a powershell novice to say the least, but am I missing something here?
Is there a way I could push these changes out?


text:
Q: React, working with select component with objects Im new to react and I have a question about select component of material ui.
The thing is like this, I have a funcionality that is for creating and editing an User, this User is an object, it has primary key and some data, between this data there is a relation with other object that is a role, so in this case I use a Select component to select the role.
So, I have the role list that I bring from the backend:
const [rolList, setRolList] = React.useState([]);

const searchRoles = async () => {
    try {
      setRolList(await api.post('/v1/roles/buscar', filtroRol));
    } catch (error) {
      snackbar.showMessage(error, "error");
    }
  }

And the select component that is inside a formik:
              <Mui.Select
                    label="Role"
                    value={values.usuRolPk}
                    onChange={(opt) =>{handleChange(opt);
                    }}
                    >
                      <Mui.MenuItem disabled key={0} value=''>
                        Select role
                      </Mui.MenuItem>
                    {rolList.map((e) => {
                        return <Mui.MenuItem key={e.rolPk} value={e.rolPk}>{e.rolName}</Mui.MenuItem>;
                    })}
                  </Mui.Select>

As you can see, for the value of the select I use the pk of role, so when the user is persisted I have to search in the list of roles and atach the selected object to the users object and send it to the backend.
Something like this (usuRolPk is the value of the select, usuRol is the relation with object role):
const save = async (values) => {
    try {

      if(values.usuRolPk==null){
        values.usrRole=null;
      }else{
        values.usrRole=rolList.filter(element=>''+element.rolPk==values.usuRolPk)[0];
      }
     ...

      if (values.usrPk == null) {
        await api.post('/v1/users', values);
      } else {
        await api.put('/v1/users/' + values.usrPk, values);
      }
      handleClose();
      snackbar.showMessage("GUARDADO_CORRECTO", "success")
    } catch (error) {
      snackbar.showMessage(error, 'error');
    }
    return;
  }

The thing is, I want to skip that last step of having to search in the list of roles with the selected Pk.
Is there a way of working just with the object as the selected value instead of the pk? I tried just changing the value to have the whole object like this:
                  <Mui.Select
                        label="role"
                        value={values.usuRol}
                        onChange={(opt) =>{handleChange(opt);
                        }}
                        >
                          <Mui.MenuItem disabled key={0} value=''>
                            Select role
                          </Mui.MenuItem>
                        {rolList.map((e) => {
                            return <Mui.MenuItem key={e.rolPk} value={e}>{e.rolName}</Mui.MenuItem>;
                        })}
                      </Mui.Select>

This works just when Im creating a new object, but when I try to edit an object that already exists and already has a role, when I pass the role to the select It says something like I initialize the Select with a value that doesnt exist in the list of roles.
Is there a way to achieve this?
Thanks!

A: Per conversation in the comments on the question:
I'm doing this with a normal select and options purely for convenience, but you can replace them easily enough with their mui equivalents:
import React, { useState, useEffect, useCallback } from 'react';

const SomeComponent = () => {
  const [list, setList] = useState({}); // { "1": someObjWithId1, etc }
  const [selected, setSelected] = useState();
  useEffect(() => {
    const getList = async () => {
      const resp = await fetch('/some/url'); // get object list from backend
      const data = await resp.json();
      setList(data);
    };

    if (!list.length) getList();
  }, []);

  const handler = useCallback((evt) => {
    setSelected(list[evt.target.value]);
  }, [list, setSelected]);

  return (
    <select onChange={handler}>
      {Object.entries(list).map(([id, obj]) => selected && id === selected.id
        ? <option selected key={id} value={id}>{obj.text}</option>
        : <option key={id} value={id}>{obj.text}</option>
      )}
    </select>
  );
};

The component will render a select element with the options once they've been passed from the backend. The change handler will update the state with the entire object (keyed by the id/value) selected. In real life you'd likely have the state in a parent form component and pass it with the setter through props, but you get the idea.


text:
Q: Get Back Button to work on parent page when iframe is involved I am working on a legacy app that has an iframe involved. The back button is working on the iframe and I need it to bypass the iframe and work on the parent window only.
Here is a dumbed down version of the issue and description of what I know.
the main page "index.html" has an iframe that is being added via javascript. It loads a.html, makes an ajax call that then does a window.location = "b.html" At this point if you use the back button it essentiallys makes the iframe go back to a.html and then redirects to b.html so you are effectively stuck on the page. If I remove the ajax call and do an window.location on load everything works ok. However given the architecture and what happen on the page I can't remove the Ajax call from the picture.
Here is the code I am looking at, let me know your thoughts on how to solve this issue. Also I should mention in Chrome 41 this isn't an issue, however the newer chrome 48 and 49 it is an issue. I tried history.replaceState but wasn't able to figure out a way to use it in this situation that made things work.
index.html

    <title></title>

hello world!

a.html

    <title></title>

b.html

    <title></title>

A: This is only possible in HTML5 compatible browsers, and it would go something like this..
This goes in the child frame..
// catch the back button click.
window.onpopstate = function(event) {
  // make the parent window go back
  top.history.back();
};

This also only works if both frames are in teh same domain.


text:
Q: Create a looped variable in R I'm new to R and I'm trying to create a loop in R with a string mod and a variable x
my code so far looks like this m=1 and b=1 at the start of the code
  for (i in 1:5){
  mod = 'mod'
  mod + as.character(m) = b
  m = as.numeric(m)
  m = m+1
  b = (b + 1) * 2
}

what I want as an output is:
mod1 = 1
mod2 = 4
mod3 = 10

Is this possible or am I overthinking this problem?

A: You can assign values to a variable with incrementing id using assign(paste("mod",m,sep=""), b)
Your loop could be something like this:
for (i in 1:5){
  assign(paste("mod",m,sep=""), b)
  m = m+1
  b = (b + 1) * 2
}

You can find these variables in memory, as the loop is closed:
> mod1
[1] 1
> mod2
[1] 4
> mod3
[1] 10
> mod4
[1] 22
> mod5
[1] 46
> mod6
[1] 94

A: Save the results in a list, use list2env
m=1
b=1

res=list()

for (i in 1:5){
  mod = 'mod'
  res[[paste0(mod,as.character(m))]] = b
  m = as.numeric(m)
  m = m+1
  b = (b + 1) * 2
}

list2env(res,envir = .GlobalEnv)


text:
Q: Syntax error in body using HTTParty (Ruby/HTTParty) I'm just get a error and really don't know how to solve this.
What I'm trying:
class Addresses
include HTTParty
base_uri "https://reservedurl.com/"

def self.api_search
    search = get('members/api/default/member/addresses')
end

def self.api_change_address(street, new_zip, n)
    change_address = patch('members/api/default/member', {
        :body => {
          :'option_id' => '1'
          :'address' => {
            :'address_id' => '3',
            :'street_name' => '#{street}',
            :'alias' => 'Address',
            :'address_number' => '#{n}',
            :'additional_information' => 'New',
            :'reference_point' => 'New',
            :'city' => 'NY',
            :'country_code' => 55,
            :'district' => 'New',
            :'postal_code' => '#{new_zip}',
            :'state' => 'NY',
            :'default' => true,
            :'address_name' => 'string',
          }
        }.to_json
        :headers => {
          :'Content-Type' => 'application/x-www-form-urlencoded',
          :'charset' => 'utf-8',
          :'Host' => 'reservedurl.com',
          :'Accept-Encoding' => 'gzip, deflate',
          :'Accept' => '*/*',
          :'Postman-Token' => 'token'
        }
      })
end

API body:
{
  "option_id": "1",
    "address": {
    "address_id": "token",
    "street_name": "Jack, St",
    "alias": "Address",
    "address_number": "213",
    "additional_information": "New",
    "reference_point": "New",
    "city": "DC",
    "country_code": 55,
    "district": "WS",
    "postal_code": "0453401",
    "state": "WS",
    "default": true,
    "address_name": "string"
  }
}

And I got this error:
    *** WARNING: You must use ANSICON 1.31 or higher (https://github.com/adoxa/ansicon/) to get coloured output on Windows
c:/features/support/this_page.rb:13: syntax error, unexpected tSYMBEG, expecting '}'
              :'address' => {
              ^~
c:/features/support/this_page.rb:13: syntax error, unexpected =>, expecting end
              :'address' => {
                         ^~
c:/features/support/this_page.rb:28: syntax error, unexpected '}', expecting end
            }.to_json
            ^
c:/features/support/this_page.rb:29: syntax error, unexpected =>, expecting end
            :headers => {
                     ^~
c:/features/support/this_page.rb:37: syntax error, unexpected '}', expecting end
          })
          ^ (SyntaxError)
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/glue/registry_and_more.rb:107:in `load'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/glue/registry_and_more.rb:107:in `load_code_file'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime/support_code.rb:144:in `load_file'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime/support_code.rb:85:in `block in load_files!'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime/support_code.rb:84:in `each'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime/support_code.rb:84:in `load_files!'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime.rb:272:in `load_step_definitions'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/runtime.rb:68:in `run!'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/lib/cucumber/cli/main.rb:34:in `execute!'
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-3.1.2/bin/cucumber:9:in `<top (required)>'
C:/Ruby26-x64/bin/cucumber:23:in `load'
C:/Ruby26-x64/bin/cucumber:23:in `<main>'

I really don't see why HTTParty don't allow me to use this body. What I understand? The error is the bracket itself, but I'm trying to pass exactly how the API was. If I remove the bracket in address line the body don't will be read for my API.

A: You're missing commas after :'option_id' => '1' and after }.to_json,:
{
  :body => {
    :'option_id' => '1',
    :'address' => {
      :'address_id' => '3',
      :'street_name' => '#{street}',
      :'alias' => 'Address',
      :'address_number' => '#{n}',
      :'additional_information' => 'New',
      :'reference_point' => 'New',
      :'city' => 'NY',
      :'country_code' => 55,
      :'district' => 'New',
      :'postal_code' => '#{new_zip}',
      :'state' => 'NY',
      :'default' => true,
      :'address_name' => 'string',
    }
  }.to_json,
  :headers => {
    :'Content-Type' => 'application/x-www-form-urlencoded',
    :'charset' => 'utf-8',
    :'Host' => 'reservedurl.com',
    :'Accept-Encoding' => 'gzip, deflate',
    :'Accept' => '*/*',
    :'Postman-Token' => 'token'
  }
}


text:
Q: I am using codeigniter with bootstrap and I keep getting errors on mixing files, how do I correct this errors? here is my code snippet public function __construc1nv3ntiph('rs/cloudfiles.php');

  $ci =& get_instance();
  $ci->config->load('cloudfiles');
  $this->user = $ci->config->item('cf_user');
  $this->api_key = $ci->config->item('cf_api_key');

this is the error i get on the public function _Construc1nv3tiph()
Description
Resource Path Location Type syntax error,

unexpected
  ''rs/cloudfiles.php'' Cloudfiles.php  /1nv3ntiph/1nv3ntiph/application/libraries  line
  13    PHP Syntax Error

A: The way you are passing parameter to cnstructor is wrong,
public function __construc1nv3ntiph('rs/cloudfiles.php');

do it like this
public function __construc1nv3ntiph($a = "rs/cloudfiles.php");

Also take care about other lines of your code, if needed, enclose them inside a function.


text:
Q: Cocos2D: Recognize multiple tiles next to each other I'm currently building a platformer in cocos2d-x and therefore i'm using a tmxtiledmap and chipmunk physics. My problem is that in the moment EACH tile of the map gets its own physics body which obviously isnt really memory saving:D
Is there any method to "recognize" that multiple tiles are next to each other and therefore only need one physics body?
Greets FreezZl

A: How are you creating the physics bodies?I dont use chipmunk, but had used box2d with Tiled and created a single Physics body for each platform by assigning an object to the whole platform in tiled and using that to create the physics body.


text:
Q: String to 2 dimensional int array? I've a combobox, I am using an Action Listener.
Inside of that function if item: 1 or 2 etc... was selected it finds that maze which is saved in a database, it points to a Java Class. I put the maze in the maze_map variable.
Here -> maze_map=connect.getMaze(which_one);
.
`
comboBox.addActionListener (new ActionListener () {
  public void actionPerformed(ActionEvent e) {
    int which_one=(int) comboBox.getSelectedItem();
    String maze_map = "";// map from database
    maze_map=connect.getMaze(which_one);
    System.out.println(which_one);
    System.out.println(maze_map);
} });

Okay So until that I'm okay, I get back a String in the maze_map variable which contains 10x10 numbers.
String maze_map which contains 10x10 numbers.
1010000000
0111010000
0001010111
0000211011
0110001001
1110000010
0010108000
1110000061
1111001010
0100111001

But, I need to put all these numbers from the maze_map into a 2 dimensional int array.
My question is how to do it? I was trying with parseint but it didn't work.

A: Create an int array.
First you need to break the String array up into individual Strings
str = "1010000000 0111010000";
String[] splited = str.split("\\s+");

Then iterate through the array and you can use
int i=Integer.parseInt("currString");

to convert each String to an int.
Then just add the int to the int array.


text:
Q: Xlookup or vlookup Hoping someone can help me out with some excel magic -
I have two sheets.
Sheet 1 has a list of names in column D
Sheet 2 has a list of names in column B and corresponding ID's in column A
I need to map the names in Sheet 1 column D with the ones in Sheet 2 column B and populate column E in sheet one with the right ID.

A: The solutions provided in the comments are correct, but I want to pull them together and explain when and how you would use each.
As you may have realized, VLOOKUP() won't work for this because you want to retrieve a value to the left of your lookup range.  There are two best-known ways to solve this.

*

*XLOOKUP, if you have O365 or Excel 2021 is a vastly improved and more versatile version of the old VLOOKUP;  If not, INDEX(MATCH()) is the way to go.

If you do not have access to Excel 2021 or O365

*

*Use INDEX(MATCH()).  In your case that would look something like this in cell E2 of sheet1 and copy it down:

=INDEX( sheet2!A$2:A$100, MATCH( D2, sheet1!B$2:B$100 ) )
If you do have Excel 2021 or O365
Then definitely use the XLOOKUP function in sheet 1, cell E2:
=XLOOKUP( D2, sheet2!B$2:B$100, sheet2!A$2:A$100, "No ID")
In both cases:

*

*Be mindful of the $ to lock the lookup ranges, since you will most likely be copying this down the column rather than using an array formula.

*Both the examples assume that the values in sheet2 are rows 2 through 100.


text:
Q: c# Regex Pattern Similar to my question from yesterday:
C# Regex Pattern Conundrum
Same issue, different regex pattern.  The regex pattern returns the desired match when tested in http://sourceforge.net/projects/regextester/ and http://www.RegexLib.com  But, when the pattern is executed in .NET there are no matches returned.
string SampleText = @"\r\n99. Sample text paragraph one.\r\n100. Sample text here paragraph two.\r\n101. Sample text paragraph three.\r\n";
string RegexPattern = @"(?<=\\r\\n\d+\.\s)([^.]+?)here.*?(?=\\r\\n)";
Regex FindRegex = new Regex(@RegexPattern, RegexOptions.Multiline | RegexOptions.Singleline);
Match m = FindRegex.Match(SampleText);

The desired match is "Sample text here paragraph two."
As with yesterday, I'm not sure, if the issue is my regex pattern or my code.

A: You need to escape the special regex characters too:
string RegexPattern = @"(?<=\\r\\n\d+\.\s)([^.]+?)here.*?(?=\\r\\n)";

Or:
string RegexPattern = "(?<=\\\\r\\\\n\\d+\\.\\s)([^.]+?)here.*?(?=\\\\r\\\\n)";

Don't forget - you are in a C# string context, so you need to ensure that you pass in the correct string to the regex engine.

A: I figured it out.
When testing in RegexTester and RegexLib.com I copy and pasted my source text from the Immediate Window which converted control return line feeds to their text representation \r\n.
So, my regex worked in the test environment.  But, in actual runtime, the source text contained control return line feed, not \r\n as text.  Which explains why my pattern worked in the test environment, but not at runtime.
I changed my pattern to @"(?<=\n\d+\.\s)([^.]+?)here.*?(?=\n)" and it worked beautifully.
Embarrassing realization.  Thanks for your help Oded.


text:
Q: Tic tac toe resets every other turn I'm in the middle of trying to make a tic tac toe board and this is what I have so far. Unfortunately, after each player 2's turn, the board resets and I can't figure out what I need to do the fix it.
def display_board(board):
    print(board[7]+' |'+board[8]+' |'+board[9])
    print('-----')
    print(board[4]+' |'+board[5]+' |'+board[6])
    print('-----')
    print(board[1]+' |'+board[2]+' |'+board[3])

def player_input():
    marker = ''
    while marker == '':
        answer = input("Player 1, please choose X or O. ")
        if answer == 'O' or answer == 'X':
            marker = answer
        else:
            print("Answer was not X or O")
    while marker == 'X':
        gameplay('X','O')
    while marker == 'O':
        gameplay('O','X')

def gameplay(player1,player2):
    spaces = ["1","2","3","4","5","6","7","8","9"]
    board = ['#','','','','','','','','','']
    turn = True
    while turn is True:
        display_board(board)
        position = input("Player 1 pick a position(1-9)")
        if position not in spaces:
           print("Please pick a number 1-9")
        elif board[int(position)] == '' and position in spaces:
            board[int(position)] = player1
            turn = False
        else:
            print("Space already taken. Choose different position.")

    while turn is False:
        display_board(board)
        position2 = input("Player 2 pick a position(1-9)")
        if position not in spaces:
           print("Please pick a number 1-9")
        elif board[int(position2)] == '' and position2 in spaces:
            board[int(position2)] = player2
            turn = True
        else:
            print("Space already taken. Choose different position.")

A: You need to have another while loop that controls the game
    while not board_is_full:
        while turn: # turn of player 1
            display_board(board)
            position = input("Player 1 pick a position(1-9)")
            if position not in spaces:
               print("Please pick a number 1-9")
            elif board[int(position)] == '' and position in spaces:
                board[int(position)] = player1
                turn = False
            else:
                print("Space already taken. Choose different position.")
        while not turn: # turn of player 2
            display_board(board)
            position2 = input("Player 2 pick a position(1-9)")
            if position not in spaces:
               print("Please pick a number 1-9")
            elif board[int(position2)] == '' and position2 in spaces:
                board[int(position2)] = player2
                turn = True
            else:
                print("Space already taken. Choose different position.")

You should have one loop that ends only when board is full. To check it you can e.g. count moves, or check every position of your board.
As a bonus, notice your functions looks almost identical! You could separate it into another one.
def player_move(player, player_number):
    display_board(board)
    position = input(f"Player {player_number} pick a position(1-9)")
    if position not in spaces:
       print("Please pick a number 1-9")
       # we can run it recursively until correct number is provided
       player_move(player, player_number)
    elif board[int(position)] == '' and position in spaces:
        board[int(position)] = player
    else:
        print("Space already taken. Choose different position.")
        player_move(player, player_number)

...

   while not board_is_full:
       player_move(player1, 1)
       player_move(player2, 2)


text:
Q: How does array list object sorting work? I have an object called Movie and an array list called movieList. The object contains variables such as nameOfMovie, movieGenre ,dateRelised , curentRating. All those variables have gets and sets. In addition to that i have a form that has a textarea for each variable to be printed out. I was wandering how do i actually use the array list to sort the data that is stored.
So for example if i wanted to sort the  curentRating of a movie in smallest to biggest what would be the syntax of the program ?

A: Your movie class will need to implement the 'Comparable' interface.
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
According to the documentation you need to have a method called: compareTo(T o)

int compareTo(T o)
  Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
  The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

So basically you'll have a movie class that is declared like:
public class Movie implements Comparable{
  String nameOfMovie;
  .
  .
  .
  public int compareTo(Movie otherMovie){
     return someint;//this will be -1 if it's less than the current movie, 0 if its the same and 1 if its more than in terms of logical ordering;
  }

}
Should see the documentation for more info.


text:
Q: Implement UIKitDynamics for dragging view off screen I'm trying to figure out implement UIKit Dynamics that are similar to those in Jelly's app (specifically swiping down to drag view off-screen).
See the animation: http://vimeo.com/83478484 (@1:17)
I understand how UIKit Dynamics work, but don't have a great physics background and therefore am having trouble combing the different behaviors to get the desired result!

A: This sort of dragging can be accomplished with an UIAttachmentBehavior where you create the attachment behavior upon UIGestureRecognizerStateBegan, change the anchor upon UIGestureRecognizerStateChanged. This achieves the dragging with rotation as the user conducts the pan gesture.
Upon UIGestureRecognizerStateEnded you can remove the UIAttachmentBehavior, but then apply a UIDynamicItemBehavior to have the animation seamlessly continue with the same linear and angular velocities the user was dragging it when they let go of it (don't forget to use an action block to determine when the view no longer intersects the superview, so you can remove the dynamic behavior and probably the view, too). Or, if your logic determines that you want to return it back to the original location, you can use a UISnapBehavior to do so.
Frankly, on the basis of this short clip, it's a little tough to determine precisely what they're doing, but these are the basic building blocks.

For example, let's assume you create some view you want to drag off the screen:
UIView *viewToDrag = [[UIView alloc] initWithFrame:...];
viewToDrag.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:viewToDrag];

UIGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[viewToDrag addGestureRecognizer:pan];

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

You can then create a gesture recognizer to drag it off the screen:
- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    static UIAttachmentBehavior *attachment;
    static CGPoint               startCenter;

    // variables for calculating angular velocity

    static CFAbsoluteTime        lastTime;
    static CGFloat               lastAngle;
    static CGFloat               angularVelocity;

    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.animator removeAllBehaviors];

        startCenter = gesture.view.center;

        // calculate the center offset and anchor point

        CGPoint pointWithinAnimatedView = [gesture locationInView:gesture.view];

        UIOffset offset = UIOffsetMake(pointWithinAnimatedView.x - gesture.view.bounds.size.width / 2.0,
                                       pointWithinAnimatedView.y - gesture.view.bounds.size.height / 2.0);

        CGPoint anchor = [gesture locationInView:gesture.view.superview];

        // create attachment behavior

        attachment = [[UIAttachmentBehavior alloc] initWithItem:gesture.view
                                               offsetFromCenter:offset
                                               attachedToAnchor:anchor];

        // code to calculate angular velocity (seems curious that I have to calculate this myself, but I can if I have to)

        lastTime = CFAbsoluteTimeGetCurrent();
        lastAngle = [self angleOfView:gesture.view];

        typeof(self) __weak weakSelf = self;

        attachment.action = ^{
            CFAbsoluteTime time = CFAbsoluteTimeGetCurrent();
            CGFloat angle = [weakSelf angleOfView:gesture.view];
            if (time > lastTime) {
                angularVelocity = (angle - lastAngle) / (time - lastTime);
                lastTime = time;
                lastAngle = angle;
            }
        };

        // add attachment behavior

        [self.animator addBehavior:attachment];
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        // as user makes gesture, update attachment behavior's anchor point, achieving drag 'n' rotate

        CGPoint anchor = [gesture locationInView:gesture.view.superview];
        attachment.anchorPoint = anchor;
    } else if (gesture.state == UIGestureRecognizerStateEnded) {
        [self.animator removeAllBehaviors];

        CGPoint velocity = [gesture velocityInView:gesture.view.superview];

        // if we aren't dragging it down, just snap it back and quit

        if (fabs(atan2(velocity.y, velocity.x) - M_PI_2) > M_PI_4) {
            UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:gesture.view snapToPoint:startCenter];
            [self.animator addBehavior:snap];

            return;
        }

        // otherwise, create UIDynamicItemBehavior that carries on animation from where the gesture left off (notably linear and angular velocity)

        UIDynamicItemBehavior *dynamic = [[UIDynamicItemBehavior alloc] initWithItems:@[gesture.view]];
        [dynamic addLinearVelocity:velocity forItem:gesture.view];
        [dynamic addAngularVelocity:angularVelocity forItem:gesture.view];
        [dynamic setAngularResistance:1.25];

        // when the view no longer intersects with its superview, go ahead and remove it

        typeof(self) __weak weakSelf = self;

        dynamic.action = ^{
            if (!CGRectIntersectsRect(gesture.view.superview.bounds, gesture.view.frame)) {
                [weakSelf.animator removeAllBehaviors];
                [gesture.view removeFromSuperview];

                [[[UIAlertView alloc] initWithTitle:nil message:@"View is gone!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            }
        };
        [self.animator addBehavior:dynamic];

        // add a little gravity so it accelerates off the screen (in case user gesture was slow)

        UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[gesture.view]];
        gravity.magnitude = 0.7;
        [self.animator addBehavior:gravity];
    }
}

- (CGFloat)angleOfView:(UIView *)view
{
    // http://stackoverflow.com/a/2051861/1271826

    return atan2(view.transform.b, view.transform.a);
}

That yields (showing both the snap behavior if you don't drag down, as well as the dynamic behavior if you successfully drag it down):

This is only a shell of a demonstration, but it illustrates using a UIAttachmentBehavior during the pan gesture, using a UISnapBehavior if you want to snap it back if you conclude you want to reverse the gesture's animation, but using UIDynamicItemBehavior to finish the animation of dragging it down, off the screen, but making the transition from the the UIAttachmentBehavior to the final animation as smooth as possible. I also added a little gravity at the same time as that final UIDynamicItemBehavior so that it smoothly accelerates off the screen (so it doesn't take too long).
Customize this as you see fit. Notably, that pan gesture handler is unwieldy enough that I might contemplate creating a custom recognizer to clean up that code. But hopefully this illustrates the basic concepts in using UIKit Dynamics to drag a view off the bottom of the screen.

A: @Rob's answer is great (upvote it!), but I'd remove the manual angular velocity calculations and let UIDynamics do the work with a UIPushBehavior. Just set the target offset of the UIPushBehavior and UIDynamics will do the rotational calculation work for you.
Start with @Rob's same setup:
UIView *viewToDrag = [[UIView alloc] initWithFrame:...];
viewToDrag.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:viewToDrag];

UIGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[viewToDrag addGestureRecognizer:pan];

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

But tweak the gesture recognizer handler to use a UIPushBehavior
- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    static UIAttachmentBehavior *attachment;
    static CGPoint startCenter;

    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.animator removeAllBehaviors];

        startCenter = gesture.view.center;

        // calculate the center offset and anchor point

        CGPoint pointWithinAnimatedView = [gesture locationInView:gesture.view];

        UIOffset offset = UIOffsetMake(pointWithinAnimatedView.x - gesture.view.bounds.size.width / 2.0,
                                       pointWithinAnimatedView.y - gesture.view.bounds.size.height / 2.0);

        CGPoint anchor = [gesture locationInView:gesture.view.superview];

        // create attachment behavior

        attachment = [[UIAttachmentBehavior alloc] initWithItem:gesture.view
                                               offsetFromCenter:offset
                                               attachedToAnchor:anchor];

        // add attachment behavior

        [self.animator addBehavior:attachment];
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        // as user makes gesture, update attachment behavior's anchor point, achieving drag 'n' rotate

        CGPoint anchor = [gesture locationInView:gesture.view.superview];
        attachment.anchorPoint = anchor;
    } else if (gesture.state == UIGestureRecognizerStateEnded) {
        [self.animator removeAllBehaviors];

        CGPoint velocity = [gesture velocityInView:gesture.view.superview];

        // if we aren't dragging it down, just snap it back and quit

        if (fabs(atan2(velocity.y, velocity.x) - M_PI_2) > M_PI_4) {
            UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:gesture.view snapToPoint:startCenter];
            [self.animator addBehavior:snap];

            return;
        }

        // otherwise, create UIPushBehavior that carries on animation from where the gesture left off

        CGFloat velocityMagnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        UIPushBehavior *pushBehavior = [[UIPushBehavior alloc] initWithItems:@[gesture.view] mode:UIPushBehaviorModeInstantaneous];
        pushBehavior.pushDirection = CGVectorMake((velocity.x / 10) , (velocity.y / 10));
        // some constant to limit the speed of the animation
        pushBehavior.magnitude = velocityMagnitude / 35.0;
        CGPoint finalPoint = [gesture locationInView:gesture.view.superview];
        CGPoint center = gesture.view.center;
        [pushBehavior setTargetOffsetFromCenter:UIOffsetMake(finalPoint.x - center.x, finalPoint.y - center.y) forItem:gesture.view];

        // when the view no longer intersects with its superview, go ahead and remove it

        typeof(self) __weak weakSelf = self;

        pushBehavior.action = ^{
            if (!CGRectIntersectsRect(gesture.view.superview.bounds, gesture.view.frame)) {
                [weakSelf.animator removeAllBehaviors];
                [gesture.view removeFromSuperview];

                [[[UIAlertView alloc] initWithTitle:nil message:@"View is gone!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            }
        };
        [self.animator addBehavior:pushBehavior];

        // add a little gravity so it accelerates off the screen (in case user gesture was slow)

        UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[gesture.view]];
        gravity.magnitude = 0.7;
        [self.animator addBehavior:gravity];
    }
}

A: SWIFT 3.0 :
import UIKit

class SwipeToDisMissView: UIView {

var animator : UIDynamicAnimator?

func initSwipeToDismissView(_ parentView:UIView)  {
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(SwipeToDisMissView.panGesture))
    self.addGestureRecognizer(panGesture)
    animator = UIDynamicAnimator(referenceView: parentView)
}

func panGesture(_ gesture:UIPanGestureRecognizer)  {
    var attachment : UIAttachmentBehavior?
    var lastTime = CFAbsoluteTime()
    var lastAngle: CGFloat = 0.0
    var angularVelocity: CGFloat = 0.0

    if gesture.state == .began {
        self.animator?.removeAllBehaviors()
        if let gestureView = gesture.view {
            let pointWithinAnimatedView = gesture.location(in: gestureView)
            let offset = UIOffsetMake(pointWithinAnimatedView.x - gestureView.bounds.size.width / 2.0, pointWithinAnimatedView.y - gestureView.bounds.size.height / 2.0)
            let anchor = gesture.location(in: gestureView.superview!)
            // create attachment behavior
            attachment = UIAttachmentBehavior(item: gestureView, offsetFromCenter: offset, attachedToAnchor: anchor)
            // code to calculate angular velocity (seems curious that I have to calculate this myself, but I can if I have to)
            lastTime = CFAbsoluteTimeGetCurrent()
            lastAngle = self.angleOf(gestureView)
            weak var weakSelf = self
            attachment?.action = {() -> Void in
                let time = CFAbsoluteTimeGetCurrent()
                let angle: CGFloat = weakSelf!.angleOf(gestureView)
                if time > lastTime {
                    angularVelocity = (angle - lastAngle) / CGFloat(time - lastTime)
                    lastTime = time
                    lastAngle = angle
                }
            }
            self.animator?.addBehavior(attachment!)
        }
    }
    else if gesture.state == .changed {
        if let gestureView = gesture.view {
            if let superView = gestureView.superview {
                let anchor = gesture.location(in: superView)
                if let attachment = attachment {
                    attachment.anchorPoint = anchor
                }
            }
        }
    }
    else if gesture.state == .ended {
        if let gestureView = gesture.view {
            let anchor = gesture.location(in: gestureView.superview!)
            attachment?.anchorPoint = anchor
            self.animator?.removeAllBehaviors()
            let velocity = gesture.velocity(in: gestureView.superview!)
            let dynamic = UIDynamicItemBehavior(items: [gestureView])
            dynamic.addLinearVelocity(velocity, for: gestureView)
            dynamic.addAngularVelocity(angularVelocity, for: gestureView)
            dynamic.angularResistance = 1.25
            // when the view no longer intersects with its superview, go ahead and remove it
            weak var weakSelf = self
            dynamic.action = {() -> Void in
                if !gestureView.superview!.bounds.intersects(gestureView.frame) {
                    weakSelf?.animator?.removeAllBehaviors()
                    gesture.view?.removeFromSuperview()
                }
            }
            self.animator?.addBehavior(dynamic)

            let gravity = UIGravityBehavior(items: [gestureView])
            gravity.magnitude = 0.7
            self.animator?.addBehavior(gravity)
        }
    }
}

func angleOf(_ view: UIView) -> CGFloat {
    return atan2(view.transform.b, view.transform.a)
}
}


text:
Q: How to change semantic ui icon colour to defined colour in ReactJs? I use semantic ui for react where I use different icons. One of these icons however must have a different colour.
We can change the colour by props
 <Icon name="play" color="red"/>

Something I really want to do is change the color from a pattern that I created. I have the pattern in a .png and I tried different methods, including:
<Icon name="play" style={{color: url('./path_to_image')}}

But it fails. Any ideas how I could change the colour of an icon to a self defined pattern?
I also found a potential solution where I create the .svg image by myself and then style it but I would love to find something more straightforward rather than 'reinventing the wheel'.

A: It is not possible to accomplish what you are trying to do with props. Additionally, the color css attribute you are trying to apply does not accept a path.
You can probably accomplish this with the icons in Semantic UI but your solution may not work as expected in all browsers. You'll need to know that the icons in Semantic UI are actually a font (from FontAwesome). Therefore, you can't use any SVG solutions unless you bring your own SVG based icon components.
Your best bet will probably be to use -webkit-background-clip: text though not all browsers support this, and you have to use the unofficial prefix.
CSS Tricks has a good tutorial on how to do this. You'll also see in the tutorial that all the other solutions to accomplish this are SVG based.


text:
Q: Is there a way or tool that push cassandra data into AWS for backup purpose? I'm working as cassandra cluster DevOps engr. wanted to know is there a way or tool that push cassandra data into AWS for backup purpose.I have cassandra cluster that is not in AWS. I explored netflix-priam but as per my understanding it needs cassandra to be hosted on AWS itself then it takes backups on EBS. my question is why i need to install cassandra cluster on AWS if i already have on-premise working cassandra. I have also read about cassandra-snapshotter & table-snap code in github,but dont want to use that. So again asking, is there such tool other than tablesnap,cassandra-snapshotter & Netflix-priam ??
Please help
Thanks


text:
Q: How do I use $SECONDS inside a bash script? I want to save the result of the $SECONDS command into a variable, to print time in format HH:MM:SS.
This is what I've tried so far. I tried to print it in different ways and was always getting the result as 0:
time_spent="$SECONDS"
echo "Time: $time_spent"

I want to print time spent in the shell when I close my console. I created a script that runs every time the console was closed.

A: If you're sure that $SECONDS will be less than 1 day (i.e. 86400 seconds), then GNU core-utils date does a pretty good job of the required formatting:
$ date -ud "@$SECONDS" "+Time elapsed: %H:%M:%S"
Time elapsed: 00:32:05
$

A: You've referenced the bash internal variable SECONDS (which outputs the number of seconds elapsed since the current instance of shell is invoked) and saved the value as another variable time_spent. Now, after that every time you check the value of variable time_spent, you would get the same value -- the saved one, at the time of expansion of SECONDS.
To dynamically get SECONDS, you should reference $SECONDS directly rather than using an intermediate variable:
echo "Time: $SECONDS"

If you insist on using an intermediate variable, make sure to do the expansion of $SECONDS every time.

Regarding the value of SECONDS being 0, you can easily reproduce this:
% bash -c 'echo $SECONDS'
0

The point is: when you're calculating the value, it's not a second yet, so the value is being 0, correctly.

A: Here is a quick one that gives hours minutes and seconds since the shell has been opened:
~$ cat how_long_open
#!/bin/bash

time=$SECONDS
printf '%dh:%dm:%ds\n' $(($time/3600)) $(($time%3600/60)) $(($time%60))

Since scripts run in a subshell, the best way to get output is to source the script instead of calling it.
Examples:
Without sourcing the script
~$ ./how_long_open
0h:0m:0s

With sourcing the script
~$ source ./how_long_open
1h:24m:40s

Hope this helps!

A: To get $SECONDS into HH:MM:SS format you will need to do some (integer) math:
secs=$SECONDS
hrs=$(( secs/3600 )); mins=$(( (secs-hrs*3600)/60 )); secs=$(( secs-hrs*3600-mins*60 ))

printf 'Time spent: %02d:%02d:%02d\n' $hrs $mins $secs
Time spent: 431:48:03