问:
Implement an scroll to select an item ListView
I want to use an ListView where you scroll the list to select an item.
It should be like a Seekbar but the thumb should be fixed and you must use the bar to adjust it. One problem am facing is, I have no idea how this kind of widget is called, making it hard for me to search. So I made this image below to give you an better idea. And to be fair, I don't even know if this is the right title for this kind of feature.

I usually see this kind of interface in clock setting (see below image)

答:
Reference scroll horizontal at https://stackoverflow.com/a/38411582/5887320 by use RecyclerView instead of ListView.

This is my customize code to get virtical scroll :

1.dimens.xml

```<code><dimen name="item_dob_width">100dp</dimen>
<dimen name="item_dob_height">50dp</dimen>
</code>```

2.recyclerview_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">

    <TextView
        android:id="@+id/tv_year"
        android:layout_width="@dimen/item_dob_width"
        android:layout_height="@dimen/item_dob_height"
        android:textColor="@android:color/white"
        android:background="@android:color/darker_gray"
        android:textSize="28sp"
        android:gravity="center"/>

</LinearLayout>
</code>```

3.recyclerview.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"/>

</LinearLayout>
</code>```

4.MainActivity.java

```<code>import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;

public class MainActivity extends Activity{

private static final String TAG = MainActivity.class.getSimpleName();

public float firstItemHeightDate;
public float paddingDate;
public float itemHeightDate;
public int allPixelsDate;
public int finalHeightDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates = new ArrayList<>();

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

    getRecyclerviewDate();
}

public void getRecyclerviewDate() {
    final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.recycler_view);
    if (recyclerViewDate != null) {
        recyclerViewDate.postDelayed(new Runnable() {
            @Override
            public void run() {
                setDateValue();
            }
        }, 300);
        /*recyclerViewDate.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
                setDateValue();
            }
        }, 5000);*/
    }
    ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
    vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
            finalHeightDate = recyclerViewDate.getMeasuredHeight();
            itemHeightDate = getResources().getDimension(R.dimen.item_dob_height);
            paddingDate = (finalHeightDate - itemHeightDate) / 2;
            firstItemHeightDate = paddingDate;
            allPixelsDate = 0;

            final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
            dateLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerViewDate.setLayoutManager(dateLayoutManager);
            recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    synchronized (this) {
                        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                            calculatePositionAndScrollDate(recyclerView);
                        }
                    }

                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    allPixelsDate += dy;
                }
            });
            if (labelerDates == null) {
                labelerDates = new ArrayList<>();
            }
            genLabelerDate();
            dateAdapter = new DateAdapter(labelerDates, (int) firstItemHeightDate);
            recyclerViewDate.setAdapter(dateAdapter);
            dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
            return true;
        }
    });
}

private void genLabelerDate() {
    for (int i = 0; i < 32; i++) {
        LabelerDate labelerDate = new LabelerDate();
        labelerDate.setNumber(Integer.toString(i));
        labelerDates.add(labelerDate);

        if (i == 0 || i == 31) {
            labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
        } else {
            labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
        }
    }
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/

private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
    int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);

    if (expectedPositionDate == -1) {
        expectedPositionDate = 0;
    } else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
        expectedPositionDate--;
    }
    scrollListToPositionDate(recyclerView, expectedPositionDate);

}

/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
    float targetScrollPosDate = expectedPositionDate * itemHeightDate + firstItemHeightDate - paddingDate;
    float missingPxDate = targetScrollPosDate - allPixelsDate;
    if (missingPxDate != 0) {
        //recyclerView.smoothScrollBy((int) missingPxDate, 0);//horizontal
          recyclerView.smoothScrollBy(0, (int) missingPxDate);//virtical
    }
    setDateValue();
}

//
private void setDateValue() {
    int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
    int setColorDate = expectedPositionDateColor + 1;
    //set color here
    dateAdapter.setSelecteditem(setColorDate);
}

public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
    private ArrayList<LabelerDate> dateDataList;

    private static final int VIEW_TYPE_PADDING = 1;
    private static final int VIEW_TYPE_ITEM = 2;
    private int paddingHeightDate = 0;

    private int selectedItem = -1;

    public DateAdapter(ArrayList<LabelerDate> dateData, int paddingHeightDate) {
        this.dateDataList = dateData;
        this.paddingHeightDate = paddingHeightDate;

    }

    @Override
    public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ITEM) {
            final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
                    parent, false);
            return new DateViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
                    parent, false);

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
            layoutParams.height = paddingHeightDate;
            view.setLayoutParams(layoutParams);
            return new DateViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(DateViewHolder holder, int position) {
        LabelerDate labelerDate = dateDataList.get(position);
        if (getItemViewType(position) == VIEW_TYPE_ITEM) {
            holder.tvDate.setText(labelerDate.getNumber());
            holder.tvDate.setVisibility(View.VISIBLE);

            Log.d(TAG, "default " + position + ", selected " + selectedItem);
            if (position == selectedItem) {
                Log.d(TAG, "center" + position);
                holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
                holder.tvDate.setTextSize(35);

            } else {
                holder.tvDate.setTextColor(Color.BLACK);
                holder.tvDate.setTextSize(18);
            }
        } else {
            holder.tvDate.setVisibility(View.INVISIBLE);
        }
    }

    public void setSelecteditem(int selecteditem) {
        this.selectedItem = selecteditem;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return dateDataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        LabelerDate labelerDate = dateDataList.get(position);
        if (labelerDate.getType() == VIEW_TYPE_PADDING) {
            return VIEW_TYPE_PADDING;
        } else {
            return VIEW_TYPE_ITEM;
        }

    }

    public class DateViewHolder extends RecyclerView.ViewHolder {
        public TextView tvDate;

        public DateViewHolder(View itemView) {
            super(itemView);
            tvDate = (TextView) itemView.findViewById(R.id.tv_year);
        }
    }
}

private class LabelerDate {
    private int type;
    private String number;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}
}
</code>```

Body:
Reference scroll horizontal at https://stackoverflow.com/a/38411582/5887320 by use RecyclerView instead of ListView.

This is my customize code to get virtical scroll :

1.dimens.xml

<dimen name="item_dob_width">100dp</dimen>
<dimen name="item_dob_height">50dp</dimen>

2.recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">

    <TextView
        android:id="@+id/tv_year"
        android:layout_width="@dimen/item_dob_width"
        android:layout_height="@dimen/item_dob_height"
        android:textColor="@android:color/white"
        android:background="@android:color/darker_gray"
        android:textSize="28sp"
        android:gravity="center"/>

</LinearLayout>

3.recyclerview.xml

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"/>

</LinearLayout>

4.MainActivity.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.util.ArrayList;

public class MainActivity extends Activity{

private static final String TAG = MainActivity.class.getSimpleName();

public float firstItemHeightDate;
public float paddingDate;
public float itemHeightDate;
public int allPixelsDate;
public int finalHeightDate;
private DateAdapter dateAdapter;
private ArrayList<LabelerDate> labelerDates = new ArrayList<>();

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

    getRecyclerviewDate();
}

public void getRecyclerviewDate() {
    final RecyclerView recyclerViewDate = (RecyclerView) findViewById(R.id.recycler_view);
    if (recyclerViewDate != null) {
        recyclerViewDate.postDelayed(new Runnable() {
            @Override
            public void run() {
                setDateValue();
            }
        }, 300);
        /*recyclerViewDate.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerViewDate.smoothScrollToPosition(dateAdapter.getItemCount()-1);
                setDateValue();
            }
        }, 5000);*/
    }
    ViewTreeObserver vtoDate = recyclerViewDate.getViewTreeObserver();
    vtoDate.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            recyclerViewDate.getViewTreeObserver().removeOnPreDrawListener(this);
            finalHeightDate = recyclerViewDate.getMeasuredHeight();
            itemHeightDate = getResources().getDimension(R.dimen.item_dob_height);
            paddingDate = (finalHeightDate - itemHeightDate) / 2;
            firstItemHeightDate = paddingDate;
            allPixelsDate = 0;

            final LinearLayoutManager dateLayoutManager = new LinearLayoutManager(getApplicationContext());
            dateLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerViewDate.setLayoutManager(dateLayoutManager);
            recyclerViewDate.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    synchronized (this) {
                        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                            calculatePositionAndScrollDate(recyclerView);
                        }
                    }

                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    allPixelsDate += dy;
                }
            });
            if (labelerDates == null) {
                labelerDates = new ArrayList<>();
            }
            genLabelerDate();
            dateAdapter = new DateAdapter(labelerDates, (int) firstItemHeightDate);
            recyclerViewDate.setAdapter(dateAdapter);
            dateAdapter.setSelecteditem(dateAdapter.getItemCount() - 1);
            return true;
        }
    });
}

private void genLabelerDate() {
    for (int i = 0; i < 32; i++) {
        LabelerDate labelerDate = new LabelerDate();
        labelerDate.setNumber(Integer.toString(i));
        labelerDates.add(labelerDate);

        if (i == 0 || i == 31) {
            labelerDate.setType(DateAdapter.VIEW_TYPE_PADDING);
        } else {
            labelerDate.setType(DateAdapter.VIEW_TYPE_ITEM);
        }
    }
}
/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/

private void calculatePositionAndScrollDate(RecyclerView recyclerView) {
    int expectedPositionDate = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);

    if (expectedPositionDate == -1) {
        expectedPositionDate = 0;
    } else if (expectedPositionDate >= recyclerView.getAdapter().getItemCount() - 2) {
        expectedPositionDate--;
    }
    scrollListToPositionDate(recyclerView, expectedPositionDate);

}

/* this if most important, if expectedPositionDate < 0 recyclerView will return to nearest item*/
private void scrollListToPositionDate(RecyclerView recyclerView, int expectedPositionDate) {
    float targetScrollPosDate = expectedPositionDate * itemHeightDate + firstItemHeightDate - paddingDate;
    float missingPxDate = targetScrollPosDate - allPixelsDate;
    if (missingPxDate != 0) {
        //recyclerView.smoothScrollBy((int) missingPxDate, 0);//horizontal
          recyclerView.smoothScrollBy(0, (int) missingPxDate);//virtical
    }
    setDateValue();
}

//
private void setDateValue() {
    int expectedPositionDateColor = Math.round((allPixelsDate + paddingDate - firstItemHeightDate) / itemHeightDate);
    int setColorDate = expectedPositionDateColor + 1;
    //set color here
    dateAdapter.setSelecteditem(setColorDate);
}

public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateViewHolder> {
    private ArrayList<LabelerDate> dateDataList;

    private static final int VIEW_TYPE_PADDING = 1;
    private static final int VIEW_TYPE_ITEM = 2;
    private int paddingHeightDate = 0;

    private int selectedItem = -1;

    public DateAdapter(ArrayList<LabelerDate> dateData, int paddingHeightDate) {
        this.dateDataList = dateData;
        this.paddingHeightDate = paddingHeightDate;

    }

    @Override
    public DateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ITEM) {
            final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
                    parent, false);
            return new DateViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,
                    parent, false);

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
            layoutParams.height = paddingHeightDate;
            view.setLayoutParams(layoutParams);
            return new DateViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(DateViewHolder holder, int position) {
        LabelerDate labelerDate = dateDataList.get(position);
        if (getItemViewType(position) == VIEW_TYPE_ITEM) {
            holder.tvDate.setText(labelerDate.getNumber());
            holder.tvDate.setVisibility(View.VISIBLE);

            Log.d(TAG, "default " + position + ", selected " + selectedItem);
            if (position == selectedItem) {
                Log.d(TAG, "center" + position);
                holder.tvDate.setTextColor(Color.parseColor("#76FF03"));
                holder.tvDate.setTextSize(35);

            } else {
                holder.tvDate.setTextColor(Color.BLACK);
                holder.tvDate.setTextSize(18);
            }
        } else {
            holder.tvDate.setVisibility(View.INVISIBLE);
        }
    }

    public void setSelecteditem(int selecteditem) {
        this.selectedItem = selecteditem;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return dateDataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        LabelerDate labelerDate = dateDataList.get(position);
        if (labelerDate.getType() == VIEW_TYPE_PADDING) {
            return VIEW_TYPE_PADDING;
        } else {
            return VIEW_TYPE_ITEM;
        }

    }

    public class DateViewHolder extends RecyclerView.ViewHolder {
        public TextView tvDate;

        public DateViewHolder(View itemView) {
            super(itemView);
            tvDate = (TextView) itemView.findViewById(R.id.tv_year);
        }
    }
}

private class LabelerDate {
    private int type;
    private String number;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}
}


来源: stackexchange

问:
Pass a string to method CREATE RECORD in 4D
Can i pass a string variable to the 4D CREATE RECORD method ? or any other method i just need to set the name table as a variable.
I already tried to pass a string variable but as the method only accepts table object i can't find any way to do that</p>

答:
You can do this with a pointer. Anywhere 4D expects a table you can use a dereferenced pointer to a table.

You can get a pointer to a table in a few ways:

```<code>C_Pointer($pTable)
$pTable:=Table(4) // where 4 is the table number; command returns a pointer to the table
// -OR-
$pTable:=->[SomeTable] // directly setting a pointer to the table

CREATE RECORD($pTable->) // dereferenced pointer as parameter
// do some work here, setting field values
SAVE RECORD($pTable->)
</code>```

Depending on how you are choosing the variable table name you may need some code to tie the text to the table or table number. A method that took the text and set a pointer to the table would do the trick.

Update:
Incorporating what @TomB suggested (I wasn't aware of that command), I would do something like this (though in real code I'd create a method that returned a pointer to the table rather than running Create Record in the If statement). Where $tSomeTableName is the string variable you are working with.

```<code>ARRAY TEXT($atTableNames;0)
ARRAY LONGINT($aLTableNumbers;0)
GET TABLE TITLES($atTableNames;$aLTableNumbers)

C_LONGINT($LFind)
$LFind:=Find in array($atTableNames;$tSomeTableName)

C_POINTER($pTable)
If ($LFind>0)
    $pTable:=Table($aLTableNumbers{$LFind})

    CREATE RECORD($pTable->)
      // do some work
    SAVE RECORD($pTable->)

Else
    ALERT("Table name "+$tSomeTableName+" not recognized.")
End if
</code>```

I prefer this to Execute Formula because it handles cases where the table name in the text variable is not a valid table name in the database.

ContentLicense: CC BY-SA 3.0

Body:
You can do this with a pointer. Anywhere 4D expects a table you can use a dereferenced pointer to a table.

You can get a pointer to a table in a few ways:

C_Pointer($pTable)
$pTable:=Table(4) // where 4 is the table number; command returns a pointer to the table
// -OR-
$pTable:=->[SomeTable] // directly setting a pointer to the table

CREATE RECORD($pTable->) // dereferenced pointer as parameter
// do some work here, setting field values
SAVE RECORD($pTable->)

Depending on how you are choosing the variable table name you may need some code to tie the text to the table or table number. A method that took the text and set a pointer to the table would do the trick.

Update:
Incorporating what @TomB suggested (I wasn't aware of that command), I would do something like this (though in real code I'd create a method that returned a pointer to the table rather than running Create Record in the If statement). Where $tSomeTableName is the string variable you are working with.

ARRAY TEXT($atTableNames;0)
ARRAY LONGINT($aLTableNumbers;0)
GET TABLE TITLES($atTableNames;$aLTableNumbers)

C_LONGINT($LFind)
$LFind:=Find in array($atTableNames;$tSomeTableName)

C_POINTER($pTable)
If ($LFind>0)
    $pTable:=Table($aLTableNumbers{$LFind})

    CREATE RECORD($pTable->)
      // do some work
    SAVE RECORD($pTable->)

Else
    ALERT("Table name "+$tSomeTableName+" not recognized.")
End if

I prefer this to Execute Formula because it handles cases where the table name in the text variable is not a valid table name in the database.


问:
String of ISO-8601 datetime to number of seconds in Java
How do I convert a string of ISO-8601 datetime (ex: 2012-05-31T13:48:04Z) to number of seconds( 10 digit integer) using Java?

答:
tl;dr

```<code>Instant.parse( "2012-05-31T13:48:04Z" )
       .getEpochSecond()
</code>```

1338472084

See this code run live at IdeOne.com.

Using java.time

Much easier with the java.time classes that supplant the troublesome old legacy date-time classes.

Easy to parse your input string as the java.time classes use ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

```<code>Instant instant = Instant.parse( "2012-05-31T13:48:04Z" ) ;
</code>```

I am guessing that by “seconds” you meant the number of seconds elapsed since the beginning of 1970 UTC (1970-01-01T00:00:00Z). The Instant class can tell you the number of seconds since that Unix epoch.

```<code>long secondsSinceEpoch = instant.getEpochSecond() ;
</code>```

1338472084

Beware of data loss, obviously. You are ignoring any fractional second that may be present in your date-time value.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
tl;dr

Instant.parse( "2012-05-31T13:48:04Z" )
       .getEpochSecond()

1338472084

See this code run live at IdeOne.com.

Using java.time

Much easier with the java.time classes that supplant the troublesome old legacy date-time classes.

Easy to parse your input string as the java.time classes use ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.parse( "2012-05-31T13:48:04Z" ) ;

I am guessing that by “seconds” you meant the number of seconds elapsed since the beginning of 1970 UTC (1970-01-01T00:00:00Z). The Instant class can tell you the number of seconds since that Unix epoch.

long secondsSinceEpoch = instant.getEpochSecond() ;

1338472084

Beware of data loss, obviously. You are ignoring any fractional second that may be present in your date-time value.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
GitBook document file conversion
i have created a gitbook account and working on a documentation, i have some difficulties in converting my work into formats(pdf, mobi and epub). Help me out
. i have the link for my work but how to convert it into a format </p>

答:
https://calibre-ebook.com/, Calibre is what you want

Calibre can convert (pdf, epubs, mobi, etc...) to any other book format(pdf, azw3, epub, mobi, even html)

Title: GitBook document file conversion


问:
Regex java issue code not working
I have an issue with a little regex code I wrote. The code basically checks my "longString" which contains the string that's being checked and outputs the words in the string that matches the regex.

```<code>import java.util.regex.*;

public class regexPractice
{

    public static void main(String[] args) {
        String  longString = " Derek Banas CA ";

        regexChecker(longString, "\\s[A-Za-z]{2,20}\\s");
    }

    public static void regexChecker(String theregex, String stringCheck) {
        //theregex is the regex your searching for

        Pattern Checkregex = Pattern.compile(theregex);

        Matcher regexMatcher = Checkregex.matcher(stringCheck);

        while (regexMatcher.find()) { //kicks out all the matches for you
            if (regexMatcher.group().length() != 0) {
                System.out.println(regexMatcher.group().trim());
                //trim gets rid of all the white space
            }
        }
    }
}
</code>```

When I run the code nothing shows up not even an error message. I rechecked my code and didn't find any errors.

By the way, I'm using android studio.

答: Your regex is incorrect, because you are using a-Z which should be 'z' (the normal case).</p>

Title: Regex java issue code not working

Body:
I have an issue with a little regex code I wrote. The code basically checks my "longString" which contains the string that's being checked and outputs the words in the string that matches the regex.

import java.util.regex.*;

public class regexPractice
{

    public static void main(String[] args) {
        String  longString = " Derek Banas CA ";

        regexChecker(longString, "\\s[A-Za-z]{2,20}\\s");
    }

    public static void regexChecker(String theregex, String stringCheck) {
        //theregex is the regex your searching for

        Pattern Checkregex = Pattern.compile(theregex);

        Matcher regexMatcher = Checkregex.matcher(stringCheck);

        while (regexMatcher.find()) { //kicks out all the matches for you
            if (regexMatcher.group().length() != 0) {
                System.out.println(regexMatcher.group().trim());
                //trim gets rid of all the white space
            }
        }
    }
}

When I run the code nothing shows up not even an error message. I rechecked my code and didn't find any errors.

By the way, I'm using android studio.


问:
SQL - Order by time, then text on beginning
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

```<code>TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
</code>```

When I use ORDER BY TimeSched, it returns this result:

```<code>TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day
</code>```

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

```<code>TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
</code>```

答:
Here is the answer to my question.</p>

```<code>SELECT CASE TimeSched WHEN 'Restday' THEN 1 WHEN 'No Schedule' THEN 2 ELSE 3 END
AS TimeSked, TimeSched ORDER BY TimeSked, TimeSched
</code>```

Body:
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM

When I use ORDER BY TimeSched, it returns this result:

TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM

Body:
Here is the answer to my question.

SELECT CASE TimeSched WHEN 'Restday' THEN 1 WHEN 'No Schedule' THEN 2 ELSE 3 END
AS TimeSked, TimeSched ORDER BY TimeSked, TimeSched


问:
Swift Timer App
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code</p>

```<code>@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}
</code>```

答:
If your start method runs while a timer is already active, you create a second timer. Now you have two timers calling the same action, which accounts for your problem. Scheduled timers are retained by their run loops, so even though you don't have a reference to the old timer, it's still there.

At a minimum you need to either invalidate the old timer or else just keep using the one you have. But there are some things that would help make the code better:

Your timer attribute should probably be a Swift optional. Initializing it as Timer() doesn't do anything useful. It would make more sense if timer could be nil when no timer should be running.

You should probably disable your "start" button when a timer is running. It doesn't make sense for it to be active when the timer has already started. You could do this by setting up an IBOutlet for the button and changing the value if the button's isEnabled property.

Title: Swift Timer App

Body:
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code

@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}


问:
Merge JSON records using Python
I have a huge json file as follows,

```<code>{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
</code>```

I need to merge the two and obtain the desired result as

```<code>{"id": "KA88457",
 "name": "Steven",
 "phone":"+6590876589",
 "fax":["+6563323248"],
 "email":"steve@alexandra.com"}
</code>```

I checked online but I was able to find only merging two json files in python. Can you please help to in merging these type of records using python.

答:
Python dictionaries have a .update() method, which can also be used for your situation. It is used to update the original dict to include the changes or addition from the second dict.

```<code>first_dict={"id": "KA88457","name": "Steven", "phone":"+6590876589"}
second_dict={"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
first_dict.update(second_dict)
print(first_dict)
</code>```

Output:

```<code>{'id': 'KA88457', 'name': 'Steven', 'phone': '+6590876589', 'fax': ['+6563323248'], 'email': 'steve@alexandra.com'}
</code>```

Title: Merge JSON records using Python

Body:
I have a huge json file as follows,

{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}

I need to merge the two and obtain the desired result as

{"id": "KA88457",
 "name": "Steven",
 "phone":"+6590876589",
 "fax":["+6563323248"],
 "email":"steve@alexandra.com"}

I checked online but I was able to find only merging two json files in python. Can you please help to in merging these type of records using python.

Body:
Python dictionaries have a .update() method, which can also be used for your situation. It is used to update the original dict to include the changes or addition from the second dict.

first_dict={"id": "KA88457","name": "Steven", "phone":"+6590876589"}
second_dict={"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
first_dict.update(second_dict)
print(first_dict)

Output:

{'id': 'KA88457', 'name': 'Steven', 'phone': '+6590876589', 'fax': ['+6563323248'], 'email': 'steve@alexandra.com'}


问:
How can I get the checked status of a checkbox
I have a gridview parameter in my asp.net program as follows:

Name: row.Cells[5].Controls[0]

Value: (Text="" Checked=true)

type: System.Web.UI.WebControls.CheckBox

How can I get the Checked status of such parameter?

答:
Here...</p>

```<code>(CType(gridview.Rows(0).Cells(5).Controls(0), CheckBox).Checked)
</code>```

Body:
Here...

(CType(gridview.Rows(0).Cells(5).Controls(0), CheckBox).Checked)


问:
C# DateTime format in Arrays
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.</p>

```<code>private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}
</code>```

答:
Try this

```<code>private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989
    DateTime date;
    if (!DateTime.TryParseExact(sDate, new string[] { "MM/dd/yyyy", "M/dd/yyyy", "MM/d/yyyy" }, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out date))
    {
        return string.Empty;
    }
    return date.ToString("MM-dd-yyyy");
}
</code>```

This would also work if you just wanted to use a standard TryParse:

```<code>private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989
    var usCultureInfo = System.Globalization.CultureInfo.GetCultureInfo(0x0409);
    DateTime date;
    if (!DateTime.TryParse(sDate, usCultureInfo, System.Globalization.DateTimeStyles.AdjustToUniversal, out date))
    {
        return string.Empty;
    }
    return date.ToString("MM-dd-yyyy");
}
</code>```

Note that these examples will return an empty string when the date isn't understood.

But do consider using the MySQL driver and parameterized queries since this will make your code safer and it will be easier to work with.

Title: C# DateTime format in Arrays

Body:
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.

private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}

Body:
Try this

private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989
    DateTime date;
    if (!DateTime.TryParseExact(sDate, new string[] { "MM/dd/yyyy", "M/dd/yyyy", "MM/d/yyyy" }, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out date))
    {
        return string.Empty;
    }
    return date.ToString("MM-dd-yyyy");
}

This would also work if you just wanted to use a standard TryParse:

private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989
    var usCultureInfo = System.Globalization.CultureInfo.GetCultureInfo(0x0409);
    DateTime date;
    if (!DateTime.TryParse(sDate, usCultureInfo, System.Globalization.DateTimeStyles.AdjustToUniversal, out date))
    {
        return string.Empty;
    }
    return date.ToString("MM-dd-yyyy");
}

Note that these examples will return an empty string when the date isn't understood.

But do consider using the MySQL driver and parameterized queries since this will make your code safer and it will be easier to work with.


问:
Don't understand why replace() method is not working as expected
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

```<code>function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}
</code>```

All of the example test cases work except for the following:

```<code>Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''
</code>```

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?

答:
You can use substring. Your replace replaces and replaces the first occurrence of the last character in the words -- definitely what you're after:

```<code>function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.length ? a.substring(0, a.length - 2) + a[a.length - 1].toLowerCase() : a;
  });
  return words.join(' ');
}
</code>```

Body:
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}

All of the example test cases work except for the following:

Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?

Body:
You can use substring. Your replace replaces and replaces the first occurrence of the last character in the words -- definitely what you're after:

function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.length ? a.substring(0, a.length - 2) + a[a.length - 1].toLowerCase() : a;
  });
  return words.join(' ');
}


问:
Prevent mutually recursive execution of triggers?
Suppose you have the tables Presentations and Events. When a presentation is saved and contains basic event information, such as location and date, an event will be created automatically using a trigger. (I'm afraid it's impossible for technical reasons to simply keep the data at one place and use a view.) In addition, when changing this information later on in the presentation, the trigger will copy the updates over to the event as well, like so:

```<code>CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
    UPDATE Events
    SET Events.Date = Presentations.Date,
        Events.Location = Presentations.Location
    FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
    WHERE Presentations.ID IN (SELECT ID FROM inserted)
END
</code>```

Now, the customer wants it so that, if a user ever changes the information in the event, it should go back to the presentation as well. For obvious reasons, I can't do the reverse:

```<code>CREATE TRIGGER update_events
ON Events
AFTER UPDATE
AS
BEGIN
    UPDATE Presentations
    SET Presentations.Date = Events.Date,
        Presentations.Location = Events.Location
    FROM Events INNER JOIN Presentations ON Events.PresentationID = Presentations.ID
    WHERE Events.ID IN (SELECT ID FROM inserted)
END
</code>```

After all, this would cause each trigger to fire after each other. What I could do is add a column last_edit_by to both tables, containing a user ID. If filled by the trigger with a special invalid ID (say, by making all user IDs of actual persons positive, but user IDs of scripts negative), I could use that as an exit condition:

```<code>    AND last_edit_by >= 0
</code>```

This might work, but what I'd like to do is indicate to the SQL server that, within a transaction, a trigger should only fire once. Is there a way to check this? Or perhaps to check that a table has already been affected by a trigger?

Answer thanks to Steve Robbins:

Just wrap the potentially nested UPDATE statements in an IF condition checking for trigger_nestlevel(). For example:

```<code>CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
    IF trigger_nestlevel() < 2
        UPDATE Events
        SET Events.Date = Presentations.Date,
            Events.Location = Presentations.Location
        FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
        WHERE Presentations.ID IN (SELECT ID FROM inserted)
END
</code>```

Note that trigger_nestlevel() appears to be 1-based, not 0-based. If you want each of the two triggers to execute once, but not more often, just check for trigger_nestlevel() < 3 in both triggers.

答:
I'm not sure about doing it per transaction, but do you need nested triggers switched on for other parts? If you switch them off on the server then a trigger won't fire from another trigger updating a table.

EDIT (answer from the comments): You will need to alter trigger A to use TRIGGER_NESTLEVEL

OwnerDisplayName: Sören Kuklau

ContentLicense: CC BY-SA 2.5

Body:
Suppose you have the tables Presentations and Events. When a presentation is saved and contains basic event information, such as location and date, an event will be created automatically using a trigger. (I'm afraid it's impossible for technical reasons to simply keep the data at one place and use a view.) In addition, when changing this information later on in the presentation, the trigger will copy the updates over to the event as well, like so:

CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
    UPDATE Events
    SET Events.Date = Presentations.Date,
        Events.Location = Presentations.Location
    FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
    WHERE Presentations.ID IN (SELECT ID FROM inserted)
END

Now, the customer wants it so that, if a user ever changes the information in the event, it should go back to the presentation as well. For obvious reasons, I can't do the reverse:

CREATE TRIGGER update_events
ON Events
AFTER UPDATE
AS
BEGIN
    UPDATE Presentations
    SET Presentations.Date = Events.Date,
        Presentations.Location = Events.Location
    FROM Events INNER JOIN Presentations ON Events.PresentationID = Presentations.ID
    WHERE Events.ID IN (SELECT ID FROM inserted)
END

After all, this would cause each trigger to fire after each other. What I could do is add a column last_edit_by to both tables, containing a user ID. If filled by the trigger with a special invalid ID (say, by making all user IDs of actual persons positive, but user IDs of scripts negative), I could use that as an exit condition:

    AND last_edit_by >= 0

This might work, but what I'd like to do is indicate to the SQL server that, within a transaction, a trigger should only fire once. Is there a way to check this? Or perhaps to check that a table has already been affected by a trigger?

Answer thanks to Steve Robbins:

Just wrap the potentially nested UPDATE statements in an IF condition checking for trigger_nestlevel(). For example:

CREATE TRIGGER update_presentations
ON Presentations
AFTER UPDATE
AS
BEGIN
    IF trigger_nestlevel() < 2
        UPDATE Events
        SET Events.Date = Presentations.Date,
            Events.Location = Presentations.Location
        FROM Presentations INNER JOIN Events ON Presentations.EventID = Events.ID
        WHERE Presentations.ID IN (SELECT ID FROM inserted)
END

Note that trigger_nestlevel() appears to be 1-based, not 0-based. If you want each of the two triggers to execute once, but not more often, just check for trigger_nestlevel() < 3 in both triggers.

LastEditorDisplayName: Sören Kuklau

OwnerDisplayName: Steve Robbins

LastEditorDisplayName: splattne


答:
I think what you need to do is invalidate if there is a timer running</p>

```<code>@IBAction func start(_ sender: AnyObject) {
    if (timer) {
        timer.invalidate()
    }
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
</code>```

Title: Swift Timer App

Body:
I think what you need to do is invalidate if there is a timer running

@IBAction func start(_ sender: AnyObject) {
    if (timer) {
        timer.invalidate()
    }
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}


问:
IntelliJ: Some classes have changed message
The following message is shown with regards to the SlottingTest2 file:

I know I have not changed any other file than SlottingTest2.java (at least not intentionally). So what does this message mean, and what might trigger it? Could it be referring to changes others have made in an upstream Git repo?

答:
You probably have a debug session running. After you have updated and recompiled (possibly automatically) your file , Intellij suggests to reload the updated version of your .class into your debugging session.

To get rid of the warning, you can either make it automatic or disabled using the following setting:


问:
What does $ sign at the end of function name indicate?
Here is the code I'm reviewing...</p>

```<code>import { Observable } from 'rxjs/Rx';
// reducer
import { playerRegister, PlayerState } from './player';
export function getPlayer$ (state$: Observable<MyAppState>): Observable<PlayerState> {
  return state$.select(state => state.player);
};
</code>```

答:
Syntactically, the dollar ($) character has no special meaning in JavaScript identifiers.

It is, however, sometimes used by convention to indicate that a variable holds an Observable or that a function will return an Observable.

ContentLicense: CC BY-SA 4.0

Body:
Here is the code I'm reviewing...

import { Observable } from 'rxjs/Rx';
// reducer
import { playerRegister, PlayerState } from './player';
export function getPlayer$ (state$: Observable<MyAppState>): Observable<PlayerState> {
  return state$.select(state => state.player);
};


问:
Riemann sum equations
I have an equation for finding the mid point value for the Riemann sum, but it is not providing the correct value for the midpoint when entering coefficients 3, 4, 0 and upper and lower limits of -1 and 1 with 10 rectangles.

```<code>float getMidPoint(int final, int initial, int rectangle, int coefficient1, int coefficient2, int coefficient3)
{
    float deltaX;
    float sumMidPoint;
    float f_X;
    float x;
    x = initial;
    deltaX = (final - initial) / rectangle;
    while(x < final)
    {
        f_X = pow((coefficient1 * x), 2) + (coefficient2 * x) + coefficient3;

        sumMidPoint += f_X * deltaX;
        x = x + deltaX;
    }
    return (sumMidPoint);
}
</code>```

I am not sure why I am not getting the correct value for sumMidPoint. The test case has the sumMidPoint = 1.980000 sq. units

答:
Two issues:

final, initial and rectangle are all integers, therefore you're making an integer division:

(final - initial) / rectangle = 2/20 = 0.1 in float but 0 in int

to correct, set at least one of them as float, but better both:

```<code>float final, float initial
</code>```

Your second error is in the formula: 3x^2 is 3 * pow(x, 2). You wrote (3x)^2.

Also, to be safe, don't forget to initialize your sumMidPoint variable before using it:

float sumMidPoint = 0;

Here is my final version of the code:

```<code>#include <stdio.h>
#include <math.h>

float getMidPoint(float final, int initial, int rectangle, int   coefficient1, int coefficient2, int coefficient3) {
    float deltaX = (final - initial) / rectangle;
    float sumMidPoint = 0;
    float f_X;
    float x = initial + deltaX / 2;

    for(int i=0; i< rectangle; i++)
    {
        f_X = (coefficient1 * pow( x, 2)) + (coefficient2 * x) + coefficient3;

        sumMidPoint += f_X * deltaX;
        x = x + deltaX;
    }
    return(sumMidPoint);

}

int main() {
    printf("Result: %f\n", getMidPoint(1, -1, 10, 3, 4, 0));
    return(0);
}
</code>```

Output:
Result: 1.980000

Title: Riemann sum equations

Body:
I have an equation for finding the mid point value for the Riemann sum, but it is not providing the correct value for the midpoint when entering coefficients 3, 4, 0 and upper and lower limits of -1 and 1 with 10 rectangles.

float getMidPoint(int final, int initial, int rectangle, int coefficient1, int coefficient2, int coefficient3)
{
    float deltaX;
    float sumMidPoint;
    float f_X;
    float x;
    x = initial;
    deltaX = (final - initial) / rectangle;
    while(x < final)
    {
        f_X = pow((coefficient1 * x), 2) + (coefficient2 * x) + coefficient3;

        sumMidPoint += f_X * deltaX;
        x = x + deltaX;
    }
    return (sumMidPoint);
}

I am not sure why I am not getting the correct value for sumMidPoint. The test case has the sumMidPoint = 1.980000 sq. units

Body:
Two issues:

final, initial and rectangle are all integers, therefore you're making an integer division:

(final - initial) / rectangle = 2/20 = 0.1 in float but 0 in int

to correct, set at least one of them as float, but better both:

float final, float initial

Your second error is in the formula: 3x^2 is 3 * pow(x, 2). You wrote (3x)^2.

Also, to be safe, don't forget to initialize your sumMidPoint variable before using it:

float sumMidPoint = 0;

Here is my final version of the code:

#include <stdio.h>
#include <math.h>

float getMidPoint(float final, int initial, int rectangle, int   coefficient1, int coefficient2, int coefficient3) {
    float deltaX = (final - initial) / rectangle;
    float sumMidPoint = 0;
    float f_X;
    float x = initial + deltaX / 2;

    for(int i=0; i< rectangle; i++)
    {
        f_X = (coefficient1 * pow( x, 2)) + (coefficient2 * x) + coefficient3;

        sumMidPoint += f_X * deltaX;
        x = x + deltaX;
    }
    return(sumMidPoint);

}

int main() {
    printf("Result: %f\n", getMidPoint(1, -1, 10, 3, 4, 0));
    return(0);
}

Output:
Result: 1.980000


问:
How to format and insert a character in between a string- Postgresql
I have this table.

member_id | phone_number
-----------+--------------
         1 | 09151234567
         2 | 09904897851
         3 | 09196332111
         4 | 09957935412
         5 | 09251279633
         6 | 09357489412
         7 | 09155974684
(7 rows)

I format the phone_number column to this format (63)xxxxxxxxx. Using this code

update member set phone_number = regexp_replace(phone_number, '0(.)', '(63)');

member_id | phone_number

-----------+---------------
         1 | (63)151234567
         2 | (63)904897851
         3 | (63)196332111
         4 | (63)957935412
         5 | (63)251279633
         6 | (63)357489412
         7 | (63)155974684
(7 rows)

And now I need to update this column again to this format (63)xxx-xxxxxx.
I don't want to replace a character, I need to insert a character in between the string.
I've tried using substring, regexp_replace but failed. I'm doing something wrong. I did find questions somehow related to this but they are all about string replacement.

答:
To convert from format (63)xxxxxxxxx to (63)xxx-xxxxxx, you could try

```<code>UPDATE member SET phone_number = regexp_replace(phone_number, '(\(\d{2}\)\d{3})(\d{6})', '\1-\2');
</code>```

You could also convert directly from original format to (63)xxx-xxxxxx by using the following

```<code>UPDATE member SET phone_number = regexp_replace(phone_number, '(0\d)(\d{3})(\d{6})', '(63)\2-\3');
</code>```

I've create a sample at this link http://rextester.com/VCX4636

Body:
To convert from format (63)xxxxxxxxx to (63)xxx-xxxxxx, you could try

UPDATE member SET phone_number = regexp_replace(phone_number, '(\(\d{2}\)\d{3})(\d{6})', '\1-\2');

You could also convert directly from original format to (63)xxx-xxxxxx by using the following

UPDATE member SET phone_number = regexp_replace(phone_number, '(0\d)(\d{3})(\d{6})', '(63)\2-\3');

I've create a sample at this link http://rextester.com/VCX4636


问:
nginx set remaining count for limit_req in X-RateLimit-Remaining header
I'm actually a little surprised that I couldn't find anything after a couple hours of googling, but the problem is as follows:

I want nginx to serve as my throttle for my API.

My config file contains a well-cited example of limit_req_zone:

limit_req_zone $binary_remote_addr zone=limit:2m rate=10r/m;

along with my location directive containing the expected limit_req zone=limit nodelay;

I would love to have nginx attach headers to the response message for both the X-RateLimit-Remaining and X-RateLimit-Reset attributes.  Basically have nginx use the active count of the rate=10r/m to populate X-RateLimit-Remaining and timeframe of the same rate=10r/m value to populate X-RateLimit-Reset with how many seconds are left before a refresh.

```<code>http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=2r/s;
    limit_req_status 429;
    limit_conn_status 429;

    server {
        listen       80;
        server_name  [removed];

        location / {
            limit_req zone=limit nodelay;

            proxy_pass http://reverse-proxy-example;
            add_header  X-RateLimit-Remaining [nginx variable?];
            add_header  X-RateLimit-Reset [nginx variable?]
        }
}
</code>```

Thoughts?  Possible?  Would love to avoid hitting the application to get these numbers.

答:
Packngo from Packet has a function that might be a good fit for what you need to do.

Sample from packngo:

```<code>func (r *Response) populateRate() {
    // parse the rate limit headers and populate Response.Rate
    if limit := r.Header.Get(headerRateLimit); limit != "" {
        r.Rate.RequestLimit, _ = strconv.Atoi(limit)
    }
    if remaining := r.Header.Get(headerRateRemaining); remaining != "" {
        r.Rate.RequestsRemaining, _ = strconv.Atoi(remaining)
    }
    if reset := r.Header.Get(headerRateReset); reset != "" {
        if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 {
            r.Rate.Reset = Timestamp{time.Unix(v, 0)}
        }
    }
}
</code>```

Body:
I'm actually a little surprised that I couldn't find anything after a couple hours of googling, but the problem is as follows:

I want nginx to serve as my throttle for my API.

My config file contains a well-cited example of limit_req_zone:

limit_req_zone $binary_remote_addr zone=limit:2m rate=10r/m;

along with my location directive containing the expected limit_req zone=limit nodelay;

I would love to have nginx attach headers to the response message for both the X-RateLimit-Remaining and X-RateLimit-Reset attributes.  Basically have nginx use the active count of the rate=10r/m to populate X-RateLimit-Remaining and timeframe of the same rate=10r/m value to populate X-RateLimit-Reset with how many seconds are left before a refresh.

http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=2r/s;
    limit_req_status 429;
    limit_conn_status 429;

    server {
        listen       80;
        server_name  [removed];

        location / {
            limit_req zone=limit nodelay;

            proxy_pass http://reverse-proxy-example;
            add_header  X-RateLimit-Remaining [nginx variable?];
            add_header  X-RateLimit-Reset [nginx variable?]
        }
}

Thoughts?  Possible?  Would love to avoid hitting the application to get these numbers.

Body:
Packngo from Packet has a function that might be a good fit for what you need to do.

Sample from packngo:

func (r *Response) populateRate() {
    // parse the rate limit headers and populate Response.Rate
    if limit := r.Header.Get(headerRateLimit); limit != "" {
        r.Rate.RequestLimit, _ = strconv.Atoi(limit)
    }
    if remaining := r.Header.Get(headerRateRemaining); remaining != "" {
        r.Rate.RequestsRemaining, _ = strconv.Atoi(remaining)
    }
    if reset := r.Header.Get(headerRateReset); reset != "" {
        if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 {
            r.Rate.Reset = Timestamp{time.Unix(v, 0)}
        }
    }
}


问:
Python 2.7 Export csv file with data
I am trying to export my data into a csv file

My code is as follows

```<code>x1=1
x2=2
y1=1
y2=4
z1=1
z2=2

a = (x1,y1,z1)
b = (x2,y2,z2)
def distance(x1,y1,z1,x2,y2,z2):
 return (((x2-x1)**2)+((y2-y1)**2)+((z2-z1)**2))**0.5
w=distance(x1,y1,z1,x2,y2,z2)
print w
if w>1 and w<2:
    time = 1
if w>2 and w<3:
    time = 2
if w>3 and w<4:
    time = 3

import csv

with open('concert_time.csv', 'w') as output:
</code>```

I am stuck at this last line.  I would like a file with two columns for 'Letter Combinations' and 'Time', and the output to look like:

```<code>Letters         Time
a and b           3
</code>```

I know there is a way to get this output by explicitly labeling a row as '3' for the appropriate time, but I would like a csv file that will change if I change the values of a or b, and thus the value of 'time' would change.  I have tried

```<code>writer.writerows(enumerate(range(time), 1))
</code>```

but this does not get me the desired output (in fact it is probably very far off, but I am new to Python so my methods have been guess and check)

Any help is greatly appreciated!

答:
completing your code for csv writer. Also make sure to open file as wb on windows so that carriage return (newline) is added automatically.

```<code>with open('concert_time.csv', 'wb') as output:
    writer = csv.writer(output)
    writer.writerow(["Letter Combinations", "Time"]) #header
    writer.writerow(["a and b", time]) #data
</code>```

Content of concert_time.csv:

```<code>Letter Combinations,Time
a and b,3
</code>```

Title: Python 2.7 Export csv file with data

Body:
I am trying to export my data into a csv file

My code is as follows

x1=1
x2=2
y1=1
y2=4
z1=1
z2=2

a = (x1,y1,z1)
b = (x2,y2,z2)
def distance(x1,y1,z1,x2,y2,z2):
 return (((x2-x1)**2)+((y2-y1)**2)+((z2-z1)**2))**0.5
w=distance(x1,y1,z1,x2,y2,z2)
print w
if w>1 and w<2:
    time = 1
if w>2 and w<3:
    time = 2
if w>3 and w<4:
    time = 3

import csv

with open('concert_time.csv', 'w') as output:

I am stuck at this last line.  I would like a file with two columns for 'Letter Combinations' and 'Time', and the output to look like:

Letters         Time
a and b           3

I know there is a way to get this output by explicitly labeling a row as '3' for the appropriate time, but I would like a csv file that will change if I change the values of a or b, and thus the value of 'time' would change.  I have tried

writer.writerows(enumerate(range(time), 1))

but this does not get me the desired output (in fact it is probably very far off, but I am new to Python so my methods have been guess and check)

Any help is greatly appreciated!

Body:
completing your code for csv writer. Also make sure to open file as wb on windows so that carriage return (newline) is added automatically.

with open('concert_time.csv', 'wb') as output:
    writer = csv.writer(output)
    writer.writerow(["Letter Combinations", "Time"]) #header
    writer.writerow(["a and b", time]) #data

Content of concert_time.csv:

Letter Combinations,Time
a and b,3


问:
How do I create a special link so that the user who clicked on that link can access a certain registration page?
I am using Swift mailer to generate a email that gets sent to the user when the admin user creates an account for that user. I want that email to contain a link that leads to a account registration page which only that user can access.

What do I have to do to make the registration page only accessible to that user?

答:
The page will always be accessible to any user (as it will be a GET request if clicked through the mail link), so the trick is to make it a difficult URL for a regular visitor to find. Simply create a random string of your choice (preferably uniquely-correlated to each user in the database) and append it to the page you want the user to visit:

```<code>$id = rand(1, 100000); // Grab the unique string from your database here
echo "<a href='page.php?id='" . $id . ">Registration link</a>";
</code>```

Then, to check if this ID variable is set when someone accesses the page, you can check the $_GET parameter:

```<code>if(isset($_GET['id'] && !empty($_GET['id'])) {
  // Code here will be executed on any ID in page.php?id=[any]
}
</code>```

If you want to check for a specific string, you can use:

```<code>$id = 1337;
if($_GET['id'] == $id) {
  // Code here will only trigger when visiting page.php?id=1337
}
</code>```

You can also check if a particular user is visiting the page, by setting checking that the logged-in user's ID matches the $_GET parameter:

```<code>$id = '' // Grab the user's ID from your database here
if(isset($_GET['id'] && !empty($_GET['id']) && $_GET['id'] == $id) {
  // Code here should be written based on the user being logged in
}
</code>```

There's unfortunately no way to stop someone 'guessing' that you have code pertaining to an ID $_GET, as E-mails can't open links in POST. Restricting the content based on a specific GET request is your best bet, as someone will have difficulty guessing the exact value the parameter needs.

For your specific situation, you should be perfectly fine just using something like the 1337 code above. Simply set the href> link in the E-mail to use that specific value.

Hope this helps! :)

Body:
The page will always be accessible to any user (as it will be a GET request if clicked through the mail link), so the trick is to make it a difficult URL for a regular visitor to find. Simply create a random string of your choice (preferably uniquely-correlated to each user in the database) and append it to the page you want the user to visit:

$id = rand(1, 100000); // Grab the unique string from your database here
echo "<a href='page.php?id='" . $id . ">Registration link</a>";

Then, to check if this ID variable is set when someone accesses the page, you can check the $_GET parameter:

if(isset($_GET['id'] && !empty($_GET['id'])) {
  // Code here will be executed on any ID in page.php?id=[any]
}

If you want to check for a specific string, you can use:

$id = 1337;
if($_GET['id'] == $id) {
  // Code here will only trigger when visiting page.php?id=1337
}

You can also check if a particular user is visiting the page, by setting checking that the logged-in user's ID matches the $_GET parameter:

$id = '' // Grab the user's ID from your database here
if(isset($_GET['id'] && !empty($_GET['id']) && $_GET['id'] == $id) {
  // Code here should be written based on the user being logged in
}

There's unfortunately no way to stop someone 'guessing' that you have code pertaining to an ID $_GET, as E-mails can't open links in POST. Restricting the content based on a specific GET request is your best bet, as someone will have difficulty guessing the exact value the parameter needs.

For your specific situation, you should be perfectly fine just using something like the 1337 code above. Simply set the <a href> link in the E-mail to use that specific value.

Hope this helps! :)


问:
Howto delete every second and third element from an array?
I want to delete every second and third element from an array in Javascript.

My array looks like this:

```<code>var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
</code>```

Now I want to delete every second and third element. The result would look like this:

```<code>["Banana", "Orange", "Apple"]
</code>```

I tried to use a for-loop and splice:

```<code>for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};
</code>```

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

答:
This works for me.

```<code>var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"];

for(var i = 0; i < fruits.length; i++) {
    fruits.splice(i+1,2);
}

//fruits = Banana,Orange,Apple,Pear
</code>```

Here's a demo that illustrates it a little better: http://jsfiddle.net/RaRR7/

Body:
I want to delete every second and third element from an array in Javascript.

My array looks like this:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

Now I want to delete every second and third element. The result would look like this:

["Banana", "Orange", "Apple"]

I tried to use a for-loop and splice:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

Body:
This works for me.

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"];

for(var i = 0; i < fruits.length; i++) {
    fruits.splice(i+1,2);
}

//fruits = Banana,Orange,Apple,Pear

Here's a demo that illustrates it a little better: http://jsfiddle.net/RaRR7/


答:
As @TatsuyukiIshi said, you need to change the use of replace() for regular assignment. For extra help, here is an updated version of your alienLanguage function:

```<code>function alienLanguage(str){
    return str.toUpperCase().split(' ').map(function(word) {
        return word.slice(0, -1) + word.substr(-1).toLowerCase()
    }).join(' ')
}
</code>```

Fiddle here

Extra notes:

word.slice(0,-1) returns the word minus the last character.

word.substr(-1) returns the last character as a string.

.map() returns an array, so you can call join() directly on the result.

Title: Don't understand why replace() method is not working as expected

Body:
As @TatsuyukiIshi said, you need to change the use of replace() for regular assignment. For extra help, here is an updated version of your alienLanguage function:

function alienLanguage(str){
    return str.toUpperCase().split(' ').map(function(word) {
        return word.slice(0, -1) + word.substr(-1).toLowerCase()
    }).join(' ')
}

Fiddle here

Extra notes:

word.slice(0,-1) returns the word minus the last character.

word.substr(-1) returns the last character as a string.

.map() returns an array, so you can call join() directly on the result.


答:
isn't the last character specified already?

No, you've only specified what character to replace, not where. replace searches the string for the expression.

How can I replace the last e?

Don't use replace at all. It does construct a new string anyway, and you can do that much easier:

```<code>function alienLanguage(str) {
  return str.split(' ').map(function(a) {
    return a.slice(0, -1).toUpperCase() + a.slice(-1).toLowerCase();
  }).join(' ');
}
</code>```

You also could use replace, but would use it with regular expression:

```<code>function alienLanguage(str) {
  return str.toUpperCase().replace(/.\b/g, function(last) {
//                                 ^^^^^^ matches all characters before a word boundary
    return last.toLowerCase();
  });
}
</code>```

Body:
isn't the last character specified already?

No, you've only specified what character to replace, not where. replace searches the string for the expression.

How can I replace the last e?

Don't use replace at all. It does construct a new string anyway, and you can do that much easier:

function alienLanguage(str) {
  return str.split(' ').map(function(a) {
    return a.slice(0, -1).toUpperCase() + a.slice(-1).toLowerCase();
  }).join(' ');
}

You also could use replace, but would use it with regular expression:

function alienLanguage(str) {
  return str.toUpperCase().replace(/.\b/g, function(last) {
//                                 ^^^^^^ matches all characters before a word boundary
    return last.toLowerCase();
  });
}


问:
Jumping Elements
I'm creating a parallax effect and I've made it so that (almost) every element has a different scroll speed.

I've also made it so that elements down the page don't trigger their scroll speed until they've reached the viewport.

Here's the JS for trigger commands on reveal:

```<code>function isElementInViewport (el) {

  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }

  var rect = el.getBoundingClientRect();

  return (
    rect.bottom >= 0 &&
    rect.left >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}
</code>```

My scroll speed code is:

```<code>$(window).scroll(function(){
  var wScroll = $(this).scrollTop();

  if (isElementInViewport($('#computer'))) {
    $('#computer').css({
      transform' : 'translate(0px, '+ wScroll /12 +'%)'
    });
  }
</code>```

OR for elements already at the top of page:

```<code>$(window).scroll(function(){
  var wScroll = $(this).scrollTop();

  $('#shape-2').css({
    'transform' : 'translate(0px, -'+ wScroll /8 +'%)'
  });
</code>```

The issue here is that when I add function isElementInViewport to the scroll speed.

It makes the element jump out of view when revealed, THEN it scrolls how I want it.

So, then it's out of place with the layout of the page.

I've tried compensating it by changing the position of the element so that when it's revealed it jumps to its original spot then starts scrolling, but this didn't prove helpful since the position varied from different screen sizes and resolutions.

Any way I can make it so it doesn't jump when revealed?

答: Make sure your base CSS declares a translation transform of zero, or add it from script before the element is in view; adding the attribute later may be causing the jump. </p>

Title: Jumping Elements

Body:
I'm creating a parallax effect and I've made it so that (almost) every element has a different scroll speed.

I've also made it so that elements down the page don't trigger their scroll speed until they've reached the viewport.

Here's the JS for trigger commands on reveal:

function isElementInViewport (el) {

  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }

  var rect = el.getBoundingClientRect();

  return (
    rect.bottom >= 0 &&
    rect.left >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

My scroll speed code is:

$(window).scroll(function(){
  var wScroll = $(this).scrollTop();

  if (isElementInViewport($('#computer'))) {
    $('#computer').css({
      transform' : 'translate(0px, '+ wScroll /12 +'%)'
    });
  }

OR for elements already at the top of page:

$(window).scroll(function(){
  var wScroll = $(this).scrollTop();

  $('#shape-2').css({
    'transform' : 'translate(0px, -'+ wScroll /8 +'%)'
  });

The issue here is that when I add function isElementInViewport to the scroll speed.

It makes the element jump out of view when revealed, THEN it scrolls how I want it.

So, then it's out of place with the layout of the page.

I've tried compensating it by changing the position of the element so that when it's revealed it jumps to its original spot then starts scrolling, but this didn't prove helpful since the position varied from different screen sizes and resolutions.

Any way I can make it so it doesn't jump when revealed?


问:
Why this code not working?
Appreciate if someone could help me.</p>

```<code>#!/usr/bin/python

lenlist = 9
while lenlist <= 0:
        print "hello"
        lenlist -= 1
</code>```

答:
This will work:</p>

```<code>lenlist = 9
while lenlist >= 0:
    print "hello"
    lenlist -= 1
</code>```

Title: Why this code not working?

Body:
Appreciate if someone could help me.

#!/usr/bin/python

lenlist = 9
while lenlist <= 0:
        print "hello"
        lenlist -= 1

Body:
This will work:

lenlist = 9
while lenlist >= 0:
    print "hello"
    lenlist -= 1


问:
Dagger + Retrofit. Adding auth headers at runtime
I'm wondering if there is a way for Dagger to know that it should recreate an object when new data is available.

The instance I am speaking of is with the request headers I have for retrofit. At some point (when the user logs in) I get a token that I need to add to the headers of retrofit to make authenticated requests. The issue is, I'm left with the same unauthenticated version of retrofit. Here's my injection code:

```<code>@Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .cache(cache).build();
         client
                .newBuilder()
                .addInterceptor(
                    chain -> {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .addHeader("Accept", "Application/JSON");
                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }).build();
        return client;
    }

  @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
}

@Provides
    @Singleton
    public NetworkService providesNetworkService(Retrofit retrofit) {
        return retrofit.create(NetworkService.class);
    }
</code>```

Any ideas on how to make this work?

答:
I personally created an okhttp3.Interceptor that does that for me, which I update once I have the required token. It looks something like:

```<code>@Singleton
public class MyServiceInterceptor implements Interceptor {
  private String sessionToken;

  @Inject public MyServiceInterceptor() {
  }

  public void setSessionToken(String sessionToken) {
    this.sessionToken = sessionToken;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    Request.Builder requestBuilder = request.newBuilder();

    if (request.header(NO_AUTH_HEADER_KEY) == null) {
      // needs credentials
      if (sessionToken == null) {
        throw new RuntimeException("Session token should be defined for auth apis");
      } else {
        requestBuilder.addHeader("Cookie", sessionToken);
      }
    }

    return chain.proceed(requestBuilder.build());
  }
}
</code>```

In the corresponding dagger component, I expose this interceptor so I can set the sessionToken when I need to.

That is some stuff that Jake talked about it his talk Making Retrofit Work For You.

Body:
I'm wondering if there is a way for Dagger to know that it should recreate an object when new data is available.

The instance I am speaking of is with the request headers I have for retrofit. At some point (when the user logs in) I get a token that I need to add to the headers of retrofit to make authenticated requests. The issue is, I'm left with the same unauthenticated version of retrofit. Here's my injection code:

@Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .cache(cache).build();
         client
                .newBuilder()
                .addInterceptor(
                    chain -> {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .addHeader("Accept", "Application/JSON");
                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }).build();
        return client;
    }

  @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
}

@Provides
    @Singleton
    public NetworkService providesNetworkService(Retrofit retrofit) {
        return retrofit.create(NetworkService.class);
    }

Any ideas on how to make this work?

Body:
I personally created an okhttp3.Interceptor that does that for me, which I update once I have the required token. It looks something like:

@Singleton
public class MyServiceInterceptor implements Interceptor {
  private String sessionToken;

  @Inject public MyServiceInterceptor() {
  }

  public void setSessionToken(String sessionToken) {
    this.sessionToken = sessionToken;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    Request.Builder requestBuilder = request.newBuilder();

    if (request.header(NO_AUTH_HEADER_KEY) == null) {
      // needs credentials
      if (sessionToken == null) {
        throw new RuntimeException("Session token should be defined for auth apis");
      } else {
        requestBuilder.addHeader("Cookie", sessionToken);
      }
    }

    return chain.proceed(requestBuilder.build());
  }
}

In the corresponding dagger component, I expose this interceptor so I can set the sessionToken when I need to.

That is some stuff that Jake talked about it his talk Making Retrofit Work For You.


问:
Wordpress CSS changes do not reflect
I am working on WP 3.5.1, the latest version with a Duotive Three theme installed in it. Everything was working fine until 2 days back, but from 2 days, whenever I edit my CSS file either through the FTP or the Wordpress Admin, it does not reflect in the browser, either in the website or when I open the CSS file in the browser directly. However, the changes start reflecting a few hours later, I do not know how long exactly. But it frustrates me a lot because I need to wait for a long time to see the changes and check them.
I have tried refreshing the browser with Shift + F5, I deleted browser cache, cookies and even temp files. But still it does not work. Please help.
Note:- I have been working in Wordpress since around 6 years now, built more than 100 websites in Wordpress but this is the first time I am facing this problem. I tried to consult with my network of friends and spent hours googling, many had similar problems but not exactly like mine.</p>

答:
In your WP Admin GoTo

Appearance -> Theme Options -> Dynamic CSS ->
In this option scroll down you can see USE option

Here you need to select Internal Stylesheet from drop down menu.

Title: Wordpress CSS changes do not reflect


问:
Creating an array with large initial size in powershell
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

```<code>$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}
</code>```

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

答:
Array literal multiplication:</p>

```<code>$arr = @($null) * 10000
</code>```

Body:
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

Body:
Array literal multiplication:

$arr = @($null) * 10000


问:
How does UITextField handle french characters?
I have a UITextField that takes input for both english and french.
After I type french accents chars for example àÂèÎôÛç, and log the string, it looks like this:
\M-C\240\M-C\M^B\M-C\M-(\M-C\M^N\M-C\M-4\M-C\M^[\M-C\M-'
I've done a little research, but couldn't find what kind of encoding this is.

What kind of encoding is this?
How people normally handle encoding of special character?

答:
The return type of the text method of UITextField is NSString which according to the documentation is:

An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0.

So it is just Unicode and the Xcode console just isn't printing it correctly.


问:
OutOfMemory Error: Synchronized blocks inside static methods
I'm getting an OutOfmemory error while execution of getInstance. I checked the thread dumps and found the thread is BLOCKED (Waiting for Monitor Lock on getInstance).

I'm very novice at multi-threading. Could anyone please explain if below implementation is correct or not? If not, how can it be improved?

```<code>class MyClass {
    private static MyClass instance = new MyClass();
    public static MyClass getInstance() throws Exception {
        synchronized (instance) {...}
    }
    public static MyClass clearInstance() throws Exception {
        synchronized (instance) {...}
    }
}
</code>```

答:
It's not the problem about multi threading but when you create an object of Myclass it has an instance variable instance which creates another object of Myclass and it goes into a never ending loop.

So, that's why you are getting an out of memory or stack overflow error.

Body:
I'm getting an OutOfmemory error while execution of getInstance. I checked the thread dumps and found the thread is BLOCKED (Waiting for Monitor Lock on getInstance).

I'm very novice at multi-threading. Could anyone please explain if below implementation is correct or not? If not, how can it be improved?

class MyClass {
    private static MyClass instance = new MyClass();
    public static MyClass getInstance() throws Exception {
        synchronized (instance) {...}
    }
    public static MyClass clearInstance() throws Exception {
        synchronized (instance) {...}
    }
}


问:
Recheck rcp handler after execute
I’m having an issue with our propertyTester and enabling handlers. The property is areUpdatesAvailable and the handler is enabled when this property is true. After the handler executes the areUpdatesAvailable value becomes false, but how I currently have it set up, it only checks when the selection changes. So if I right click on an item and call the Update handler and then right click on the item again without changing my selection, the update is still enabled because it’s not calling the property tester again. Is there a way to make it check again after the handler has been executed?</p>

```<code><handler
      class="com.cerner.automation.touchstone.handlers.UpdateExternalReference"
      commandId="com.cerner.automation.touchstone.workflow.Update">
      <enabledWhen>
           <with
                variable="selection">
                <test
                     property="com.cerner.automation.touchstone.testers.nodeItem.areUpdatesAvailable" value="true" forcePluginActivation="true">
                </test>
                <iterate
                     ifEmpty="false"
                     operator="and">
                     <instanceof
                          value="com.cerner.automation.touchstone.model.ExternalReferenceItem">
                     </instanceof>
                </iterate>
               <test
                forcePluginActivation="true"
                property="com.cerner.automation.touchstone.testers.nodeItem.isInternal"
                value="true">
                    </test>
           </with>
      </enabledWhen>
 </handler>
</code>```

答:
What I ended up doing was using the requestEvaluation after the handler was complete.</p>

```<code>final IEvaluationService evaluationService = (IEvaluationService) window.getService(IEvaluationService.class);
        evaluationService.requestEvaluation(property);
</code>```

Title: Recheck rcp handler after execute

Body:
I’m having an issue with our propertyTester and enabling handlers. The property is areUpdatesAvailable and the handler is enabled when this property is true. After the handler executes the areUpdatesAvailable value becomes false, but how I currently have it set up, it only checks when the selection changes. So if I right click on an item and call the Update handler and then right click on the item again without changing my selection, the update is still enabled because it’s not calling the property tester again. Is there a way to make it check again after the handler has been executed?

<handler
      class="com.cerner.automation.touchstone.handlers.UpdateExternalReference"
      commandId="com.cerner.automation.touchstone.workflow.Update">
      <enabledWhen>
           <with
                variable="selection">
                <test
                     property="com.cerner.automation.touchstone.testers.nodeItem.areUpdatesAvailable" value="true" forcePluginActivation="true">
                </test>
                <iterate
                     ifEmpty="false"
                     operator="and">
                     <instanceof
                          value="com.cerner.automation.touchstone.model.ExternalReferenceItem">
                     </instanceof>
                </iterate>
               <test
                forcePluginActivation="true"
                property="com.cerner.automation.touchstone.testers.nodeItem.isInternal"
                value="true">
                    </test>
           </with>
      </enabledWhen>
 </handler>

Body:
What I ended up doing was using the requestEvaluation after the handler was complete.

final IEvaluationService evaluationService = (IEvaluationService) window.getService(IEvaluationService.class);
        evaluationService.requestEvaluation(property);


问:
Drawer not covering header in react-navigation
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

```<code>import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);
</code>```

Other problem is how should I add 2 drawers in my app at the same screen

答:
As per my knowledge, you have to do 2 things:
 1. Put drawer control at the top of navigation stack.
 2. Set translucent propery of StatusBar

```<code><StatusBar
                translucent
                backgroundColor="rgba(0, 0, 0, 0.24)"
                animated
            />
            { Platform.OS === 'android' && Platform.Version >= 20 ?
                <View
                    style={{
                      height: 24,
                      backgroundColor: "#512DA8",
                    }}
                />
                : null }
</code>```

Kindly let me know if it does work.

Body:
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);

Other problem is how should I add 2 drawers in my app at the same screen

Body:
As per my knowledge, you have to do 2 things:
 1. Put drawer control at the top of navigation stack.
 2. Set translucent propery of StatusBar

<StatusBar
                translucent
                backgroundColor="rgba(0, 0, 0, 0.24)"
                animated
            />
            { Platform.OS === 'android' && Platform.Version >= 20 ?
                <View
                    style={{
                      height: 24,
                      backgroundColor: "#512DA8",
                    }}
                />
                : null }

Kindly let me know if it does work.