text:
Q: recyclerView Add & Delete I am working on an Android project, where I have set up a recyclerView for a CardView.
Here I have a 3 dot image, which have included a menu, where I can add or delete an item of the recyclerView. It looks like this:

For some reason, when I delete an item, and thereafter add items. Then sometimes the deleted item shows up. When I change a title to let's say "Room 1", and I delete it, then it will show up again, when I add new items. Anyone knows why this happens. Why won't it DELETE the item?
Thanks in advance!
* CODE HERE *
Recycler Adapter
public class lokationRecyclerAdapter extends RecyclerView.Adapter<lokationRecyclerAdapter.RecyclerViewHolder> {

List<String> cardList;
String test;

SensorOversigtFragment sensorOversigtFragment;

public interface listListener {
    void onAddListener( List<String> cardList, int position);
}

public lokationRecyclerAdapter(List<String> cardList) {
    this.cardList = cardList;
    notifyDataSetChanged();
}

@Override
public RecyclerViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from( viewGroup.getContext() ).inflate( R.layout.lokationcardview, viewGroup, false );
    return new RecyclerViewHolder( view );
}

public void addItem() {
    cardList.add( new String() );
    notifyDataSetChanged();
}

public void deleteItem(int position) {
    cardList.remove( position );
    notifyItemRemoved( position );
    notifyItemRangeChanged( position, cardList.size() );

}

@Override
public void onBindViewHolder(RecyclerViewHolder recyclerViewHolder, int position) {
    recyclerViewHolder.cardView.setBackgroundResource( R.drawable.ic_circleshape );
    listListener.onAddListener(cardList.get( position ), position);
}

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

class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public int nummer;
    private CardView cardView;
    private Button menuButton;
    private TextView lokationsName;

    public void alertDialog(View itemView) {

        new AlertDialog.Builder( itemView.getContext() );

        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder( itemView.getContext() );
        builder.setCancelable( true );
        builder.setTitle( "Tilføj eller ændre navnet på lokation" );
        builder.setMessage( "Hold styr på dine sensorer ved at oprette lokationer i form af eksempelvis lokaler." );

        final EditText input = new EditText( itemView.getContext() );
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT );
        input.setMaxLines( 1 );
        input.setInputType( InputType.TYPE_CLASS_TEXT );
        input.setLayoutParams( lp );
        builder.setView( input );

        builder.setPositiveButton( "Ja", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                test = input.getText().toString();
                lokationsName.setText( test );
            }
        } );

        builder.setNegativeButton( "Nej", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        } );

        android.support.v7.app.AlertDialog dialog = builder.create();
        dialog.show();

    }

    public RecyclerViewHolder(final View itemView) {
        super( itemView );

        cardView = (CardView) itemView.findViewById( R.id.lokationcard_view );
        menuButton = (Button) itemView.findViewById( R.id.menuButton );
        lokationsName = (TextView) itemView.findViewById( R.id.lokationsName );

        itemView.setOnClickListener( this );

        menuButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final PopupMenu popupMenu = new PopupMenu( itemView.getContext(), menuButton );
                popupMenu.getMenuInflater().inflate( R.menu.lokationpopmenu, popupMenu.getMenu() );

                popupMenu.setOnMenuItemClickListener( new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        switch (item.getItemId()) {

                            case R.id.changeLokation:
                                System.out.println( "GET ADAPTER POSITION: " + getAdapterPosition() );
                                alertDialog( itemView );
                                break;

                            case R.id.addCardView:
                                String lokation = lokationsName.getText().toString();
                                System.out.println("LOKATIONS NAME: " + lokation );
                                if(lokation.equals( "TILFØJ LOKATION" )) {
                                   Toast.makeText( itemView.getContext(), "Du skal ændre navnet på lokation først!", Toast.LENGTH_LONG ).show();
                                } else {
                                    addItem();
                                }
                                break;

                            case R.id.deleteCardView:
                                if (cardList.size() > 1) {
                                    deleteItem( getAdapterPosition() );
                                } else {
                                    Toast.makeText( itemView.getContext(), "Du kan ikke slette den sidste CardView", Toast.LENGTH_LONG ).show();
                                }
                                break;

                        }
                        return true;
                    }
                } );
                popupMenu.show();
            }
        } );

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {

        nummer = getAdapterPosition();
        Intent intent = new Intent( itemView.getContext(), gridTabelActivity.class );
        Bundle bundle = ActivityOptions.makeCustomAnimation( v.getContext(), R.anim.slide_in_right, R.anim.slide_out_left ).toBundle();
        itemView.getContext().startActivity( intent, bundle );
    }

 }

}

Fragment initializing recyclerView
public class SensorOversigtFragment extends Fragment {

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;

List<String> test = new ArrayList<>();

public SensorOversigtFragment() {
    // Required empty public constructor
}

public void onAddListener(List<String> cardList, int position) {
    test = cardList;
    cardList.add( new String() );
    adapter.notifyDataSetChanged();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate( R.layout.lokationcardlist, container, false );

    recyclerView = (RecyclerView) view.findViewById( R.id.lokationrecycler_view );

    test.add( "test" );

    adapter = new lokationRecyclerAdapter( test );
    recyclerView.setHasFixedSize( true );
    recyclerView.setAdapter( adapter );
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager( this.getActivity() );
    recyclerView.setLayoutManager( linearLayoutManager );

    adapter.notifyDataSetChanged();

    return view;
    }
}

A: I think you should use an interface for adding and should listen to that interface from the fragment and only from there you should add or delete items
           makerInterface.onAddListener(cardList.get(position),position);

and this should go inside onBindViewHolder
TeamMakerInterface.java
public interface TeamMakerInterface {

    void onAddListener( List<String> cardList,int position);

}

Instead of Adding and deleting it inside do that in the fragment itself
    @Override
    public void onAddListener( List<String> cardList,int position) {
       cardList.add( new String() );
       notifyDataSetChanged();
    }


text:
Q: Enterprise OSGi vs. EJB i have an application server (JBoss) with some EJBs deployed. Now i must develop an OSGi application which i would like to reuse with my application server. I know that new application servers allows to deploy OSGi bundles in the application server itself.
These are my questions:
Could i simple deploy my OSGi bundles into the application server instead of EJBs?
Do OSGi services scale as well as EJB or should i better use EJB for performance-critical parts of the application(Is there are any "OSGi service thread pool" in application server)?
Will the OSGi service be the bottleneck for EJB-Based application if used together?
Thanks, Slava

A: If you were using GlassFish, you could do use best both the worlds, as GlassFish can automatically make your EJBs that are part of your OSGi bundle available as OSGi services. See
http://weblogs.java.net/blog/ss141213/archive/2010/03/30/ejb-osgi-service-demo-eclipsecon
For more info, ask in glassfish forum at users@glassfish.java.net

redpajama_set_name: RedPajamaStackExchange


text:
Q: display custom events in webkit browser inspector timeline I wanted to view custom events in the timeline of the web inspector of safari, or chrome's developer tools.
Has anyone had success creating events and having them displayed in the inspector? This would be extremely useful.
this doesn't show up in timeline:
var event = document.createEvent( 'CustomEvent' );
event.initCustomEvent('myEvent', true, false);
document.dispatchEvent( event );

this works, but it's a mouse event, which is not my intention:
var event = document.createEvent( 'MouseEvents' );
event.initEvent('click', true, false);
document.dispatchEvent( event );

A: You need to add a listener for your custom event.
document.addEventListener('myEvent', function() { console.log('myEvent'); });

var event = document.createEvent('CustomEvent');
event.initEvent('myEvent', true, false);
document.dispatchEvent(event);

Source:
http://code.google.com/searchframe#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/inspector/InspectorInstrumentation.cpp&exact_package=chromium&q=willDispatchEventOnWindowImpl&type=cs&l=337


text:
Q: How to print values computed from variables in angular? I have a FormGroupin a component like:
form: FormGroup = new FormGroup({
    $key: new FormControl(null),
    from: new FormControl('', Validators.required),
    to: new FormControl('', Validators.required),
    quantity: new FormControl('', [Validators.required, Validators.pattern('[0-9]*')]),
    price: new FormControl('', [Validators.required, Validators.pattern('[0-9]*')]),
    ticker: new FormControl('', Validators.required)
  });

And in the html, I have the Input elements to accept the inputs for each of the five form-controls.
I'm just facing some trouble in outputting Amount to the html:

Amount: {{ form.controls['quantity'] * form.controls['price']}}

I'm getting errors:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
Can someone help me to understand whats going on?

A: Convert the variables to numbers.
Try this:

Amount: {{ +form.controls['quantity'] * +form.controls['price']}}

Or change type of your input to number:
<input type="number" formControlName="quantity">
<input type="number" formControlName="price">

And change your form:
quantity: new FormControl(null, Validators.required),
price: new FormControl(null, Validators.required),

A: Thanks @Bazhan, but actually this below modification gave the expected output:

Amount: {{ form.value.quantity * form.value['price']}}

I should have accessed the value field instead of the controls field.


text:
Q: JSP custom closing form tag show on wrong spot We are using JSP custom form tag, we found the closing tag </form> always shows in the wrong spot, which causes a lot problems for us because the following dynamically generated html elements are not nested inside <form>...</form> after the user submits the form, those elements data are lost.
   Here is the code:
   <ct:table>
       <ct:form name="form1" >
           <ct:addFromRequest prefix="<%= AP.CSA_PREFIX %>" />
           <ct:add name="<%= AP.ACTION %>" value=" " />

            .....some dynamically generated code here

       </ct:form>
    </ct:table>

In IE, it works as expected:

    <form name="form1" >

    ...

    </form>

But in FireFox and Chrome, it always show like:

    <form name="form1" ></form>  *******the closing </form> tag appears here

    ... dynamically generated html controls here

The whole page is code is here:
<%
CCtFormValidation ct_form = new CCtFormValidation( jsp_input );
CCtHelperFunctions ct_helper = new CCtHelperFunctions( jsp_input );
%>

<%@ include file="../../generic_gui/template/general_head.jsp" %>
<ct:script>
function CheckForm ( form_to_check )
{
    if ( form_to_check.<%=AP.MANAGE_GROUP%>[0].checked
        && form_to_check.<%=AP.GROUP_ID%>.selectedIndex < 1 )
    {
        <%= ct_form.printErrorJavascriptAlert ( CFrontEndErrorCodes.FRONTEND_ERROR_CODE_MISSING_MANDATORY_PARAMS ) %>
        form_to_check.<%=AP.GROUP_ID%>.focus();
        return false;
    }
    return true;
}
function BeforeSubmit( form_to_submit )
{
    form_to_submit.<%=AP.ACTION%>.value = "<%=AP.ACTION_SUBMIT%>";
}

function BeforeCancel( form_to_cancel )
{
    form_to_cancel.<%=AP.ACTION%>.value = "<%=AP.ACTION_CANCEL%>";
}

function OnLoad()
{
}

</ct:script>

<%@ include file="../../generic_gui/template/general_body_start.jsp" %>
<ct:table width="75%">

            <ct:form name="form1">
            <ct:addFromRequest prefix="<%= AP.CSA_PREFIX %>" />
            <ct:add name="<%= AP.ACTION %>" value=" " />

                <%= rc.getStr ( "s_page_title" ) %>

                <%= rc.getStr ( "s_text_1" ) %>

            <input type="radio" name="<%=AP.MANAGE_GROUP%>" value="<%=AP.MODIFY_GROUP%>" checked>

                <%= rc.getStr("s_modify_group_text")%>

                <select id="<%=AP.GROUP_ID%>" name="<%=AP.GROUP_ID%>" size="1" class="textBoxNoSize" onFocus="document.form1.<%=AP.MANAGE_GROUP%>[0].checked=true;">
                    <OPTION value="<%=rc.getStr("s_select_group")%>"><%=rc.getStr("s_select_group")%></OPTION>
                <%
                    CCSAGroupDetails current_group;
                    for ( int counter = 0 ; counter < group_list.size() ; ++counter )
                    {
                        current_group = ( CCSAGroupDetails ) group_list.get ( counter );
                    %>
                    <OPTION value="<%=current_group.getGroupId()%>"><%=current_group.getGroupName()%></OPTION>
                <% } %>
                </select>

            <input type="radio" name="<%=AP.MANAGE_GROUP%>" value = "<%=AP.CREATE_GROUP%>">

                <%= rc.getStr("s_create_group_text")%>

            <ct:button param="button_next" javascript="SubmitForm( document.form1 );"/>

            <ct:button param="button_cancel" javascript="CancelForm( document.form1 );"/>

</ct:form>
</ct:table>
<%@ include file="../../generic_gui/template/general_body_end.jsp" %>
<%@ include file="../../generic_gui/template/general_footer.jsp" %>

The page rendered on IE with right tag start and close <form name=form1>...</form> however, FF and Chrome page rendered as <form name=form1></form>.
Any problems with my code?


text:
Q: Share android project in Github creates empty project I followed this SO answer to share my project. I happen to have a volley library in my project. But I only see the library in my github account and not my project. I am on Android studio 2.2.3. Obviously, the git and github test from Android studio is working(successful). I tried this many times but each time my whole project is missing except the Volley library. Has anyone encountered the similar problem? What am I missing?

A: In the newer versions of Android Studio, you have to create the repository as shown in the screen shot below.

Then from that same selection you select "share project on Github". After that you simply select CVS-> Commit Changes each time you make changes to the file. The first step is missing in all of the SO answers and online tutorials available online today.

A: This seems to be an old post but I came across this post when I had similar issues. I tried to share android project and it kept creating empty file.
I tried to run git add . on my local repository but like you it only pushed one activity and when I tried to push again it kept giving me cannot connect to repository error. This is another stack link that helped me I followed the steps given by Aditya Anand on this link :
cannot connect to repository from configured remote. you would want to check .git config
steps:
Step-by-step process:
1) Delete the repository from GitHub
2) Open android studio.
3) Load the file on which you were working.
4) Click on - VCS > Git > Remotes... >
5) Git remotes will popup.
6) Select the file, and click on (-) red minus sign.
7) Remove remote origins
8) Click on yes
After I followed those steps I went ahead and run the git add . command again. Then from android studio I pushed the project which successfully pushed all the files. Hope this helps.


text:
Q: How much space should I leave free on an SSD to ensure performance and stability? I have heard from various sources that if you use close to all of the storage on your disk you will run into performance and/or reliability issues. Is this also true of SSDs? If so how much free space is it recommended that I leave on the drive?

A: There is no technical problem with using up most of your storage - you do run into other issue if you use up ALL of your storage, like you are out of room. The performance hit you have been hearing about is actually a problem with spinning disk hard drives.
The issue that you run into with spinning disk is that as you fill up the drive, the data get written out farther and farther on the platter, causing the drive head to have to move farther back and forth on the platter to actually get to the data. This will introduce a disk latency hit.
That being said, with lower end SSDs you do have to watch out because they do not have as many spare blocks set aside to replace failed ones. So when they run out of spare blocks and can't replace them you can run into performance and stability issues like you would with any drive that has an increasing number of bad sectors.
As far as how much to leave free? I would leave the normal amount you would for any other server in your environment so you have enough time to react to the low space alerts and not run out of space.

A: For SSDs it might also be better to leave some free space, but for a different reason than for HDDs, for which Zypher already pointed out the reason.
SSD performance is not (much) influenced by fragmentation, but is by free blocks that can be garbage collected by the SSD controller. Depending on the quality of the garbage controller and if your SSD, OS or filesystem do not support TRIM, it might increase performance in the long term to leave some SSD space unpartitioned to have more free blocks available for writes. This space needs to be unpartitioned, free space on the filesystem is irrelevant if the OS doesn't notify the SSD controller with TRIM that it these blocks are indeed free.
I don't know what a sufficient amount of free space should be. I myself left about 5-10% unpartitioned on SSD drives where TRIM wasn't supported (Linux, before kernel 2.6.33 and on an encrypted drive).


text:
Q: post parameter (array) undefined when assigned to variable I've got this on my node server:
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.post('/jetsi', function (req, res, next) {
  console.log(req.body);
  let filesFolders = req.body.fs;

  for (var i = 0, len = filesFolders.length; i < len; i++) {
    console.log(filesFolders[i]);
  }
  return res.status(200).send("test");
});

the problem is when I try to store req.body.fs to my variable (filesFolders)... it undefined!
If I debug my server, I see the data correctly, but I can work with it... why? look at the picture:

I call to the server on a react app like this:
const url = config.API_URL + 'jetsi';
axios({
  url: url,
  method: 'post',
  data: { fs: this.state.itemsToDownload },
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.zip');
  document.body.appendChild(link);
  link.click();
});

The idea is to create a zip file (and download it). So from a react app I send a post request with an array witch I need to get on my node app to make my zip file. Any idea what is happening?
any clue? thank's in advance


text:
Q: Sub querying data over a SQL query I've the following query,
Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345
137.2345. Round your answer to 4 decimal places.
The schema for the table STATION is id, city, state, lat_N, long_w
This is my code,
SELECT LONG_W
FROM STATION
WHERE LAT_N IN
(SELECT ROUND(MAX(LAT_N), 4) FROM STATION WHERE LAT_N < 137.2345);

This doesn't work, what am I doing wrong here.

A: There's several things wrong here.
For one thing, there is no guarantee that value in LAT_N is going to be equal to ROUND(LAT_N,4).
 78.123456 = ROUND(78.123456,4)   --> FALSE

I don't see any need for a subquery.
Maximum value for a latitude (in degrees) is going to be 90. I think the question was asking for values of LONG_W that were less than 137.2345
I read the question as specifying...

*

*access the rows in the station table

*exclude rows that don't satisfy LONG_W < 137.2345

*from those rows, find the "largest" value LAT_N

*round that largest value of LAT_N to 4 decimal places

*return the rounded value

I'd write the query like this:
 SELECT ROUND(MAX(s.lat_n),4) AS largest_lat_n
    FROM station s
   WHERE s.long_w < 137.2345

Maybe I'm reading the question wrong. (This isn't a SQL problem, it's a specification problem.)
If the question is instead asking...

*

*access the rows in the station table

*exclude rows that don't satisfy LONG_W < 137.2345

*from those rows, find the row with the "largest" value LAT_N

*take the LONG_W from that row with largest LAT_N

*round that LONG_W to 4 decimal places

*return the rounded value

To get other values on the row that have the largest LAT_N, I could do something like this:
  SELECT ROUND(s.long_w,4)
    FROM station s
   WHERE s.long_w < 137.2345
   ORDER BY s.lat_n DESC
   LIMIT 1

If I want to use a subquery, there's a potential that we'll get multiple rows back with the same LAT_N, and some of those values of LONG_W could be larger than 137.2345
Consider a table containing rows with values:
LAT_N     LONG_W
-------   ---------
87.654321 131.313131
87.654321 140.404040

... and assume that the value of 87.654321 is the "largest" that occurs for rows with LONG_W < 137.2345. (That is, no other rows with a larger LAT_N.)
Consider the return from this statement:
 SELECT t.long_w
   FROM ( SELECT MAX(s.lat_n) AS largest_lat_n
            FROM station s
           WHERE s.long_w < 137.2345
        ) s
   JOIN station t
     ON t.lat_n = s.largest_lat_n

That's going to return both of the rows. If we do a MAX() function, we're going to get back the higher value, 140.4040404 value. And that doesn't seem to match the specification.  To prevent larger values of LONG_W from being returned, we'd either need to add a predicate to the query (condition in the WHERE clause)
  WHERE t.long_w < 137.2345

Or, we could use an expression in the SELECT list to filter out LONG_W values that don't meet the specification
 SELECT MAX( IF(t.long_w<137.2345,t.long_w,NULL) ) AS long_w

A: You should ROUND the value retrieved like this:
Select ROUND(LONG_W,4)
from STATION
where LAT_N = (
    Select max(LAT_N)
    from STATION where
    LAT_N < 137.2345
);

A: Try this. It is much simple and works fine.
SELECT ROUND(LONG_W,4)
FROM STATION
WHERE LAT_N < 137.2345
ORDER BY LAT_N DESC LIMIT 1;


text:
Q: Does $\sum_{i=0}^\infty{i\left((1-p^{i+1})^m-(1-p^{i})^m\right)}$ go to infinity as $\log m$? Summary
I think that the following sum
$$\sum_{i=1}^\infty{i\left((1-p^{i+1})^m-(1-p^{i})^m\right)}$$
is $O(\log m)$, where $0<p<1$ and $m \geq 1$. However, I was not able to prove it formally, despite my endless efforts (binomial expansions, derivation, majoration, etc. and combination thereof).
Context
I was studying a variation of the skip list data structure.
Each key in a skip list is associated a "tower" of a certain height. Height is chosen by repeatedly tossing a coin: with  probability $p$ the tower grows of one level, with probability $1-p$ we stop.
Consider $m$ keys and the random variable "maximum level of the towers of that $m$ keys". The above expression is the expected value of this RV.
Strangely enough standard literature about skip lists takes a sort of work around to prove that the number of levels are $O(\log n)$ where $n$ is the number of keys in the skip list.
Experiments with Mathematica
It is possible to numerically support my conjecture.
The following is a Mathematica experiment.
maxi = 100;
maxm = 10^9;
G[m_] := Sum[i*((1 - p^(i + 1))^m - (1 - p^i)^m), {i, 0, maxi}];
p = 0.5;
delta = G[m] - Log[1/p, m] /. m -> maxm;
DiscretePlot[{G[m], Log[1/p, m]}, {m, 1, maxm, maxm/200},
 PlotLegends -> "Expressions"]
DiscretePlot[G[m] - Log[1/p, m] - delta, {m, 1, maxm, maxm/100}]

we get chart of both the sum and the log function up to $m=10^9$ and
chart of their difference. The latter chart is a bit funny, I do not know if it is a numerical phenomenon or a ripple of the function itself.

A: Let's denote your sum by $S(m,p)$. First of all, we have
$$S(m,p)=\sum_{k=1}^{\infty}\big(1-(1-p^k)^m\big)=\color{blue}{\sum_{j=1}^{m}(-1)^{j-1}\binom{m}{j}\frac{p^j}{1-p^j}}.$$
(The first equality is obtained, with $a_k=1-(1-p^k)^m$, from
$$\sum_{k=1}^{n}k(a_k-a_{k+1})=\sum_{k=1}^{n}ka_k-\sum_{k=1}^{n+1}(k-1)a_k=\sum_{k=1}^{n}a_k-na_{n+1};$$
to get the second, expand $(1-p^k)^m$ and sum over $k$ first).
A "tool" for this kind of sums is Nørlund–Rice integral (easily verified by oneself):
$$S(m,p)=-\frac{m!}{2\pi i}\oint_{C}F(m,p,z)\,dz,\qquad F(m,p,z)=\frac{(p^{z}-1)^{-1}}{\prod_{j=0}^{m}(z+j)}$$
where $C$ is a closed contour encircling $z=-1,\ldots,-m$ and no other poles of the integrand.
Now, if $C_n$ is the circle $|z|=-(2n+1)\pi/\ln p$ oriented counterclockwise, then
$$0=\lim_{n\to\infty}\frac{m!}{2\pi i}\oint_{C_n}F(m,p,z)\,dz=-S(m,p)+m!\sum_{n\in\mathbb{Z}}\operatorname*{Res}_{z=2n\pi i/\ln p}F(m,p,z);$$
evaluation of the residues gives (not just an asymptotic - an exact one!)
$$S(m,p)=-\frac{1}{2}-\frac{H_m}{\ln p}+\frac{1}{\pi}\sum_{n=1}^{\infty}\frac{1}{n}\Im\prod_{j=1}^{m}\Big(1+\frac{2n\pi i}{j\ln p}\Big)^{-1},$$
where $H_m=\sum\limits_{j=1}^{m}\dfrac{1}{j}$ is the $m$-th harmonic number.
This confirms $\color{blue}{\dfrac{S(m,p)}{\ln m}\underset{m\to\infty}{\longrightarrow}-\dfrac{1}{\ln p}}$, as $H_m=\ln m+O(1)$ when $m\to\infty$.


text:
Q: Elegant way to convert string of values into a Javascript array? I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"

I need it to be a javascript array with numbers:
[1,2,3,4,5,6]

I tried:
var array = new Array("1,2,3,4,5,6".split(","))

But the numbers are still strings in the output:
["1","2","3","4","5","6"]

Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?

A: A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });

A: You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];

Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);

A: Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
    function(item, i)
    {
        return parseInt(item, 10);
    });

A: // jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);

// returns an array of numbers

A: If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");

A: If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);

var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));

http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.


text:
Q: Three monitor gaming with two different video cards I have a Radeon 7450 HD with a DVI monitor connected and a Intel HD 4000 with a DVI and a VGA monitor connected on my machine. I'm running both of them with the three monitors extended in Windows 8.1, all working fine.
But I've been trying to do some three monitor gaming and technologies such as Eyefinity and Intel Collage Display, but it seems that they are only applied to the monitors connected to the card (I can use Collage Display with the two monitors on the Intel). Is there any way I can do three monitor gaming with my setup?

A:
I've been trying to do some three monitor gaming and technologies
  such as Eyefinity and Intel Collage Display,
  but it seems that they are only applied to the monitors connected to the card

True. To use eyefinity you would need to connect all the monitors in the eyefinity setup to AMD card(s). As far as I know that is also true for the Intel GPU.
However there is software which can combine different GPUs (even across brands) and present one GPU to the system. (See Lucid Virtu).  I have not found out if this 'virtual GPU' supports eyefinity like functionality. So the best I can offer is a 'maybe' for your current setup.
However, why not simply connect all three displays to the AMD card and use eyefinity? In my experience that works just fine and it is probably more stable than running a game across different brand/model GPU's.

A: Unfortunately, I don't believe this is possible. If there is a solution for it, then it is far beyond the grasp of both Google and myself. You would require a special piece of software to actually have both the Intel and AMD technologies operating together as it is unlikely either of the technologies are compatible with each other.
As well, the performance of a discrete Radeon HD7450 is not only better than the Intel HD 4000, but it is also likely to pass more "graphics tests" than the integrated chip is. You'd likely have a weird situation where two of the monitors would out-perform the single monitor running off of the integrated chip as well.
I believe you can buy a special kind of hub (not a splitter) that can "add" another port to the discrete graphics card if that might work for you. This is about all of the information I can provide.


text:
Q: Angular FxFlex Layout MediaOberver - calculate active width based on given div? I am trying to customize fxFlex behavior. I have an web application which can be used as a standalone verions (full screen on the web browser) and it can be also be embedded as a web component. Application is responsive - it has mobile (up to 600px), tablet (up to 960px) and standard (over 960px) versions.
The point is, when application runs as a standalone version, resizing window causes expected behavior. When application is embedded, even if it takes some part of the screen (it can be embedded in a div with fixed width) current media width is calculated based on a full screen width.
I uderstand that flex-layout methods (e.g. fxHide.xs) look at mediaObserver.isActive() method which gives output based on window. I am trying to do something with that, but haven't found anything useful so far. Is it possible:

*

*to tell flex-layout to look at specific div width rather than window? E.g. someone have to put div with specific id around embedded application.

*override MediaObserver isActive method?

any other ideas?

A: I mostly just use Flex-Layout, but once in a while when I need to be specific I use CSS media queries - '@media only screen and (max-width: 720px)'. These two methods always work for me. However, a third method is running this code to check if the 'on-screen load' event is mobile or not.
public get isMobileAgent(): boolean {
    const agent = navigator.userAgent || navigator.vendor || (window as any).opera;
    // tslint:disable-next-line:max-line-length
    return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(agent.substr(0, 4)));
  }

A: You could use the offsetWidth of the element to specify a value for a class and then apply rules or other logic based on that.
@ViewChild('container', { static: true}) container: ElementRef;

getFlexClass() {
     return this.container.nativeElement.offsetWidth < 600 ? 'mobile' :
            this.container.nativeElement.offsetWidth < 960 ? 'tablet' : 'standard';
}


text:
Q: How do I click on this link using Selenium in Java I am on this website and I am trying to click on Batch search using the selenium webDriver:
https://metlin.scripps.edu/landing_page.php?pgcontent=mainPage
The HTML code for the link is:
<a href="landing_page.php?pgcontent=batch_search" style="color:white; font-weight:bold; font-size:13px">Batch Search </a >

My attempted solution is:
driver3.findElement(By.linkText("Batch Search")).click();

However, this doesn't seem to work.
Any ideas?

A: linkText is an exact match but there's an extra space character after "Batch Search" that's not present in your query so it won't match.
Either fix the search query or use partialLinkText.

A: I like to use css selectors, which would be:
String selector = "a[href=\"landing_page.php?pgcontent=batch_search\"]";
driver3.findElement(By.cssSelector(selector)).click()


text:
Q: Can this code (for loops) be simplified to look for duplicates, given the multiple conditions? I have snipped some of the code out here to just show the relevant bit:
void CImportOCLMAssignmentHistoryDlg::SetButtonStates()
{
    {
        // Don't allow import into the same assignment more than once.
        CByteArray aryImport;
        aryImport.SetSize(15);
        aryImport[0] = m_iImportOCLMHost;
        aryImport[1] = m_iImportOCLMCohost;
        aryImport[2] = m_iImportOCLMChairman;
        aryImport[3] = m_iImportOCLMOpenPrayer;
        aryImport[4] = m_iImportOCLMClosePrayer;
        aryImport[5] = m_iImportOCLMConductorCBS;
        aryImport[6] = m_iImportOCLMReaderCBS;
        aryImport[7] = m_iImportPTHost;
        aryImport[8] = m_iImportPTCohost;
        aryImport[9] = m_iImportPTChairman;
        aryImport[10] = m_iImportPTHospitality;
        aryImport[11] = m_iImportWTConductor;
        aryImport[12] = m_iImportWTReader;
        aryImport[13] = m_iImportPTSpeaker; // AJT v17.0.8
        aryImport[14] = m_iImportPTTheme;   // AJT v17.0.8

        COptionsDlg dlgOptions;
        REPORT_MODE_E eMode = dlgOptions.GetReportMode();
        bool bDuplicateAssignment = false;

        if (eMode == MODE_MEETING)
        {
            // The index values can't be duplicated within each meeting
            // Midweek 0 to 6
            // Weekend 7 to 14

            // Midweek
            for (int iAssignment = 0; iAssignment < 7; iAssignment++)
            {
                if (aryImport[iAssignment] != (BYTE)-1)
                {
                    for (int iAssignment2 = iAssignment + 1; iAssignment2 < 7; iAssignment2++)
                    {
                        if (aryImport[iAssignment2] == aryImport[iAssignment])
                        {
                            bDuplicateAssignment = true;
                            break;
                        }
                    }
                    if (bDuplicateAssignment)
                        break;
                }
            }

            if (!bDuplicateAssignment)
            {
                // Weekend
                for (int iAssignment = 7; iAssignment < aryImport.GetSize(); iAssignment++)
                {
                    if (aryImport[iAssignment] != (BYTE)-1)
                    {
                        for (int iAssignment2 = iAssignment + 1; iAssignment2 < aryImport.GetSize(); iAssignment2++)
                        {
                            if (aryImport[iAssignment2] == aryImport[iAssignment])
                            {
                                bDuplicateAssignment = true;
                                break;
                            }
                        }
                        if (bDuplicateAssignment)
                            break;
                    }
                }
            }
        }
        else
        {
            // The index values can't be duplicated anywhere in the array
            for (int iAssignment = 0; iAssignment < aryImport.GetSize(); iAssignment++)
            {
                if (aryImport[iAssignment] != (BYTE)-1)
                {
                    for (int iAssignment2 = iAssignment + 1; iAssignment2 < aryImport.GetSize(); iAssignment2++)
                    {
                        if (aryImport[iAssignment2] == aryImport[iAssignment])
                        {
                            bDuplicateAssignment = true;
                            break;
                        }
                    }
                    if (bDuplicateAssignment)
                        break;
                }
            }
        }

        if (bDuplicateAssignment)
            m_btnImport.EnableWindow(FALSE);
        else
            m_btnImport.EnableWindow(TRUE);
    }
}

The code is functional. I just wondered if it could be simplified without over-complicating readability.
No need to comment on my use of literal integers instead of #define or enum values. I am aware of that improvement. It is primarily the way I go about looking for duplicates. Can it be simplified?

A: Instead of two nested passes through your array, you can use a bitmap to check for duplicates:
bool CImportOCLMAssignmentHistoryDlg::DetectDuplicateAssignment(CByteArray &aryImport, INT_PTR iMin, INT_PTR iMax)
{
  std::vector<bool> found(256);
  for (INT_PTR iAssignment = iMin; iAssignment < iMax; iAssignment++)
  {
    auto value = aryImport[iAssignment];
    if (value != (BYTE)-1)
    {
      if (found[value])
        return true;
      found[value] = true;
    }
  }
  return false;
}

To make it more C++'y, use std::vector<bool> found(256); instead of C-style array; also saves some space.

A: I have done it like this for now:
void CImportOCLMAssignmentHistoryDlg::SetButtonStates()
{
    {
        // Don't allow import into the same assignment more than once.
        CByteArray aryImport;
        aryImport.SetSize(15);
        aryImport[0] = m_iImportOCLMHost;
        aryImport[1] = m_iImportOCLMCohost;
        aryImport[2] = m_iImportOCLMChairman;
        aryImport[3] = m_iImportOCLMOpenPrayer;
        aryImport[4] = m_iImportOCLMClosePrayer;
        aryImport[5] = m_iImportOCLMConductorCBS;
        aryImport[6] = m_iImportOCLMReaderCBS;
        aryImport[7] = m_iImportPTHost;
        aryImport[8] = m_iImportPTCohost;
        aryImport[9] = m_iImportPTChairman;
        aryImport[10] = m_iImportPTHospitality;
        aryImport[11] = m_iImportWTConductor;
        aryImport[12] = m_iImportWTReader;
        aryImport[13] = m_iImportPTSpeaker; // AJT v17.0.8
        aryImport[14] = m_iImportPTTheme;   // AJT v17.0.8

        COptionsDlg dlgOptions;
        REPORT_MODE_E eMode = dlgOptions.GetReportMode();
        bool bDuplicateAssignment = false;

        if (eMode == MODE_MEETING)
        {
            // The index values can't be duplicated within each meeting
            // Midweek 0 to 6
            // Weekend 7 to 14

            // Midweek
            bDuplicateAssignment = DetectDuplicateAssignment(aryImport, 0, 7);

            if (!bDuplicateAssignment)
            {
                // Weekend
                bDuplicateAssignment = DetectDuplicateAssignment(aryImport, 7, aryImport.GetSize());
            }
        }
        else
        {
            // The index values can't be duplicated anywhere in the array
            bDuplicateAssignment = DetectDuplicateAssignment(aryImport, 0, aryImport.GetSize());
        }

        if (bDuplicateAssignment)
            m_btnImport.EnableWindow(FALSE);
        else
            m_btnImport.EnableWindow(TRUE);
    }
}

bool CImportOCLMAssignmentHistoryDlg::DetectDuplicateAssignment(CByteArray &aryImport, INT_PTR iMin, INT_PTR iMax)
{
    bool bDuplicateAssignment = false;

    for (INT_PTR iAssignment = iMin; iAssignment < iMax; iAssignment++)
    {
        if (aryImport[iAssignment] != (BYTE)-1)
        {
            for (INT_PTR iAssignment2 = iAssignment + 1; iAssignment2 < iMax; iAssignment2++)
            {
                if (aryImport[iAssignment2] == aryImport[iAssignment])
                {
                    bDuplicateAssignment = true;
                    break;
                }
            }
            if (bDuplicateAssignment)
                break;
        }
    }

    return bDuplicateAssignment;
}

If anyone has an alternative approach please let me know. Thanks.


text:
Q: Why are these problems well posed? I've the following definition:

The problem $(f, x)$ is well-posed in $E_\delta(x)$ if a constant $L_{abs}\geq 0$ exists such that $$|f(\widetilde{x}) - f(x)| \leq L_{abs}|\widetilde{x} - x|$$ If such a constant $L_{abs}$ does not exist, the problem is called ill-posed.

Here's the measurement is done in absolute error, but there's also a version in terms of relative error.
Then I've the following examples:

*

*The constant mapping $f : \mathbb{R} \mapsto \mathbb{R}$, $f (x) := 0$ is clearly well posed. It is even "destroying" information

*The linear mapping $f : \mathbb{R} \mapsto \mathbb{R}$, $f(x) := ax$, $0 \neq a \in \mathbb{R}$ is also well-posed $\forall x \in \mathbb{R}$. Obviously, we have $L_{abs} =a$.

*The problem $f : \mathbb{R} \mapsto \mathbb{R}$, $f(x):= |x|$ is ill-posed at $x=0$.

I've a few questions regarding these examples.
For all 3 cases, I don't understand why one can claim that the problem is well posed based on the definition.
Regarding the second example, why $L_{abs} = a$?

A: For the first case:
$\forall x, y \; |f(x) - f(y) | = |0 -  0| = 0$ so taking $L_{abs}  > 0$ it is always true that $|f(x) - f(y)| \leq L_{abs}  |x -  y|$.
For the linear mapping $x \mapsto ax$:
$\forall x, y \; |f(x) - f(y)| = |ax -  ay| = |a(x-y)| = |a||x-y|$
So $L_{abs}  = |a|$. Note that the definition is with $L_{abs}  \geq 0$ while the example states $a \in \mathbb{R}^*$ so I think there's an issue and that it should be $|a|$ and not $a$.
For the third case:
Let $x = 0$ and $\tilde{x}  = x + \epsilon = \epsilon$ with $|\epsilon| < \delta$.
If $\epsilon > 0$ then $|\epsilon| = \epsilon$ and $\epsilon \leq L_{abs}  \epsilon$ for any $L_{abs} \geq 1$.
If $\epsilon < 0$ then $|\epsilon| = - \epsilon$ and the definition gives $-\epsilon \leq L_{abs} (-\epsilon) $ which is true for $L_{abs} \leq 1$.
So this leaves us with $L_{abs} = 1$ for $x = 0$ and $\tilde{x}$ in the open ball of center $x$ and radius $\delta$, so not sure why the example says the problem is ill-posed  at $0$.
Note however that the absolute value function is not differentiable at $0$.

A: For $2)$, setting $f(x):=ax$ gives : $|f(x)-f(x')| = |a||x-x'|$ and then you can choose $L_{abs} = |a|$. So by your definition, the problem is well-posed.
For $1)$, it's even better, every constant $\lambda >0$ can be chosen for $L_{abs}$ since : $|f(x)-f(x')| = 0 \leq \lambda |x-x'|$.
For $3)$, with $x=0$, we have $|f(x)-f(x')| = |x'| = |x'-0|$ so you can choose $L_{abs} = 1$.


text:
Q: What is the typical speed that PHP connects to MySQL? Say I have very standard mysql connection code:
$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

A: One possibility is that mysql is doing a DNS lookup to find the name of the connecting server; depending on your setup, this could take a long time.  There's not really much benefit to it, aside from being able to specify the users by hostname rather than IP address (e.g. user@example.com rather than user@192.168.1.1).
This can be disabled in the configuration or when starting up MySQL with the --skip-name-resolve parameter.  More information is available on the MySQL site.

A: 2 seconds does seem slow, but it depends on your server and database server. Depending on what else they are doing, where they are located and many other factors it could actually be fast.
I usually get times of less than a second.

A: For local LAN, unless you're using antiquated equipment, or something is wrong, it should typically be on the order of (a) millisecond(s).

A: Do you have lots of tables?  It may be spending time looking around after connecting.  Is the command line mysql client slow too?  Is it fast if you're connecting from localhost?

A: That is very slow. On avarage websites, the entire page renders within two seconds. That is, connecting to the database, running the queries, retrieving results and rendering the page.


text:
Q: Rails 3: Custom error message in validation I don't understand why the following is not working in Rails 3. I'm getting "undefined local variable or method `custom_message'" error.
validates :to_email, :email_format => { :message => custom_message }

def custom_message
  self.to_name + "'s email is not valid"
end

I also tried using :message => :custom_message instead as was suggested in  rails-validation-message-error post with no luck.
:email_format is a custom validator located in lib folder:
class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || 'is not valid')
    end
  end
end

A: Just for reference, this is what I believe is going on. The 'validates' method is a class method, i.e. MyModel.validates(). When you pass those params to 'validates' and you call 'custom_message', you're actually calling MyModel.custom_message. So you would  need something like
def self.custom_message
  " is not a valid email address."
end

validates :to_email, :email_format => { :message => custom_message }

with self.custom_message defined before the call to validates.

A: If anyone is interested I came up with the following solution to my problem:
Model:
validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" }

lib/email_format_validator.rb:
class EmailFormatValidator < ActiveModel::EachValidator

  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

      error_message = if options[:message] && options[:name_attr]
        object.send(options[:name_attr]).capitalize + options[:message]
      elsif options[:message]
        options[:message]
      else
        'is not valid'
      end

      object.errors[attribute] << error_message
    end
  end
end

A: Maybe the method "custom_message" needs to be defined above the validation.


text:
Q: RegExp test jQuery I'm using some jQuery/JavaScript to detect the path name of the page and assign an id to its link within the navigation. It essentially changes the link text from black to blue.  Anyway, I've borrowed some of the code and I'm not advanced enough to figure out the RegExp test part, but when it passes the homepage as the path /, it assigns the id to all the links in the navigation (/index.html passes fine).  Can someone help me figure out why the test is not working properly on the path name /?
$(function() {
    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");

    $('.nav ul li a').each(function() {
        if (urlRegExp.test(this.href.replace(/\/$/,''))) {
            $(this).attr('id', 'selected');
        }
    });

    $(function() {
        if (url === "/index.html" || url === "/") {
            $('.nav').attr('id','homenav');
        }
    });
});

A: This should accomplish the same task:
var trailing_slash_re = /\/$/,
canon_url = location.pathname.replace(trailing_slash_re, '');

$('.nav ul li a').each(function() {
  var this_url = this.href.replace(trailing_slash_re, '');
  if (this_url.substr(-canon_url.length) == canon_url) {
    this.id = 'selected';
    return false; // don't process any others
  }
});

For each link it determines whether it ends with the canon_url. I'm jumping out of the loop once it has found an anchor that matches. This avoids multiple selected id's.

A: To explain your situation

*

*when you are setting up
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); you are first removing the trailing slash. This is done by your regex /\/$/.

*When you pass in / you will remove that slash and the resulting regex is /$/. This will match anything since all it is looking for is $ (which in regex indicates the end of the string). A solution will likely involve handling the / case specifically (as you indicated you have already done and the solution above does).
If you want to mess around with regex I have found that a good resource is http://gskinner.com/RegExr/


text:
Q: When will NSautorelease release this? Okay say I have a function like below:
-(NSNumber *)calculate{
  NSNumber *myNum = [[[NSNumber alloc]initWithInt:5] autorelease];
  return myNum;
}

When will myNum be released? Will whenever I call calculate, myNum will be created and added to the stack?
Also say I have a property like:
@property (nonatomic, retain) NSMutableArray *inputsArr;

and I synthesized it as:
@synthesize inputsArr = _inputsArr;

and I alloc and initiate it in the code of one of mu functions..
How would I go about releasing this memory? any guides to CoaCoa memory management...I can only find really confusing or obvious guides..
Thanks in advance

A: autorelease pools are thread local stacks -- you push and pop them. the deferred release message will be sent to the object when the pool is destroyed.
consider this:
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSNumber * n = [NSNumber numberWithDouble:1.0/17.0]; << n is autoreleased
[n self]; << OK!
[pool release]; << n is messaged release
[n self]; << BAM!

So 'when' really depends on how the autorelease pools are built -- but it's always possible to ensure your objects outlive a local pool, so this is never a restriction:
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSNumber * n = [NSNumber numberWithDouble:1.0/17.0]; << n is autoreleased
[n self]; << OK!
[n retain];
[pool release]; << n is messaged release
[n self]; << OK!
[n release];
[n self]; << BAM!

The above is what you should rely on. In some real world cases, an object may still be alive  where you would expect "BAM!", but you should never rely on "well, it should have been destroyed, but it seems to work alright".

A: The NSApplication class sets up autorelease pools (instances of the NSAutoreleasePool class) during initialization and inside the event loop—specifically, within its initialization (or sharedApplication) and run methods. generally autorelease pool is popped  at the end of the event loop, but this depends on you or the app.
If you are going to be using lots of temporary objects (autoreleased / from convenience methods) you may want to think about creating your own short-term autorelease pools to avoid temporary memory peaks.Autorelease objects are added to the latest autorelease pool to be created.
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // create your own little autorelease pool
  // these objects get added to the autorelease pool you created above
  NSNumber *aNumber1 = [NSNumber numberWithFloat:1]; // refcount is 1, you are not owner, will be automatically released
  NSNumber *aNumber2 = [NSNumber numberWithFloat:2]; // refcount is 1, you are not owner, will be automatically released
  NSNumber *aNumber3 = [NSNumber numberWithFloat:3]; // refcount is 1, you are not owner, will be automatically released
  NSNumber *aNumber4 = [NSNumber numberWithFloat:4]; // refcount is 1, you are not owner, will be automatically released
  NSNumber *aNumber5 = [NSNumber numberWithFloat:5]; // refcount is 1, you are not owner, will be automatically released
  NSNumber *aNumber6 = [NSNumber numberWithFloat:6]; // refcount is 1, you are not owner, will be automatically released

  // ... do a bunch of stuff with all objects above.
  ...

  [pool release]; // all objects added to this pool (the ones above) are released

Take a look at Memory Management with Objective C / Cocoa / iPhone.


text:
Q: A smoothed series still exibits strong seasonality I have a monthly time series. It is basically a price level series (inflation data), and I converted it into monthly percentage changes (i.e. like the CPI measure). This time series exhibits extremely large seasonality on an annual period. I did a moving average filter of period 12, and my intuition was that this would smooth the seasonality. However, when I checked I found that the smoothed series ACF still had a large spike at 12 months, and no other statistically significant spikes, but the PACF has spikes at 12 and 24. The best fitting arima type was (0,1,0)(2,0,0)[12]. This is significantly better than any non-seasonal model. The SAR coefficients are (1) -0.5 and (2) -0.3.
If I do a seasonal decomposition, then I discover that the the MA has reduced the cyclical component (of period 12) to almost zero, as I expected.
What is the intuitive explanation of these results, does it perhaps mean that there is a longer cycle, of say 24 months? Decomposing on 24 months reveals a small but not entirely negligible seasonal component, yet the SAR coefficients are large.
In short, I am confused of the conditions under which a Moving average filter of appropriate period does not remove the need for seasonality from an ARIMA type model.

A: The filter/equation that you are using is evidentially insufficient for your data. Naive identification tools often tacitly ignore the possibility of incorporating more complicated/generalized approaches. If you post your data in excel format I will try and help you in this regard.


text:
Q: Locked out of ESXi 6.0 host, but can login to console. How to grant access via ESXCli? VMware's KB's on this are not helping, I cannot find what I need for my exact situation: I am locked out of vSphere, but can login locally to the ESXi host at the console (physically, standing at the KVM) EDIT: I just found out this is called the DCUI. I have enabled SSH and the ESXi shell, but cannot login to either one of them either. What are my options here? I believe what happened is my predecessor setup vCSA 6 on this host (and set vCenter to manage the host itself, thus locking it), but I am not sure since I cannot get into either. Thank you.

A: It sounds like the host is in lockdown mode. If so, you'll need to disable lockdown mode. Refer to this article on the procedure:
https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1008077


text:
Q: how to filter array object using object property I got an array of object
    const devices = [{
    deviceLocation: {
      label: "Pure",
      value: "pure"
    },
    deviceName: "test7"
    devicePaymentMethods: [{
      label: "ab",
      value: "ab"
    } {
      label: "cd",
      value: "cd"
    } {
      label: "ef",
      value: "ef"
    }]
    deviceType: "iPad"
    id: "001"
    connected: false
    enabled: false
  },

  {
    deviceLocation: {
      label: "kandy",
      value: "kandy"
    },
    deviceName: "test4"
    devicePaymentMethods: [{
      label: "ab",
      value: "ab"
    } {
      label: "cd",
      value: "cd"
    }]
    deviceType: "iPad"
    id: "004"
    connected: false
    enabled: false
  }
]

I want to filter the array by object using deviceName,deviceLocation and devicePaymentMethods
Here is what I have already done and it is working for deviceName and deviceLocation  but doesn't work for devicePaymentMethods
const filterByValue = (array, string) => {
return array.filter(o =>
  Object.keys(o).some(k => {
    if (k === "deviceName") {
      return o[k].toLowerCase().includes(string.toLowerCase());
    } else if (k === "deviceLocation") {
      return o[k].label.toLowerCase().includes(string.toLowerCase());
    } else if (k === "devicePaymentMethods") {
       o[k].map(pay => {
          if(pay.label.toLowerCase().includes(string.toLowerCase()))
        return pay;
      });
    }
  })
);
};

 filterByValue(devices, "ab")

A: You forget to mentioned return while filtering the data inside map
return o[k].map(pay => {
  if(pay.label.toLowerCase().includes(string.toLowerCase()))
    return pay;

const devices = [{
    deviceLocation: {
      label: "Pure",
      value: "pure"
    },
    deviceName: "test7",
    devicePaymentMethods: [{
      label: "ab",
      value: "ab"
    }, {
      label: "cd",
      value: "cd"
    }, {
      label: "ef",
      value: "ef"
    }],
    deviceType: "iPad",
    id: "001",
    connected: false,
    enabled: false,
  },
  {
    deviceLocation: {
      label: "kandy",
      value: "kandy"
    },
    deviceName: "test4",
    devicePaymentMethods: [{
      label: "ab",
      value: "ab"
    }, {
      label: "cd",
      value: "cd"
    }],
    deviceType: "iPad",
    id: "004",
    connected: false,
    enabled: false,
  }
];

const filterByValue = (array, string) => {
  return array.filter(o =>
    Object.keys(o).some(k => {
      if (k === "deviceName") {
        return o[k].toLowerCase().includes(string.toLowerCase());
      } else if (k === "deviceLocation") {
        return o[k].label.toLowerCase().includes(string.toLowerCase());
      } else if (k === "devicePaymentMethods") {
        return o[k].some(pay => {
          if (pay.label.toLowerCase().includes(string.toLowerCase())) {
            return pay;
          }
        });
      }
    })
  );
};

console.log(filterByValue(devices, "ab"));
console.log(filterByValue(devices, "ef"));

A: You could take a slightly different approach with an array of wanted keys and keys for nested array for search.

const
    keys = [['deviceName'], ['deviceLocation', 'label'], ['devicePaymentMethods', 'label']],
    filterByValue = (array, string) => array.filter(object => keys.some(([key, sub]) => {
        if (!(key in object)) return false;
        if (typeof object[key] === 'string' && object[key].toLowerCase() === string) return true;
        if (Array.isArray(object[key]) && sub)
            return object[key].some(o => o[sub].toLowerCase() === string);
    })),
    devices = [{ deviceLocation: { label: "Pure", value: "pure" }, deviceName: "test7", devicePaymentMethods: [{ label: "ab", value: "ab" }, { label: "cd", value: "cd" }, { label: "ef", value: "ef" }], deviceType: "iPad", id: "001", connected: false, enabled: false }, { deviceLocation: { label: "kandy", value: "kandy" }, deviceName: "test4", devicePaymentMethods: [{ label: "ab", value: "ab" }, { label: "cd", value: "cd" }], deviceType: "iPad", id: "004", connected: false, enabled: false }],
    result = filterByValue(devices, "ab");

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Cannot delete a Kafka topic in Windows I have set the Zookeeper properties of "delete.topic.enable" to true. But I still cannot delete the topic. When I do mvn install or mvn test, I got following problems:
WARN Error processing kafka.log:type=LogManager,name=LogDirectoryOffline,logDirectory=C:\Users\extznq\AppData\Local\Temp\EH4Test7267133751803693562 (com.yammer.metrics.reporting.JmxReporter:397)
javax.management.MalformedObjectNameException: Invalid character ':' in value part of property

ERROR Error while deleting healthchecktopic1516638375589-0 in dir C:\Users\extznq\AppData\Local\Temp\EH4Test9083449671042580730. (kafka.server.LogDirFailureChannel:107)
        java.io.IOException: Failed to rename log directory from C:\Users\{My-topic-path} to C:\Users\{My-topic-path}-0.0a40ae7410c2401aba0816891789c334-delete
            at kafka.log.LogManager.asyncDelete(LogManager.scala:671)
            at kafka.cluster.Partition$$anonfun$delete$1.apply(Partition.scala:178)
            at kafka.cluster.Partition$$anonfun$delete$1.apply(Partition.scala:173)
            at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:217)
            at kafka.utils.CoreUtils$.inWriteLock(CoreUtils.scala:225)
            at kafka.cluster.Partition.delete(Partition.scala:173)
            at kafka.server.ReplicaManager.stopReplica(ReplicaManager.scala:341)
            at kafka.server.ReplicaManager$$anonfun$stopReplicas$2.apply(ReplicaManager.scala:373)
            at kafka.server.ReplicaManager$$anonfun$stopReplicas$2.apply(ReplicaManager.scala:371)
            at scala.collection.Iterator$class.foreach(Iterator.scala:891)
            at scala.collection.AbstractIterator.foreach(Iterator.scala:1334)
            at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
            at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
            at kafka.server.ReplicaManager.stopReplicas(ReplicaManager.scala:371)
            at kafka.server.KafkaApis.handleStopReplicaRequest(KafkaApis.scala:190)
            at kafka.server.KafkaApis.handle(KafkaApis.scala:104)
            at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:65)
            at java.lang.Thread.run(Thread.java:745)

ERROR [Broker id=0] Ignoring stop replica (delete=true) for partition healthchecktopic1516728986980-0 due to storage exception (state.change.logger:107)
org.apache.kafka.common.errors.KafkaStorageException: Error while deleting healthchecktopic1516728986980-0 in dir C:\Users\AppData\Local\Temp\EH4Test7267133751803693562.
Caused by: java.io.IOException: Failed to rename log directory from C:\Users\AppData\Local\Temp\EH4Test7267133751803693562\healthchecktopic1516728986980-0 to C:\Users\AppData\Local\Temp\EH4Test7267133751803693562\healthchecktopic1516728986980-0.65fc6c32c44940e58c1a45bd2972523a-delete
    at kafka.log.LogManager.asyncDelete(LogManager.scala:671)

I think the Warning is all right. But I do not know why I would get errors, although I run the Eclipse as administrator. Especially, the KafkaStorageException, I still have 50GB in my computer.
Environment:

*

*Windows 10

*Zookeeper 3.5.3-beta

*Kafka 1.0.0

A: looks like you have an invalid character in the properties: Invalid character ':' in value part of property; also in the line below it seems that the placeholder you are using it is not replaced properly: C:\Users\{My-topic-path}
Furthermore there is an open issues related to file operation such as moving/delete in windows environment, I got the same problem upgrading from 0.10.2.1 to 1.1.0
This is the link to the issue: KAFKA-1194


text:
Q: Elementary proof that projective space is a quotient Fix an algebraically closed † ground field $k$ of any characteristic.  I want to use the classical definition of projective $n$-space $\mathbb{P}^n$ as set quotient of $\mathbb{A}^{n+1}\setminus 0$ by the action of $k^*$, and for its Zariski topology the definition that closed sets are the "zero sets" of homogeneous polynomials in $n+1$ variables considered as functions from $\mathbb{P}^n$ to {$0,1$}.
I'm not satisfied with my understanding of why this is the same as the quotient topology from the map $\mathbb{A}^{n+1}\setminus 0\to \mathbb{P}^{n}$.  This means proving the map is surjective, continuous, and that a set with closed pre-image is closed, the first two properties being clear.  The last part is the least trivial, meaning that:

If a set $S\subseteq \mathbb{P}^n$ has closed preimage $\widehat{S}$ in $\mathbb{A}^{n+1}\setminus 0$, i.e. $\widehat{S}$ is cut out by some polynomials $f_1,\ldots,f_r$, then $S$ is closed in $\mathbb{P}^n$, i.e. $\widehat{S}$ is cut out by some homogeneous polynomials $g_1,\ldots,g_s$.

I'm bad at algebra, so I can't seem to start doing anything here that doesn't look ugly/hard... I really want to "see" what's going on and avoid just quoting results about invariants without understanding how they work in this "toy" example.
Thanks for the help, anyone!
† Follow up: the algebraic closed hypothesis is not necessary, since David/Kevin's proof works for any infinite field, and for a finite field our spaces (as defined here) are discrete so the result is trivial.

A: Let $f$ be a polynomial which vanishes on $\hat{S}$. Write $f=\sum f_i$, where $f_i$ is homogenous of degree $i$. The set $\hat{S}$ is homogenous so, for any $\lambda \in k^*$, the polynomial $f(\lambda \cdot x) = \sum \lambda^i f_i$ also vanishes on $f$.
Since $k$ is infinite, we can find more equations of the form $\sum \lambda^i f_i=0$ than there are terms in $f$. Taking linear combinations, we deduce that each $f_i$ individually vanishes on $\hat{S}$.

A: Look at the subspace of $\mathbf{A}^{n+1}$ cut out by your polynomials. This set is invariant under the diagonal action of $k^\times$. So the functions that vanish on it will be an ideal $I$ (the radical of the ideal generated by your $f_i$) which is invariant under this action. But because $k$ is infinite, it's now relatively easy to check that if $f\in I$ and if you write $f$ as a sum of homogeneous pieces, then each homogeneous piece will be in $I$ too (the point is that the homogeneous pieces scale differently under $k^\times$ so if the degree of f is $d$ then you just use $d+1$ elements of $k^\times$ and then put a linear combination of them together and use the fact that a certain Van der Monde determinant isn't zero). Hence $I$ is generated by homogeneous elements and now you're home, unless I missed something.


text:
Q: No se muestra ImageView al emular la aplicación Quiero añadir dos ImageView a mi layout. En la Preview de Android Studio se muestran correctamente las imágenes con la API 22 pero al emular la aplicación en mi móvil de API 22 las imágenes no se ven. Utilizo la ultima versión de Android Studio y no encuentro el motivo de porque no se muestran correctamente las imágenes.
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="1"
android:id="@+id/cont">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="beforeDescendants"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:id="@+id/scroll">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:descendantFocusability="beforeDescendants"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:id="@+id/total">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="288dp"
            android:descendantFocusability="beforeDescendants"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:id="@+id/form">

            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="200dp"
                android:layout_marginTop="90dp"
                app:hintTextAppearance="@style/TextLabel"
                android:layout_marginLeft="100dp"
                android:scrollbarSize="20dp"
                android:id="@+id/usu"
                android:descendantFocusability="beforeDescendants"
                android:focusableInTouchMode="true">

                <EditText
                    android:layout_height="match_parent"
                    android:hint="Correo"
                    android:inputType="textEmailAddress"
                    android:layout_width="200dp"
                    android:id="@+id/correo" />
            </android.support.design.widget.TextInputLayout>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:theme="?attr/actionBarTheme"
                android:minHeight="?attr/actionBarSize"
                android:id="@+id/toolbar"
                android:layout_weight="0.13" />

            <android.support.design.widget.TextInputLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:hintTextAppearance="@style/TextLabel"
                android:id="@+id/co"
                android:layout_marginTop="25dp"
                android:layout_below="@+id/usu"
                android:layout_alignLeft="@+id/usu"
                android:layout_alignStart="@+id/usu">

                <EditText
                    android:layout_width="200dp"
                    android:layout_height="match_parent"
                    android:hint="Contraseña"
                    android:layout_above="@+id/textInputLayout"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:layout_weight="1"
                    android:id="@+id/pass" />
            </android.support.design.widget.TextInputLayout>

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                app:srcCompat="@drawable/key"
                android:id="@+id/imageView3"
                android:layout_alignBottom="@+id/co"
                android:layout_alignLeft="@+id/imageView2"
                android:layout_alignStart="@+id/imageView2"
                android:layout_marginBottom="8dp" />

            <ImageView
                android:layout_height="50dp"
                app:srcCompat="@drawable/user"
                android:layout_marginRight="16dp"
                android:layout_marginEnd="16dp"
                android:id="@+id/imageView2"
                android:layout_above="@+id/co"
                android:layout_toLeftOf="@+id/co"
                android:layout_toStartOf="@+id/co"
                android:layout_marginBottom="8dp"
                android:layout_width="50dp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="248dp">

            <Button
                android:text="Entrar"
                android:layout_width="150dp"
                android:layout_height="50dp"
                android:drawableLeft="@drawable/login"
                android:textColor="@android:color/white"
                android:backgroundTint="#CDDC39"
                android:id="@+id/entrar"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="26dp" />

            <TextView
                android:text="Aun no eres usuario?"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView"
                android:textSize="20sp"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true" />

            <Button
                android:text="Registrate"
                android:layout_height="50dp"
                android:drawableLeft="@drawable/account"
                android:id="@+id/registro"
                android:textColor="@android:color/white"
                android:backgroundTint="#CDDC39"
                android:layout_weight="0.13"
                android:layout_width="150dp"
                android:layout_below="@+id/textView"
                android:layout_alignLeft="@+id/entrar"
                android:layout_alignStart="@+id/entrar"
                android:layout_marginTop="30dp" />

        </RelativeLayout>
    </LinearLayout>
</ScrollView>

styles.xml
    <resources>
<!-- Base application theme. -->
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#CDDC39</item>

    <item name="colorPrimaryDark">#AFB42B</item>

    <item name="colorAccent">#FFC107</item>

</style>
<style name="AppTheme" parent="AppTheme.Base"></style>
<style name="AppTheme.Base2" parent="Theme.AppCompat.Light">

    <item name="colorPrimary">#CDDC39</item>

    <item name="colorPrimaryDark">#AFB42B</item>

    <item name="colorAccent">#518B05</item>

</style>
<style name="AppTheme2" parent="AppTheme.Base"></style>
<style name="TextLabel" parent="TextAppearance.Design.Hint">
    <item name="android:textSize">20sp</item>
</style>
</resources>

AndroidManifest.xml
   <?xml version="1.0" encoding="utf-8"?>

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Sesion.Registro"

        android:parentActivityName=".Sesion.Login">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".Sesion.Login" />
    </activity>
    <activity android:name=".Sesion.Login"
        android:windowSoftInputMode="stateUnspecified">
    </activity>

</application>

Login.java
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.libreria.conxi.proyecto.R;

    import static android.content.ContentValues.TAG;

    public class Login extends Activity {
private FirebaseAuth mAuth;

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

    mAuth = FirebaseAuth.getInstance();

    //Boton para dirigir a la Activity de Registro
    Button btn2 = (Button) findViewById(R.id.registro);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent2 = new Intent (v.getContext(), Registro.class);
            startActivityForResult(intent2, 0);
        }
    });

    //Boton para entrar en el usuario
    Button btn = (Button) findViewById(R.id.entrar);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText correo = (EditText) findViewById(R.id.correo);
            EditText pass = (EditText) findViewById(R.id.pass);

            String email=correo.getText().toString();
            String password=pass.getText().toString();

            if (email.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                return;
            }

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (!task.isSuccessful()) {
                                // there was an error
                                Log.w(TAG, "signInWithEmail", task.getException());
                                Toast.makeText(Login.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                Log.w(TAG, "signInWithEmail", task.getException());
                                Toast.makeText(Login.this, "Authentication success.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                        }
    });
}
    }

¿ Alguna idea para solucionar este problema ?

A: Cuando usas   app:srcCompat="@drawable/user", debes definir: android:background="@mipmap/user" esta propiedad de esta manera podrás cargar el recurso, no tiene sentido para mi... pero es la única forma que logre solventar el problema

A: Porqué no usas android:src="@drawable/user" directamente en lugar de app:srcCompat="@drawable/user" ?

A: Prueba lo siguiente:
public class Login extends Activity

En esta linea de tu java, debes poner:
public class Login extends AppCompatActivity

A: Si estas usando propiedades de las clases de soporte tu Activity debe extender de AppCompatActivity
Si usas vector assets, que tienen esta estructura:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
 ...
 ...
</vector>

puedes usar :
 app:srcCompat="@drawable/..."

de otra forma si son imágenes de formato .png, .jpg usa simplemente :
 android:src="@drawable/..."


text:
Q: AcquireTokenAsync method - Unable to get the token using ClientCredentials in Here I want to retrieve data from CRM and have registered it in Azure to to get Client Credentials and using it in below code:
using Microsoft.Crm.Sdk.Messages;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.WebServiceClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM_WebAPI_Test1
{
    class Program
    {
        static void Main(string[] atrgs)
        {
            MainAsync();
        }
        static async void MainAsync()
        {
            try
            {
                string organizationUrl = "https://OrgName<<URL>>.com";
                string clientId = "xxxxxxxxx-xxxx-xxxx-b7ca-xxxx";
                string clientSecret = "key received from Azure App Registration";
                string aadInstance = "https://login.microsoftonline.com/";
                string tenantID = "orgname";

                ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret);
                AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
                AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientCredentials);
                var requestedToken = authenticationResult.AccessToken;

                using (var sdkService = new OrganizationWebProxyClient(GetServiceUrl(organizationUrl), false))
                {
                    sdkService.HeaderToken = requestedToken;

                    OrganizationRequest request = new OrganizationRequest()
                    {
                        RequestName = "WhoAmI"
                    };

                    WhoAmIResponse response = sdkService.Execute(new WhoAmIRequest()) as WhoAmIResponse;
                    Console.WriteLine(response.UserId);

                    Console.WriteLine("Press any key to exit...");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
        }
        static private Uri GetServiceUrl(string organizationUrl)
        {
            return new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2");
        }
    }
}

But when it come to line:

AuthenticationResult authenticationResult = await
  authenticationContext.AcquireTokenAsync(organizationUrl,
  clientCredentials);

It directly exists the program and not giving any output, not even hitting the catch exception part. Is there anything I am missing here?
Also, how to know the tenant name while registering the application in Azure AD?
UPDATE: [Updating in question because not able to write down whole error in comment section so please bare with it.] After applying code changes as suggestion it is throwing error as below:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException:
  AADSTS50001: The application named https://orgname.com was
  not found in the tenant named mydirectory.onmicrosoft.com.  This can
  happen if the application has not been installed by the administrator
  of the tenant or consented to by any user in the tenant.  You might
  have sent your authentication request to the wrong tenant. Trace ID:
  58b1b994-eac3-4209-b553-4cea6a120500 Correlation ID:
  fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208 Timestamp: 2017-11-29 09:09:37Z
  ---> System.Net.Http.HttpRequestException:  Response status code does not indicate success: 400 (BadRequest). --->
  Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException:
  {"error":"invalid_resource","error_description":"AADSTS50001: The
  application named https://orgname.com was not found in the
  tenant named mydirectory.onmicrosoft.com.  This can happen if the
  application has not been installed by the administrator of the tenant
  or consented to by any user in the tenant.  You might have sent your
  authentication request to the wrong tenant.\r\nTrace ID:
  58b1b994-eac3-4209-b553-4cea6a120500\r\nCorrelation ID:
  fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208\r\nTimestamp: 2017-11-29
  09:09:37Z","error_codes":[50001],"timestamp":"2017-11-29
  09:09:37Z","trace_id":"58b1b994-eac3-4209-b553-4cea6a120500","correlation_id":"fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208"}:
  Unknown error    --- End of inner exception stack trace ---    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.HttpClientWrapper.d__31.MoveNext()
  --- End of inner exception stack trace ---    at Microsoft.IdentityModel.Clients.ActiveDirectory.AdalHttpClient.d__221.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AdalHttpClient.<GetResponseAsync>d__211.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__71.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__68.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__59.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
  at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__57.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__33.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__58.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  at CRM_WebAPI_Test1.Program.d__1.MoveNext() in
  E:\VS_2015\CRM
  Projects\CRM_WebAPI_Test1\CRM_WebAPI_Test1\Program.cs:line 31
          ErrorCode: invalid_resource
          StatusCode: 400

A: Firstly, you are using an async void function, which you should not do (except in event handlers where you can't affect the method signature).
So it should be something like:
static void Main(string[] atrgs)
{
    MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
}

Essentially in your code when it hits an await, it returns to Main and the program exits.
In C# 7.2 you can also declare the main method as async Task so you can just await the method.
You can get the tenant id from Azure portal.

*

*Open the Azure AD blade

*Go to Properties

*You can find the tenant id

The other option is to use any verified domain name (such as mydirectory.onmicrosoft.com).


text:
Q: Get uploaded file as stream using Express Right now, I'm trying to make an API, and one of its functions is to take a file and upload it to another website, sort of like uploading a file through the API as some sort of "proxy".
The website I'm sending the file to requires additional steps to work (namely sending the destination in another request) and I wanted to have my API do that all in one request instead, where that request already had all the details needed.
I've gotten the request for the destination done, but I'm having a hard time finding out how to "pipe" the upload of a user into the request that I send to the website. request-promise takes a file stream as an input when uploading files, so I wanted to hopefully pipe the upload coming from the user to the request. That way I don't have to use any disk space to temporarily save the file, especially since I'm very limited in disk space and since the server I'm sending it to virtually has no file limit.
As of now, I'm using express-fileupload to temporarily save the file, but this will eventually blow up my extremely small (194 MB) allocated space. I'm using express v4.16.4 and Node v12.0.0. For the requests, I use request-promise v4.2.4.
Here's how I declared the Express app and the express-fileupload object.
var router = express.Router({ caseSensitive: true });
app.use(router);

...

router.use(require("express-fileupload")({
    useTempFiles : true,
    tempFileDir : ".data/temp"
}));

And here's what I'm using to toss the file into the website:
if (req.body.id === undefined || req.files.file === undefined)
    return new APIError(400);
if (!Object.keys(JSON.parse(fs.read(".data/master_list_of_possible_values_for_that_variable.json"))).includes(req.body.id))
    return new APIError("400-ID");

var session_flag = await(session.executeRequest({
    method: "POST",
    uri: Constants.URL.upload.session,
    form: {
        id: req.body.id
    }
})
    .then(r => {return r;})
    .catch(e => { return e; }));

if (session_flag instanceof Error)
    throw session_flag;

var upload = await(session.executeRequest({
    method: "POST",
    uri: Constants.URL.upload.fileEndpoint,
    formData: {
        file: {
            value: fs.createReadStream(req.files.file.tempFilePath),
            options: {
                filename: req.files.file.name,
                contentType: req.files.file.mimetype
            }
        }
    }
})
    .then(r => {return r;})
    .catch(e => { return e; }));

if (upload instanceof Error)
    throw upload;

return { success: true };

A: What I suggest you do, is the following:

*

*Change your endpoint so you send id in the URL, that way you don't need to read the whole body to issue the first request

*Pipe the request directly to the third party endpoint

const request = require('request'); // streaming works better with request
const rp = require('request-promise');
const { once } = require('events');

// Make sure you don't have any body parser enable for this request
router.post('/:id', async(req, res) => {
   try {

        // issue first request
        await rp({
            method: "POST",
            uri: Constants.URL.upload.session,
            form: {
                id: req.body.id
            }
        })
        // pipe request
        const upload = req.pipe(request({
            method: "POST",
            uri: Constants.URL.upload.fileEndpoint,
            headers: req.headers // Send Same Content-Type, Length and so on
        }))

        // will throw on 'error'
        await once(upload, 'response')

        // check status code if you want
        const success = upload.response.statusCode === 200;

        return res.json({ success })

   } catch(e) {
      res.status(500)
        .send('error')
   }
});

Doing this, you don't need to store it in a temporary file since you're piping it directly to the third party endpoint.


text:
Q: Testing timer using JUnit I'm trying to test my Timer and I can't seem to be able to execute my task more than 1 time...
how can I test this class so it can run multiple times?
here's my code
package rpm.mode.offline;

import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import rpm.logging.LOG;
import rpm.patient.properties.OptionsProperties;

public class ResendController {

private static final Logger LOG = new LOG().getLogger();

private static ResendController instance = new ResendController();
private static OfflineDataLayer staticofflineDataLayer;
private int nbRetriesAllowed = 0;
private int nbActualRetries = 0;
private int retryTimeDelay = 0;
Timer timer;

public static ResendController getInstance(OfflineDataLayer offlineDataLayer) {
    staticofflineDataLayer = offlineDataLayer;
    return instance;
}

private ResendController() {
    nbRetriesAllowed = Integer.parseInt(OptionsProperties.getProperty(OptionsProperties.RESEND_NUMBER_RETRIES));
    retryTimeDelay = Integer.parseInt(OptionsProperties.getProperty(OptionsProperties.RESEND_DELAY_IN_MINUTES));
}

public void sendAnswers() {
    if (timer == null) {
        timer = new Timer();
        timer.schedule(new ResendTask(), 1);
        System.out.println("ResendTask task created...");
    }
}

/*
 * The Task that sends the answers of the patient.
 */
class ResendTask extends TimerTask {

    @Override
    public void run() {
        System.out.println("ResendTask run() is called....");
      }
}

}
and my Junit:
package rpm.mode.offline;

import org.junit.Test;

public class TestResendController {

@Test
public void testResend() throws InterruptedException {
    System.out.println("Java timer is about to start");

    OfflineDataLayer datalayer = null;
    ResendController controller = ResendController.getInstance(datalayer);
    controller.sendAnswers();
    Thread.sleep(4000);
    System.out.print("Pass 1...");
    Thread.sleep(4000);
    System.out.print("Pass 2...");
    Thread.sleep(4000);
    System.out.print("Pass 3...");
    Thread.sleep(4000);
    System.out.print("Pass 4...");
    Thread.sleep(4000);
    System.out.print("Pass 5...");
    Thread.sleep(4000);
    System.out.print("Pass 6...");

}
}

Output:
ResendTask task created...
ResendTask run() is called....
Pass 1...Pass 2...Pass 3...Pass 4...Pass 5...Pass 6...

A: Two issues: First, your test only is calling sendAnswers() once; are the alternating sleeps and prints that follow meant to have more calls to it?
Second, if timer is already set in ResendController, then sendAnswers() isn't doing anything—it looks like you should have timer.schedule() after the if block, not inside it.


text:
Q: why h4 tag is not showing after using clip path on sibling div? In this codepen here on codepen the h4 tag is not showing completely, above the psuedo element. I tried this psuedo selector but nothing seems to work. Am I doing anything wrong here ?
some help is appreciated.

A: Please check the codepen link and let me know if it helps
https://codepen.io/shakcho/pen/eaYVdm
.card--blue {
  position: relative;
  width: 70%;
  height: 100%;

  .header{
     position: absolute;
     z-index: 1;
  }

  &::after {
    display: block;
    content: "";
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: $color-3;
    -webkit-clip-path: polygon(0 0, 46% 0, 81% 100%, 0% 100%);
    clip-path: polygon(0 0, 46% 0, 81% 100%, 0% 100%);
  }
}


text:
Q: How can travails be romantic?
The best 'classic' novels are an odd mixture. On the one hand, they tend to be
written by people with strange names and are set in increasingly distant and
peculiar ages, where the clothes are never dry-cleaned and the characters fight
duels, go to balls, ride horses and take snuff. But they also pull off the miraculous
feat of speaking to us more directly, more urgently than anything written in our
own time. While seemingly engaged in her own love story in nineteenth-century
rural France, Emma Bovary will continue to shed light on the romantic travails of
people living in twenty-first-century space stations.

Isn't this an oxymoron? How do you determine/deduce which definition of romantic applies? Following user Dan Bron's comment, how would Definitions 2 and 3 fit?

2. Of, characterized by, or suggestive of an idealized view of reality:
3. Relating to or denoting the movement of romanticism:

A: It's the first definition of "romantic" that applies, though - "Conducive to or characterized by the expression of love." The clue that the "love" definition is the correct one is right there in the sentence: "While seemingly engaged in her own love story."
The second and third definitions do not apply here.