text:
Q: Android ImageView is rendering Bitmap images smaller while in ListView I have a ListView, inside a linear layout, that should show items based on a list_item.xml layout file. In the layout file I have two ImageViews and two TextViews. I'm using my custom ArrayAdapter to fill the ListView at runtime with Bitmap images of scale 125x25, however images are showing smaller than their initial size when rendered by the ImageView inside the ListView as shown in the screenshot (of a single list item) below:

ActivityLayout.xml:
...
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:paddingTop="40dp"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lvExp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
...

List_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="?android:attr/listPreferredItemHeight">

    <ImageView
        android:id="@+id/imageViewplate"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:adjustViewBounds="true"
        android:minWidth="300dp" />

    <TextView
        android:id="@+id/lblListItem_letter"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/imageViewplate"
        android:padding="3dp"
        android:text="A"
        android:textSize="17dip" />

    <TextView
        android:id="@+id/lblListItem_num"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/lblListItem_letter"
        android:padding="3dp"
        android:text="123456"
        android:textSize="17dip" />

    <ImageView
        android:id="@+id/imageViewchars"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="10dp"
        android:paddingTop="3dp"
        android:paddingBottom="3dp" />

</RelativeLayout>

My custom list adapter:
    package bi.anpr.layouts;

import android.content.Context;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sxx.vlctest.R;

import java.util.ArrayList;

import bi.anpr.agents.Plate;

public class PlateListAdapter extends ArrayAdapter<Plate>{

    public PlateListAdapter(Context context, int resource) {
        super(context, resource);
    }

    private ArrayList<Plate> dataSet;
    Context mContext;

    private static class ViewHolder {
        public ImageView imageView_plate, imageView_chars;
        public TextView textView_letter, textView_numbers;
    }

    private int lastPosition = -1;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Plate plate = getItem(position);
        ViewHolder viewHolder;
        final View result;

        if (convertView == null) {
            viewHolder = new ViewHolder();

            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.list_item, parent, false);

            viewHolder.textView_letter = (TextView) convertView.findViewById(R.id.lblListItem_letter);
            viewHolder.textView_numbers = (TextView) convertView.findViewById(R.id.lblListItem_num);
            viewHolder.imageView_plate = (ImageView) convertView.findViewById(R.id.imageViewplate);
            viewHolder.imageView_chars = (ImageView) convertView.findViewById(R.id.imageViewchars);
            result = convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result = convertView;
        }

        lastPosition = position;

        try{
            viewHolder.imageView_plate.setImageBitmap(plate.getEngPartImageIcon());
            viewHolder.imageView_chars.setImageBitmap(plate.getcharsImageIcon());
            viewHolder.textView_letter.setText(Character.toString(plate.getPlateLetter()));
            viewHolder.textView_numbers.setText(plate.getPlateNumbersAsString());
        }catch (Exception e){
            e.printStackTrace();
        }

        // Return the completed view to render on screen
        return convertView;
    }
}

Plate.java:
package bi.anpr.agents;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;

import java.io.Serializable;
import java.util.ArrayList;

import org.opencv.core.Mat;
import org.opencv.core.Rect;

import bi.anpr.core.IPHelper;

public class Plate implements Serializable {

    private String platePath;
    private boolean isWidePlate = true;
    private int[] color;
    private String colorString;
    private String source = "";
    private Rect bdgbx;
    private Mat srcImage;
    private Mat plateImage;
    private Bitmap engPartImageIcon, plateImageIcon, forCutImageIcon, charsImageIcon, charsTextImageIcon;
    private Mat engPartImage;
    private Mat forCut;
    private ArrayList<Character> plateNumberChars = new ArrayList<>();
    private char plateLetterChar = '#';
    private String fullPlateString = "";
    private String numbersPlateString = "";
    private double letterRate = 0;
    private double numbersRate = 0;
    private double accuracy = 0;
    private int id;
    private PlateRecogInfo plateRecogInfo;
    private ArrayList<Bitmap> charsIcons = new ArrayList<>();
    private boolean ignore = false;
    private int accurayPercent = 0;

    public Plate() {
        plateRecogInfo = new PlateRecogInfo();
    }

    public void addPlateNumberChar(char c) {
        plateNumberChars.add(c);
    }

    public Bitmap getplateImageIcon() {
        return plateImageIcon;
    }

    public void setPlateImageIcon(Bitmap plateImageIcon) {
        this.plateImageIcon = plateImageIcon;
    }

    public Bitmap getEngPartImageIcon() {
        if (engPartImageIcon == null) {
            engPartImageIcon = IPHelper.matToBitmap(engPartImage);
        }
        return engPartImageIcon;
    }

    public void setEngPartImageIcon(Bitmap engPartImageIcon) {
        this.engPartImageIcon = engPartImageIcon;
    }

    public Mat getEngPartImage() {
        return engPartImage;
    }

    public void setEngPartImage(Mat engPartImage) {
        this.engPartImage = engPartImage;
    }

    public boolean isWidePlate() {
        return isWidePlate;
    }

    public void setWidePlate(boolean isWidePlate) {
        this.isWidePlate = isWidePlate;
    }

    public Mat getImage() {
        return plateImage;
    }

    public void setImage(Mat Bitmap) {
        plateImage = Bitmap;
    }

    public Bitmap getForCutImageIcon() {
        if (forCutImageIcon == null) {
            forCutImageIcon = IPHelper.matToBitmap(forCut);
        }
        return forCutImageIcon;
    }

    public Mat getForCut() {
        return forCut;
    }

    public void setForCutImageIcon(Bitmap forCutImageIcon) {
        this.forCutImageIcon = forCutImageIcon;
    }

    public void setForCut(Mat forCut) {
        this.forCut = forCut;
    }

    public ArrayList<Character> getPlateNumberChar() {
        return plateNumberChars;
    }

    public void setPlateNumberChar(ArrayList<Character> nchar) {
        plateNumberChars = new ArrayList<Character>(nchar);
    }

    public char getPlateLetter() {
        return plateLetterChar;
    }

    public void setPlateLetter(char plateLetter) {
        plateLetterChar = plateLetter;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getLetterRate() {
        return letterRate;
    }

    public void setLetterRate(double letterRate) {
        this.letterRate = letterRate;
    }

    public double getCharsRate() {
        return numbersRate;
    }

    public void setNumbersRate(double NumbersRate) {
        this.numbersRate = NumbersRate;
    }

    public double getAccuracy() {
        return accuracy;
    }

    public int getAccurayPercent() {
        return accurayPercent;
    }

    public void setAccuracy(double totalRate) {
        this.accuracy = totalRate;
        this.accurayPercent = (int) (totalRate * 100);
    }

    public Mat getPlateImage() {
        return plateImage;
    }

    public void setPlateImage(Mat matImage) {
        this.plateImage = matImage;
        plateImageIcon = IPHelper.matToBitmap(matImage);
    }

    public PlateRecogInfo getPlateRecogInfo() {
        return plateRecogInfo;
    }

    public void setPlateRecogInfo(PlateRecogInfo plateRecogInfo) {
        this.plateRecogInfo = plateRecogInfo;
    }

    public void addCharIcon(Mat charsIcons) {
        this.charsIcons.add(IPHelper.matToBitmap(charsIcons));
    }

    public Bitmap getcharsImageIcon() {
        if (charsImageIcon == null) {
            int width = 5;
            int height = 0;
            for (Bitmap icon : charsIcons) {
                if (icon.getHeight() > height)
                    height = icon.getHeight();
                width += icon.getWidth() + 5;
            }
            height += 6;

            charsImageIcon = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(charsImageIcon);

            int i = 0;
            for (Bitmap icon : charsIcons) {
                canvas.drawBitmap(icon, i, 3, null);
                i += icon.getWidth() + 5;
            }
        }

        return charsImageIcon;
    }

    public Bitmap getCharsTextImageIcon() {
        if (charsTextImageIcon == null) {
            String chars = "";
            for (Character c : plateNumberChars) {
                String cs = c.toString();
                chars += cs;
            }

            int width = 5;
            int height = 0;
            for (Bitmap icon : charsIcons) {
                if (icon.getHeight() > height)
                    height = icon.getHeight();
                width += icon.getWidth() + 5;
            }
            height += 6;

            charsTextImageIcon = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(charsTextImageIcon);

            int i = 0;
            int j = 0;

            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
            paint.setColor(Color.BLACK);
            paint.setTextSize(16);

            canvas.drawColor(Color.WHITE);

            for (Bitmap icon : charsIcons) {

                if (j == 0)
                    canvas.drawText("Some Text", i + 2, 19, paint);
                else
                    canvas.drawText(Character.toString(chars.charAt(j - 1)), i + 3, 19, paint);

                i += icon.getWidth() + 5;
                j++;
            }

        }

        return charsTextImageIcon;
    }

    public void setCharsTextImageIcon(Bitmap charsTextImageIcon) {
        this.charsTextImageIcon = charsTextImageIcon;
    }

    public Mat getSrcImage() {
        return srcImage;
    }

    public void setSrcImage(Mat srcImage) {
        this.srcImage = srcImage;
    }

    public Rect getBdgbx() {
        return bdgbx;
    }

    public void setBdgbx(Rect bdgbx) {
        this.bdgbx = bdgbx;
    }

    public int[] getColor() {
        return color;
    }

//    public Color getColorObject() {
//        int[] color = getColor();
//
//        try {
//            return Color.parseColor(Color.rgb(color[0], color[1], color[2]));
//        } catch (Exception e) {
//        }
//        return null;
//    }

    public void setColor(int[] is) {
        this.color = is;
    }

    public String getColorString() {
        return colorString;
    }

    public void setColorString(String colorString) {
        this.colorString = colorString;
    }

    public String getFullPlateCharsString() {
        if (fullPlateString == "" || fullPlateString == null) {
            fullPlateString += plateLetterChar;
            for (Character c : plateNumberChars) {
                fullPlateString += c.toString();
            }
        }

        return fullPlateString;
    }

    public void setFullPlateString(String fullPlateString) {
        this.fullPlateString = fullPlateString;
    }

    public void setNumbersPlateString(String numbersPslateString) {
        this.numbersPlateString = numbersPslateString;
    }

    public String getPlateNumbersAsString() {
        if (numbersPlateString == "" || numbersPlateString == null) {
            for (Character c : plateNumberChars) {
                numbersPlateString += c.toString();
            }
        }

        return numbersPlateString;
    }

    public String getPlatePath() {
        return platePath;
    }

    public void setPlatePath(String platePath) {
        this.platePath = platePath;
    }

    public boolean isIgnore() {
        return ignore;
    }

    public void setIgnore(boolean ignore) {
        this.ignore = ignore;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

}

Usage:
PlateListAdapter plateListAdapter = new PlateListAdapter(getApplicationContext(), R.layout.list_item);
ListView resultsListView = (ListView) findViewById(R.id.lvExp);
resultsListView.setAdapter(plateListAdapter);
plateListAdapter.addAll(recogInfo.getPlates());
plateListAdapter.notifyDataSetChanged();

A: Using definite dimensions for ImageView's, rather than wrap_content solved the problem.


text:
Q: Remove matplotlib depreciation warning from showing I'm getting simply a MatplotlibDepreciationWarning which I don't like to see on my console. And therefore I don't want to see it.
Here's the warning:
/home/.../pyvirt/networkx/lib/python3.6/site-packages/networkx/drawing/nx_pylab.py:579:
MatplotlibDeprecationWarning:The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.
        if not cb.iterable(width):`

So if anyone can suggest any way to remove this depreciation warning from showing, it would be appreciated.
I've tried:
import warnings
warnings.filterwarnings("ignore", category=DepriciationWarning)`

Code for program is as follow which doesn't contain any error.
import networkx as nx
import matplotlib.pyplot as plt
import random

G=nx.Graph()
city_set=['Delhi','Bangalore','Hyderabad','Ahmedabad','Chennai','Kolkata','Surat','Pune','Jaipur']
for each in city_set:
    G.add_node(each)

costs=[]
value=100
while(value<=2000):
    costs.append(value)
    value=value+100

while(G.number_of_edges()<16):
    c1=random.choice(list(G.nodes()))
    c2=random.choice(list(G.nodes()))
    if c1!=c2 and G.has_edge(c1,c2)==0:
        w=random.choice(costs)
        G.add_edge(c1,c2,weight=w)

for u in G.nodes():
    for v in G.nodes():
        print(u,v,nx.has_path(G,u,v))

pos=nx.circular_layout(G)
nx.draw(G,pos,with_labels=1)
plt.show()

A: Instead of category=DepreciationWarning, category was supposed to be UserWarning for matplotlib. Therefore solution is add the following lines before starting of code-
import warnings
 warnings.filterwarnings("ignore", category=UserWarning)

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Swiftlet mysqli error The Error:

Fatal error: Swiftlet\App::autoload(): Failed opening required 'Swiftlet/Models/mysqli.php' (include_path='.:/usr/local/lib/php-5.3.13/lib/php') in /hermes/waloraweb009/b1166/htdocs/jim/ss test/Swiftlet/App.php on line 223

I'm new to MVC and trying out Swiftlet. I'm trying to setup a MYSQL database Model.
I've nailed down the error to:
class Database extends \Swiftlet\Model {
    public $mysqli;

    public function __construct(App $app) {
        $this->mysqli = new mysqli($this->app->getConfig('dbHost'),
                                   $this->app->getConfig('dbUser'),
                                   $this->app->getConfig('dbPassword'),
                                   $this->app->getConfig('dbName'));
    }
}

But I don't know why. Why would it try to load mysqli?

A: It seems the problem is that you are likely in \Swiftlet namespace.  When trying to instantiate mysqli (an item in global namespace) from within this name space, it is trying to autoload where it would normally look to autoload classes within it's namespace. The class isn't there, thus you get the autoload error.
Try changing your mysqli instantiation like this:
$this->mysqli = new \mysqli($this->app->getConfig('dbHost'), $this->app->getConfig('dbUser'), $this->app->getConfig('dbPassword'), $this->app->getConfig('dbName'));

Note that myslqi is now prefixed by \ thus referencing the mysql class in the global namespace.


text:
Q: How to set an icon for the toolbar using Tkinter I tried to change the default icons of tkinter (I am actually using customTkinter, but it is suposed to work the same way) and I did change the app icon itself but the icon showing in the toolbar is not what it should be.
here what i've got
here what it shows
I tried using all kind of iconbitmap, wm_icon, etc...


text:
Q: how to pass @model.ApplicationId from html form to js I am trying to make an auto save function that will save the form data. I am unable to pass my ApplicationId in from form to JS in order to auto save. Though with the fixed id, auto saving does work. I have the following code:
Js Code:
window.setInterval(AutoSaveDraft(id), 50000);

function AutoSaveDraft(id) {
   $.post({
         url: "/Application/Edit/"+id ,
         data: $("#application-form").serialize()
         }).done(function(data, textStatus, jqXhr) {
      if (jqXhr.status === 200) {
          alert("Data Application has been saved");
          return true;
       }
    });
}

Html CODE:
<form asp-action="Edit" id="application-form" name="@Model.ApplicationId" >
...
</form>

Basically, I want the @Model.ApplicationId to be passed to my Js, so that I can use that in my Autosaving function.

A: First off, your interval is wrong. What you are doing is calling a function and passing the result to the interval. You need to pass it a function that it can then call when needed. You are calling your function right away.
Next, all you need to do, is to use jQueries attr() method like so:

let id = 'application-form'
window.setInterval(() => AutoSaveDraft(id), 5000);

function AutoSaveDraft(id) {
  let name = $(`#${id}`).attr('name')
  console.log(name)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form asp-action="Edit" id="application-form" name="@Model.ApplicationId">

</form>

A: Let's say you have your JS on the same page as your html, you could simply write:
window.setInterval(function () {
   var id = '@Model.ApplicationId'; // Turned C# to JS here
   AutoSaveDraft(id);
}, 50000);

function AutoSaveDraft(id) {
   $.post({
      url: "/Application/Edit/"+id ,
      data: $("#application-form").serialize()
   }).done(function(data, textStatus, jqXhr) {
      if (jqXhr.status === 200) {
          alert("Data Application has been saved");
          return true;
       }
   });
}

Now let's say your JS is somewhere else:
HTML:
<form asp-action="Edit" id="application-form" name="@Model.ApplicationId" >
...
</form>

JS:
window.setInterval(function () {
   var id = $("#application-form").attr('name'); // Retrieve the ID
   AutoSaveDraft(id);
}, 50000);

function AutoSaveDraft(id) {
   $.post({
      url: "/Application/Edit/"+id ,
      data: $("#application-form").serialize()
   }).done(function(data, textStatus, jqXhr) {
      if (jqXhr.status === 200) {
          alert("Data Application has been saved");
          return true;
       }
   });
}

That's said, I would suggest you to use data- attribute to pass that kind of data. Let's try with data-application-id.
<form asp-action="Edit" id="application-form" data-application-id="@Model.ApplicationId">
...
</form>

window.setInterval(function () {
   var id = $("#application-form").data("application-id"); // Retrieve here
   AutoSaveDraft(id);
}, 50000);


text:
Q: Fundamental Polygon of Real Projective Plane Wikipedia gives the following fundamental polygon for the real projective plane $\mathbb{R}\mathrm{P}^2$

The problem here is that the corners aren't identified to a single point (like in the fundamental polygon of the torus). I don't think this picture is correct. The group presentation resulting from this polygon was considered in a previous question, and the same conclusion was reached.
What puzzles me more is that Hatcher's Algebraic Topology lists the same polygon as the fundamental polygon for the real projective plane (chapter 2, page 102), but the correct version (with only two edges identified together) is listed in an earlier page (chapter 1, page 51).
My question: Can this fundamental polygon made to actually represent the real projective plane in the sense that all corners are identified to a point and the resulting group presentation is $\mathbb{Z}_2$?
Thank you.

A: If you're ok with the fundamental polygon being a polygon on a surface which isn't $\mathbb{R}^2$, then you can get a polygon with two edges on the sphere $S^2$.
The polygon is given by taking the northern hemisphere, and the edges are given by each a half of the equator, with the identification being the antipodal map on the circle defining the equator.

If you know how covering spaces work, this region is a fundamental region of the $2$-fold covering of the sphere on to the real projective plane.


text:
Q: Proving a random walk with a drift is recurrent Given the following set of independent random variables $\mathbb{P}(X_n=1)=\frac{1+n^{-\beta}}{2}, \mathbb{P}(X_n=-1)=\frac{1-n^{-\beta}}{2}$ and the sum $S_n=\sum^n_{i=1}X_n$ I managed to prove that if $\beta<0.5$ then $S_n$ is transient by using Hoeffding's bound and that if $\beta > 1$ $S_n$ is recurrent by treating the random variables as a simple random walk with a drift - which I proved is finite almost surely.
I am now trying to prove the case of $0.5\leq\beta\leq1$. I am pretty sure intuitively that it is recurrent however I am not successful in proving the case.
Any help will be appreciated.

A: One way to prove this is to use the Lindeberg central limit theorem.  Let $m_1=2$, $m_2$, $m_3$, $\dots$ be a sequence of positive integers with $m_{i+1}\ge m_i^2$ for all $i$, and let $T_i:=X_{m_i+1}+\cdots+X_{m_{i+1}}$.  To apply the Lindeberg CLT to $T_i$, the first step is to compute the mean
\begin{eqnarray*}\mu_i&:=&{\Bbb E}X_{m_i+1}+\cdots+{\Bbb E}X_{m_{i+1}}\\
&=&(m_i+1)^{-\beta}+\cdots+m_{i+1}^{-\beta}\\
&\le&\int_{m_i}^{m_{i+1}} x^{-\beta} \, d\beta\\
&=&\frac{1}{1-\beta}(m_{i+1}^{1-\beta}-m_i^{1-\beta})&\qquad&\hbox{(if $\beta<1$; $\log(m_{i+1}/m_i)$ if $\beta=1$)}\\
&=&O(m_{i+1}^{1-\beta})&\qquad&\hbox{(if $\beta<1$; $O(\log m_{i+1})$ if $\beta=1$)}\\
&=&O(m_{i+1}^{1/2})
\end{eqnarray*}
and the variance
$$\sigma_i^2:={\Bbb E}[(X_{m_i+1}-(m_i+1)^{-\beta})^2]
+\cdots+{\Bbb E}[(X_{m_{i+1}}-m_{i+1}^{-\beta})^2].$$
Since $m_i\ge 2$ and $\beta\ge \frac 1 2 $, each term $(X_j-j^{-\beta})^2$ in this sum is always between $(1-3^{-1/2})^2$ and $(1+3^{-1/2})^2$.  Therefore, $\sigma_i^2=\Theta(m_{i+1}-m_i)$, and since $m_{i+1}\ge m_i^2\ge 2 m_i$, we also have $\sigma_i^2=\Theta(m_{i+1})$ and so  $\sigma_i=\Theta(m_{i+1}^{1/2})$.
Now, the Lindeberg condition is that, for all fixed $\epsilon>0$,
$$
\frac{1}{\sigma_i^2}\sum_{m_i+1\le j\le m_{i+1}} \mathbb{E} \left[(X_j - j^{-\beta})^2 \cdot \mathbf{1}(| X_j - j^{-\beta} | \ge \epsilon \sigma_i ) \right]\qquad\qquad(*)
$$
approaches zero as $i$ becomes large, but
since $|X_j-j^{-\beta}|$ is bounded and $\sigma_i\to\infty$, for $i$ large enough, (*) will be zero.  This means that we can apply the Lindeberg CLT to find that
$(T_i-\mu_i)/\sigma_i$ converges in distribution to a standard normal distribution.
Now, $$S_{m_{i+1}}=S_{m_i}+T_i \le T_i + m_i \le T_i + m_{i+1}^{1/2}$$ so
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge {\Bbb P}((T_i-\mu_i)/\sigma_i\le (-m_{i+1}^{1/2}-\mu_i)/\sigma_i)$$
and, by our estimates on $\mu_i$ and $\sigma_i$, there are constants $K>0$ and $L>0$ so that, for all sufficiently large $i$,
$$
m_{i+1}^{1/2}+\mu_i\le K m_{i+1}^{1/2}, \qquad \qquad
\sigma_i\ge L m_{i+1}^{1/2},
$$
so for sufficiently large $i$,
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge {\Bbb P}((T_i-\mu_i)/\sigma_i\le -K/L)\qquad(**)$$
and, by convergence in distribution, the right-hand side of (**) approaches $\Phi(-K/L)$ as $i\to\infty$, so for sufficiently large $i$,
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge\frac{\Phi(-K/L)}{2}.$$
This proves that $S_n$ is almost surely nonpositive infinitely often.  Similarly, $S_n$ is almost surely nonnegative infinitely often, so $S_n$ is recurrent.


text:
Q: VuePress build deletes CNAME file in ./docs needed for Github Pages custom domain I'm trying to get VuePress to work well with GitHub Pages and a custom domain. I have the site working -- https://www.southertonrr.com (repo) -- as long as I manually add a CNAME file to my output folder ('./dest', or in my case, './docs', because that's where GitHub Pages looks for the site) every time after I issue a build command. Otherwise, I assume the build command deletes everything in my output folder and rebuilds the entire site.
Is there a way to get vuepress build to either leave that file alone, or copy a CNAME file from my ./src to my ./docs? Should I be looking at the configureWebpack config to use webpack to do it? (I'm new to webpack.)
Different product completely, but I noticed that Docusaurus for React has a CNAME config setting that does this for you, so I thought I'd check to see if the VuePress community had something similar.

A: See relative document

Sometimes you may need to provide static assets that are not directly referenced in any of your Markdown or theme components - for example, favicons and PWA icons. In such cases, you can put them inside .vuepress/public and they will be copied to the root of the generated directory.


text:
Q: Images appearing as portrait Carrierwave I was following these tutorials for the Carrierwave gem: StackOverflow and Google Groups. I upload images, and they're automatically rotated to portrait form. Now, I tried the solution in the tutorials, and it didn't work for me. I was wondering if anyone had ideas on how to fix it.
Here's image_uploader.rb:
process :auto_orient
process :resize_to_fit => [720, 720]

def auto_orient
  manipulate! do |img|
    img = img.auto_orient
  end
end

And "manipulate!" is being flagged by Rails, saying "undefined method 'manipulate!' for #". Does anyone know how to fix this? Thanks so much.

A: Did you include this line:
include CarrierWave::RMagick

Or check out this:
http://www.rubydoc.info/github/jnicklas/carrierwave/CarrierWave/RMagick


text:
Q: Error initializing SIMPLEQ_HEAD in C I am trying to initialize a SIMPLEQ_HEAD in C and I and getting the following error:
# gcc -o semaphore semaphore.c
semaphore.c: In function `createSemaphore':
semaphore.c:10: syntax error before `{'

My semaphore.c class looks like:
#include <stdio.h>
#include "semaphore.h"

semaphore_t* createSemaphore( int initialCount )
{
    semaphore_t* sem;
    sem = (semaphore_t *) malloc( sizeof( semaphore_t ) );
    sem->head = SIMPLEQ_HEAD_INITIALIZER( sem->head );
    sem->count = initialCount;      // set the semaphores initial count
    return sem;
}
...
int main()
{

    semaphore_t* my_semaphore = createSemaphore( 5 );
    return 0;
}

And my semaphore.h looks like:
#ifndef SEMAPHORE_H
#define SEMAPHORE_H

#include <sys/queue.h>
#include <pthread.h>
#include <stdlib.h>

struct entry_thread {
    int threadid;
    SIMPLEQ_ENTRY(entry_thread) next;
} *np;

struct semaphore {
    int count;
    pthread_mutex_t mutex;
    pthread_cond_t flag;
    SIMPLEQ_HEAD(queuehead, entry_thread) head;
};

typedef struct semaphore semaphore_t;

semaphore_t* createSemaphore( int initialCount );
void destroySemaphore( semaphore_t* sem );
void down( semaphore_t* sem );
void up( semaphore_t* sem );

#endif

I'm new to C and using SIMPLEQ so if anybody is experienced in this I would greatly appreciate some help.
For your reference, SIMPLEQ_HEAD's man page is: http://www.manualpages.de/OpenBSD/OpenBSD-5.0/man3/SIMPLEQ_HEAD.3.html

A: After some testing, I realized
sem->head = SIMPLEQ_HEAD_INITIALIZER( sem->head );

is a static operation, so it wouldn't work as I'm dynamically creating semaphores/SIMPLEQs.
What I changed that line to instead is
SIMPLEQ_INIT( &(sem->head) ); // note that you don't set anything equal to the result

which dynamically takes care of the initialization, and solved my problem.


text:
Q: Entity Framework Throw Exception for Insert Duplicate error I am using Entity Framework and Telerik RadGrid. I have a table with  a constraint which throws an exception if a product with a duplicate name is tried as an insert. I am trying to catch the exception in my business layer and it seems to run through the catch block fine but I get an error from the Telerik RadScriptManager
"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Exception has been thrown by the target of an invocation."
instead of the Jquery popup that I am expecting with the message "Duplicate Product" Does anyone know what I am doing wrong? does the exception need to behandled in my DAL? but I dont think i should throw BusinessRuleExceptions from somewhere besides the BLL. I have posted the Insert function in my BL class below, if anyone has an idea what might be causing the Jscript error, please let me know, thanks!!
Edit
The Object Data Source TypeName is tied to the Business layer ProductBL
Product BL function Insert_Product is being called from my ObjectDataSource as the Insert function. In the Product.cs code behind class I have a function for Inserting Products where I am passing the product Name (see below), this function has a try catch bloeck..should I be throwing the exception here? I thought it would be right to throw the BusinessRulException in the Business Layer.
Product.CS class (Object Data Source Insert command)
 protected void ODSProducts_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        try
        {

            TextBox txtProductName = (TextBox)ProductsGrid.MasterTableView.GetInsertItem().FindControl("txtProductName");

            ((ACME.DAL.Product)e.InputParameters[0]).Product.product_name = txtProductName.Text;

        }
        catch (Exception ex)
        {
            HTMLError.HtmlError.LogHtmlError(ex, Application["ErrorLog"].ToString());
            throw;
        }
    }

ProductsBL.CS
   public void Insert_Product(Product product)
      {
        try
        {
            repository.Insert_Product(product);
        }
        catch (Exception ex)
        {
            if (ex.GetType().Name == "UpdateException")
            {

               throw new BusinessRuleException("Duplicate Product");
            }

        }
    }

Product.DAL
 public void InsertProduct(Product product)
    {

        context.Products.AddObject(product);

        context.SaveChanges();
    }

A: You will want to tap into the RadGrid_ItemInserted event.  There the event arg should have a reference to the exception thrown, and you can mark that you handled the exception so it doesn't bubble up to the user.
That's if you are letting the ODS do the full insert, and not inserting manually.

A: ok I figured this out after wasting too many hours on this. It seems like Telerik doesnt like me throwing the Business rule exception from the Business Layer class. So I ended up handling the exception instead in the codebehind in the object data source_Inserted event. This is what I did to display the error in a RadAlertWindow from the event.
enter code here
protected void ODSProducts_Updated(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.Exception != null)
        {
            if (((e.Exception.InnerException).InnerException).Message.Contains("Cannot insert duplicate key row"))
            {
                RadWindowManager.RadAlert("Duplicate Product, Enter a new Product", 330, 100, "Insert Error", "");
                e.ExceptionHandled = true;
            }
        }
    }

I dont like checking the .InnerException.Message.Contains bit but thats the only way I knew how to make sure if the exception was SQL throwing duplicate error on the unique constraint on the field. If someone knows of a more elegant way to do this please share. Hope this helps someone else as well.


text:
Q: android button widget with a dropdown list, what is the name of this particular widget? Im learning android layouts and Ive noticed a particular button widget in some android apps that I would like to add to my own apps, Im just not entirely sure what its called, In some cases this button widget even will include a dropdown list here are a few examples of what Im talking about.
in the first image you will notice that the checkmark, the camera and the pencil are all sitting inside of the button widget i'm after, and in the youtube app you will notice the thumbs up, thumbs down and more buttons

A: That's ActionBar. Native support for 3.0+ devices, and some work to do in pre 3.0-devices. You can find example in new api  14 samples(called "ActionBarCompat").

A: Please see my answer here which gives some good links on how to implement the "dashboard" pattern, and use the "quickaction" bar. I think this should put you on the right path. Also there is a link on how to implement the "action bar."
EDIT: According to Mighter, if you use API 1.6 - 2.3 there should be official Google samples for this now. Please see this.


text:
Q: script to run windows update on hyper-V images I have over 10 hyper-v images that I use for testing various projects. Some I use often some less so.
It is a lot of work starting each of the machines individually to run windows update.
I was wondering  if there is a powershell script that could spin up each of the machines, run windows update on it and then close it down again?

A: If your VMs only include recent (Vista or later) Windows system, you don't need to actually start them to apply updates; you can do it directly to the offline .VHD files, by mounting them and using the dism.exe offline servicing tool; dism.exe has several features, one of which is the ability to apply patches to an offline Windows image or VHD file.
This very nice script should be able to automatically mount a VHD file, apply some updates to it and unmount it; I've not personally tested it, but looks like it should work:
http://gallery.technet.microsoft.com/scriptcenter/839ee6f0-196f-4ed7-ac55-8e753c5d5ebe

A: Not that I am aware of. This functionality is built into SCVMM, a non-free produce MS sells.
You might be able to do some sort of homebrew script (if I remember tomorrow I've got scripts for doing some other maintenance similar to this and will post them).


text:
Q: Writing a custom mode for CodeMirror, for use in Brackets I am trying to write a plugin/extension for Brackets that will handle PowerShell.  Well after looking into it, I found that CodeMirror also doesn't have a PowerShell mode, so I need to create it myself.  I am having a terrible time because there are hardly any detailed resources online for what I am trying to do.

This is my main.js file:
    define(function (require, exports, module){
        "use strict";

        //Load Modules
        var LanguageManager = brackets.getModule("language/LanguageManager"),
            CodeMirror = brackets.getModule("thirdparty/CodeMirror2/lib/codemirror"),
            PowerShellMode = require("powershell.js");

        //Define the Language
        LanguageManager.defineLanguage("powershell", {
        name: "PowerShell",
        mode: "powershell",
        fileExtensions: ["ps1"],
        lineComment: ["\/\/"]
        });

        function log(s) {
            console.log("[PS-DevKit] " +s);
        }

        log("PowerShell module loaded!");

    });

This is my powershell.js file:
//CodeMirror Example
CodeMirror.defineMode("powershell", function() {

    return{
        startStat: function() {return {inString: false};},
        token: function(stream, state){
            //If a string starts here
            if (!state.inString && stream.peek() == '"'){
                stream.next();              //Skip quote
                state.inString = true;      //Update state
            }

            if (state.inString) {

                if (stream.skipTo('"')){    //Quote found on this line
                    stream.next();          //Skip quote
                    state.inString=false;   //Clear flag
                } else {
                    stream.skipToEnd();     //Rest of line is string
                }

                return "red-text";            //Token style

            } else {

                stream.skipTo('"') || stream.skipToEnd();
                return null;                //Unstyled token

            }
        }
    };
});

When running Brackets with this code as is, I get an error (developer console) that it could not load my powershell.js file from "Program Files(x86)\Brackets\www".  So I tried putting in the exact path to where the file is (the Bracket extensions folder sitting in my User directory), and it worked but I get the following message:
Use brackets.getModule("thirdparty/CodeMirror2/lib/codemirror") instead of global CodeMirror.
    at Object.defineProperty.get (/brackets.js:115:32)
    at file:///C:/Users/MY_USERNAME/AppData/Roaming/Brackets/extensions/user/PS-DevKit/powershell.js:2:1

Any input?  Right now, all I am trying to do is get it to load and change any text in quotes to red.  Even though I get the deprecation warning about needing to use the CodeMirror module, the extension does load, and if I create a ".ps1" file, it recognizes that it is PowerShell.

A: General answer - there actually are some fairly detailed resources for this:

*

*Writing a CodeMirror mode

*Defining a new language in Brackets - see the subsection "Custom CodeMirror modes" for how to load your new CodeMirror mode

Specific answer - I can spot a few issues in your sample code that will definitely cause problems:

*

*Use require("powershell") without the .js -- this is the format JS module loaders expect

*powershell.js should contain the same define(...) wrapper as your main.js. And it should use brackets.getModule() to get a reference to CodeMirror, same as main.js. (Using JSLint, which is built into Brackets, is helpful for warning you when you reference globals that you have forgotten to explicitly load as module dependencies).

*Your CM mode has a typo: startStat -> startState

*You need to call CodeMirror.defineMode() before calling LanguageManager.defineLanguage() - see "Custom CodeMirror modes" docs linked above. You could either do this in your powershell.js module, or early in main.js.


text:
Q: Regex used cannot retrieve correct values on pages with similar structures within the same site When the value of url = https://www.sportsgambler.com/injuries/football/argentina-superliga/
And the value of team = Argentinos Jrs
The result perfectly filters only the athletes of that team.
However, when the url = https://www.sportsgambler.com/injuries/football/usa-mls/
And when the team = Philadelphia
The result pulls all athletes that exist on the page.
I would like some help in finding a way to work this string so that it works on all pages of this site, because their pattern is the same, changing only the names of teams from different tournaments.
function PaginaDoJogo() {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Lesionados e Suspensos');
  const url = sheet.getRange('Menu L&S!H1').getValue();
  const team = sheet.getRange('Menu L&S!H2').getValue();
  const response = UrlFetchApp.fetch(url);
  const content = response.getContentText();
  const re = new RegExp(team + "[\\s\\S]+?");
  const match = content.match(re);
   const regExp = /<div[\s\S]+?(.+?)<\/span>[\s\S]+?(.+?)<\/span>[\s\S]+?(.+?)<\/span>[\s\S]+?<\/div>/g;
  const values = [];
  while ((r = regExp.exec(match[0])) !== null) {
    // console.log(r[1], r[2], r[3]);
    if (r[1] !== 'Name' && r[2] !== 'Away on International duty') {
      values.push([r[1], r[3]]);
    }
  }
  sheet.getRange(2, 1, values.length, 2).setValues(values);
}

A: There were 2 main issues I saw in the site and the script.

*

*Your re caught the "Philadelphia Union vs CF Montreal" instead.

*Not all injury-block have  at the end.

I did manage to make it work by having it catch the team name when it is only after an a tag and instead of using , I used the a tag after the divs.
Modification:
const re = new RegExp("]+>" + team + "[\\s\\S]+?]+>");

In short, team should be in between 2 a tags.

Tests:


text:
Q: Fetching a bean in Spring using getBean This question might sound lame but I had a doubt so I wanted to clear it out. I am reading Getting Started with Spring Framework by Ashish Sarin and there is this simple code which fetches a spring bean of type FixedDepositService class
package sample.spring.chapter06.bankapp;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import sample.spring.chapter06.bankapp.domain.FixedDepositDetails;
import sample.spring.chapter06.bankapp.service.FixedDepositService;

public class BankApp {
    public static void main(String args[]) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:META-INF/spring/applicationContext.xml");

        FixedDepositService fixedDepositService = context
                .getBean(FixedDepositService.class);
        fixedDepositService.createFixedDeposit(new FixedDepositDetails(1, 0,
                12, "someemail@somedomain.com"));
        fixedDepositService.createFixedDeposit(new FixedDepositDetails(1, 1000,
                12, "someemail@somedomain.com"));
    }
}

Now FixedDepositService is an interface and not a concrete class. It is implemented by another class called FixedDepositServiceImpl like this
....
@Service(value = "fixedDepositService")
public class FixedDepositServiceImpl implements FixedDepositService {
....
}

My question is, how does this code work? Shouldn't the BankApp class fetch a bean of FixedDepositServiceImpl class instead of FixedDepositService class since FixedDepositService is just an interface and contains no method definitions and FixedDepositServiceImpl is the class that actually implements it and has all the logic defined in it?

A: In straight you can use getClass().getName() to see which class object is it
FixedDepositService service = (FixedDepositService) context.getBean("fixedDepositService");

System.out.println(service.getClass().getName());  //FixedDepositServiceImpl

A: In spring this is the concept behind decoupling your actual implementation/behaviour from the client and use it as a strategy depends on your requirement.
As you mentioned above

Shouldn't the BankApp class fetch a bean of FixedDepositServiceImpl class instead of FixedDepositService class since FixedDepositService is just an interface

This is the issue when you need to have multiple strategies defined from your requirement but in most cases this is used without any actual requirement behind.
If you do not need to decouple your implementation as you implement above it is totally fine to make your FixedDepositService a concrete class and use (using @Component).
But if you have multiple implementations based on your requirement you can use a @Qualifier to mention what implementation you are going to use based on a strategy.
List<? extends FixedDepositService> fixedDepositServices; //use based on a strategy

Or
//inject single implementation if you know what you want
@Qualifier("diffrentFixedDepositService") FixedDepositService diffrentFixedDepositService;

And also it is not needed to name your service class like @Service(value = "fixedDepositService") because your not really using a (different name or you only have one implementation) for your service class.


text:
Q: Change the position of index bar in UITableView in iOS7 In iOS 7 the index bar of a tableview is closer to the edge than before. If i try to loop through all subviews of the tableview and change the position and all subviews the index bar still is in the same position. If I change the position of the tableview the index bar moves.
So my question: How do you change the position of the index bar in iOS 7 when it doesn´t seem to be a subview of it´s own?


text:
Q: Swift MacOS, how copy original file URL after casting to NSFilePromiseReceiver? I implemented a very basic drag n' drop following the official documentation:
https://developer.apple.com/documentation/appkit/documents_data_and_pasteboard/supporting_drag_and_drop_through_file_promises
However, I need more than just receiving a file, I would like to save not only the file but the original URL as well, the problem is, when I cast the received object further castings are not possible:
    open override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {

        guard let pasterboardObjects = sender.draggingPasteboard.readObjects(forClasses: [NSFilePromiseReceiver.self, NSString.self], options: nil), pasterboardObjects.count > 0 else { return false }

        pasterboardObjects.forEach {

            if let filePromiseReceiver = $0 as? NSFilePromiseReceiver {

//                print("file promise receiver", filePromiseReceiver, filePromiseReceiver.)
                filePromiseReceiver.receivePromisedFiles(atDestination: destinationURL, options: [:], operationQueue: workQueue) { _, error in
                    if let error = error {
                        print("error saving image")
                    } else {
                        print("Image saved to", destinationURL)
                    }
                }
            }

            print("After receiving file", $0)

            if let png = $0 as? NSImage {
                print("image dropped")
            }

            if let url = $0 as? URL {
                print("URL dropped")
            }

            if let string = $0 as? String {
                print("String dropped")
                internalStore?.appendString(string: string)
            }
        }
        return true
    }

How would I go about copying the $0 parameter for it to be catched down the if hierarchy?

A: There does not seem to be a way to do this, since the data is casted before reaching the forEach loop, I did notice though that the saved image contains extra metadata and that includes the location of the original file, so that kinda solves my problem.


text:
Q: If file exists with that name, what would RenameFile do? Will it delete the old file? I have this line of code in c#:
ftp.RenameFile(file_name, "folder_name/" + file_name);

where ftp is an instance of the FtpConnection class.
I'm interested to know what would happen if folder_name already has a file named file_name.
Would it delete the old file and replace it with the new one?

A: Since  the documentation (assuming I've got the right product (a)) doesn't seem to state one way or the other, the best thing you can do is try it out.
It should be immediately obvious what happens, though you probably want to try some different combinations to check effects of permissions and so forth.

(a) If I don't have the right product, the method still stands: either consult the documentation, or try it yourself.

A: It doesn't do anything. It doesn't delete the old file.


text:
Q: Qt thread ID is equal to MainWindows? (moveToThread) Now I want to create a thread and put in my class "AVC_file" inatance.
But when I print currentThreadId in textBroswer, I found MainWindows's threadID is same with the thread I created. show pitures like below.
Framework::Framework(QWidget * parent) : QMainWindow(parent)
{
  ui.setupUi(this);

  int threadID = (int)QThread::currentThreadId();
  ui.textBrowser->append("Main Tread ID : " + QString::number(threadID));
}

void Framework::on_OpenAVCFile_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(
        this, tr("Open File"), "C:\\", "AVC File (*.avc)"
    );

    if (!filePath.isEmpty())
    {
        QMessageBox::information(this, tr("File Name"), filePath);
    }

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::information(0, "info", file.errorString());
    }
    else {
        QThread *thread = new QThread(this);
        int threadID = (int)thread->currentThreadId();
        ui.textBrowser->append("Second Tread ID : " + QString::number(threadID) + "\n");
        AVC_File *AVC_file = new AVC_File();

        AVC_file->moveToThread(thread);
        connect(AVC_file, SIGNAL(requestFileContent(QString)), this, SLOT(addFileContent(QString)));
        connect(AVC_file, SIGNAL(requestFileDebug(QString)), this, SLOT(addFileDebug(QString)));
        connect(AVC_file, SIGNAL(requestFileCorrectness(bool, int)), this, SLOT(adddFileCorrectness(bool, int)));
        connect(AVC_file, SIGNAL(requestNewValue(unsigned int, int)), this, SLOT(addNewValue(unsigned int, int)));
        thread->start();

        AVC_file->AVC_FileCheck(file);
    }
}

Images about my code and results-->
Main Windows, create thread and results
Oh!I also try emit info in my "AVC_file" instance?like below.
void AVC_File::AVC_FileCheck(QFile &file)
{
    int threadID = (int)QThread::currentThreadId();
    emit requestFileContent("Thread ID by emit" + QString::number(threadID) + "\n");
    QTextStream in(&file);
    ........
    ........
}

Emit threadID info
Anyone can help me?
BTW, I use visual studio Qt add-in to develop this project.

A: QThread::currentThreadId() is a static method.
When you call it, it returns the thread ID of the thread that executes it.
In both your cases that's the main thread.

A: There are several issues that I'll address in random order.
First of all, using thread IDs is bad user experience. Give the threads a descriptive name:
int main(...) {
  QApplication app(...);
  QThread myThread;
  MyObject myObject;
  myObject->moveToThread(&myThread);
  QThread::currentThread()->setObjectName("mainThread");
  myThread.setObjectName("myThread");
  ...
}

Then use QThread::currentThread()->objectName() to retrieve it. You can also pass QObject* to qDebug() to display the name of the thread:
qDebug() << QThread::currentThread();

Your signal invocation would then become:
QString currentThreadName() {
  return QThread::currentThread()->objectName().isEmpty() ?
    QStringLiteral("0x%1").arg(QThread::currentThread(), 0, 16) :
    QThread::currentThread()->objectName();
}

   ...
   emit requestFileContent(
     QStringLiteral("Emitting from thread \"%1\"\n").arg(currentThreadName));

Then, use the above to deal with the thread you've created:
    auto thread = new QThread(this);
    thread->setObjectName("fileThread");
    ui.textBrowser->append(QStringLiteral("Worker thread: \"%1\").arg(thread->objectName()));
    auto AVC_file = new AVC_File;

    AVC_file->moveToThread(thread);
    ...

But AVC_FileCheck is invoked from the main thread. Whether that's OK or not depends on how that method is implemented. It needs to be thread-safe, see this question for a discussion of that. TL;DR: The following pattern could be a starting point:
class AVC_file : public QObject {
  Q_OBJECT
  Q_SLOT void fileCheck_impl(QIODevice * dev) {
    dev->setParent(this);
    ...
  }
  Q_SIGNAL void fileCheck_signal(QIODevice *);
public:
  void fileCheck(QIODevice *dev) { fileCheck_signal(dev); }
  AVC_file(QObject *parent = nullptr) : QObject(parent) {
    connect(this, &AVC_file::fileCheck_signal, this, &AVC_file::fileCheck_impl);
    ...
  }
};

Finally, your existing AVC_fileCheck API is broken. You pass QFile by reference: this won't ever work since it ceases to exist as soon as on_OpenAVCFile_clicked returns. When AVC_file uses that file in its thread, it's a dangling object reference.
Instead, you must pass the ownership of the file to AVC_file, and pass a pointer to an instance that AVC_file will dispose when done with. Or simply let AVC_file open the file for you!


text:
Q: overriding property attribute in class extension Say I have an interface
// Car.h
@interface Car
@property ( readonly) NSInteger rpm
@end

I want all the users of this to access this as readonly
In other areas that are private to my code and not exposed to users I want to manipulate the rpm
Say
// EngineFeedback.h
@interface EngineFeedback
@property(nonatomic , weak ) Car *theCar;
@end

// EngineFeedback.m
-(void) engineRPMReceived:(NSInteger) newRPM
{
     theCar.rpm = newRPM;
}

How can I accomplish this (where I need this to be writeable)
Can I define a class Extension that overrides the attributes
// Car_Internal.h
@interface Car ()
@property(readwrite) NSInteger rpm
@end

To be able to use this as
    // EngineFeedback.m
    #import "Car_Internal.h"
    -(void) engineRPMReceived:(NSInteger) newRPM
    {
         theCar.rpm = newRPM;
    }

Is this bad ? Is there a better way to achieve this ?

A: Using a class extension to override a readonly property declaration is perfectly fine. (In fact that's the primary purpose of the readonly attribute.) However, your Car class would need to provide an implementation of setRpm: for this to work at runtime.
So given the declarations you provided, somewhere in Car.m you'd need something like this:
- (void)setRpm:(NSInteger)newRPM
{
     _rpm = newRPM;
}

Note that the class extension can be declared in EngineFeedback.m if you prefer.


text:
Q: How to automatically redirect when user session expires in Laravel I want to redirect user automatically to the login page when session expires.
I know by Auth::check() i can check if user session exist or not. but if user refresh the page then only it is redirecting to login.
Suppose user's session expires, then immediately i want to redirect to login page without waiting for user to refresh the page.
Is it possible. please tell me the right way to do it.

A: I thing is not possible to with out any click you need a click listener
as work with ajax like this
in env  file so find line SESSION_LIFETIME=10 value change as wish in minate
and now
 $.ajax({
        type: "GET",
        url: filename,
        contentType: false,
        success: function (data) {
           // loaded your content without expire the sessions
        },
        error: function (xhr, status, error) {

           // you redirect tht to login page
           //hint: the laravel has unauthorized error for session expire or for Unauthorized users
            if (error === 'Unauthorized'){
                location.assign("login");
            }
        }
    });


text:
Q: MySQL designing database I am working actually on servers list and I'm wondering how can I design mysql table in the best way.
Index will render table with basic informations about server: address, port, players online, map, rank, ...
Server description, stats and other stuff will be in other subpage "more info about server"
In that case which design is better?
Servers(id, user_id, host, port, ...)
ServersInformations(id, server_id, players, map, ...)

Or just
Servers(id, user_id, host, port, players, map, rank)

and in
ServersInformations()

rest informations which will be rendered in subpage "more info about server"

A: What information goes on each page is really irrelevant. The only thing that matters is the type of data that you'll be storing. You should store all information about the server in a single table, aside from any columns that will contain multiple values.
For example, if your players column is just a count for the number of players, then this can be a part of the Servers table.
If you players column acually contains a list of players, you should make a new table for it, e.g.
ServerPlayers(id, playerName, ServerId)

A: Typically the tables in the database do not necessarily reflect your pages, but they reflect the relationships of your data.
If we take your first case where you have 2 tables, Servers and ServerInformation. You have a foreign key ServerInformation.server_id that (I presume) references Servers.id.
In this case what you are implying is that a Server could potentially have multiple entries in the ServerInformation table (i.e. a one-to-many relationship), all having the same server_id value, unless you make that unique, in which case it becomes a one-to-one relationship.
If you go for the second approach with one Servers table, you can still only get the fields you want for the index page. You will do a simple query that just gets the fields you need, for example: select id, user_id, host, port from servers
Unless you have a very specific reason for the first approach to separate the two tables (for example some Server entries don't have a ServerInformation entry, or you want some ServerInformation entries to have their server_id set to null if you set it to nullable), probably the one table approach is more adequate.


text:
Q: How to update MVC4 application to support Google authentication The old OAuthWebSecurity.RegisterGoogleClient(); in (RegisterAuth()) is not working now as google has disabled this in April. I have done the registration on google developer, and I got my client id and secret id, but with mvc old template there is no place to use for them!  RegisterGoogleClient() doesn't accept a client id.
I checked the mvc5 OWIN classes, and there will be a lot to update if I go that way, because I already have lots of functionality built over identity and webmatrix classes.
If anyone can throw me a link or a suggestion, it will be great.


text:
Q: how to remove the space when the image is clipped using css when clip property of the css then the image is clipped but the problem is, the clipped part of image reserve the space.Is there any way to remove that space after image is clipped.
HTML Code
// image with id: clip2

CSS Code
// code for clipping image
#clip2
    {
        position: absolute;
        clip: rect(0px, 150px,600px,0px);
    }

A: The clip property has been deprecated, so it may never work reliably.
If you could, please add a bit more detail about your intended goals, and maybe a screenshot or a sample of your code so we can show you some alternatives which work with modern standards.

A: clip (and the more recent clip-path) merely defines a path for clipping, it doesn't change the width/height of the element being clipped.
You can achieve what you want by using a div element with the size you want and set the image as a background image.

#clip2
    {
        position: absolute;
      background-image: url("image/background_right.png");
      width: 150px;
      height: 600px;
    }


text:
Q: Site routing for custom page doktypes in TYPO3 9.5 I created a news functionality on a page basis in TYPO3 9.5. The pages got special doktypes in order to seperate them from the other pages, a plugin is build to display pages as list.
The next thing I would like to do is to enhance the site routing for these page types. I would like to append the uid to the slug.
I tried to solve it with the SimpleEnhancer and a CustomEnhancer, like this:

routeEnhancers:
  Post:
    type: Custom
    routePath: '/{posttitle}'
    aspects:
      posttitle:
        type: PersistedPatternMapper
        tableName: 'pages'
        routeFieldPattern: '^(?P.+)-(?P\d+)$'
        routeFieldResult: '{title}-{uid}'

But I guess my configuration is wrong.
Is there any chance to solve appending the uid to the slug with the new site routing?

A: Short version: Since 15th march 2020 it is possible to overwrite the generation options with TCA overrides in the future (further information: https://forge.typo3.org/issues/87364).
It works like this now:
$GLOBALS['TCA']['pages']['types']['ID-OF-CUSTOM-DOKTYPE']['columnsOverrides'] = [
    'slug' => [
        'config' => [
            'generatorOptions' => [
                'fields' => ['title', 'uid'],
                'fieldSeparator' => '-',
                'prefixParentPageSlug' => true,
             ]
         ]
     ]
 ];


text:
Q: Variable not being set with return value class Person
  constructor: (@name, @org, @phone, @email) ->
    alert "#{name}: #{org} #{phone} #{email}"

__create = (title) ->
  p =
    name: ""
    org: "_organization"
    phone: "_phone"
    email: "_email"

  (p[pr] = "%#{title}#{p[pr]}%" for pr of p)

  Person(p.name, p.org, p.phone, p.email)

m = __create "author"

alert m.name

This consistently gives me:

TypeError: Cannot read property 'name' of undefined

However, the compiled JavaScript clearly assigns m a value:
__create = function(title) {
  var p, pr;
  p = {
    name: "",
    org: "_organization",
    phone: "_phone",
    email: "_email"
  };
  for (pr in p) {
    p[pr] = "%" + title + p[pr] + "%";
  }
  return Person(p.name, p.org, p.phone, p.email);
};

m = __create("author");

alert(m.name);

What am I missing here?

A: You need to use the new operator, e.g.,
__create = (title) ->
  p =
    name: ""
    org: "_organization"
    phone: "_phone"
    email: "_email"

  (p[pr] = "%#{title}#{p[pr]}%" for pr of p)

  new Person(p.name, p.org, p.phone, p.email)

http://coffeescript.org/#classes


text:
Q: How to empty box of asterisks around text perl? I'm bringing in text from a file and I need it have a border of asterisks around it. How do I do that?
I've tried this:
my $x      = 100;  # width
my $y      = 96;  # number of "hollow" rows

my $solid  = '*' x $x . $/;
my $hollow = '*' . ' ' x ($x-2) . '*' . $/;

print OUT $solid,
    ($hollow) x $y,
      $solid;

A: You can match an asterisk in a regular expression with either \* or [*].  So to remove an asterisk just replace it with nothing:
$text =~ s/[*]//;

To replace asterisks surrounded by optional whitespace at the start of a line:
$text =~ s/^\s*[*]+\s*//mg;

Similarly at the end:
$text =~ s/\s*[*]+\s*$//mg;


text:
Q: How to calculate the number of days between stages in this df Python Pandas? df = pd.DataFrame({'Campaign ID':[48464,48464,48464,48464,26380,26380,22676,39529,39529,46029,46029,46029,17030,46724,46724,39379,39379,39379],
'Campaign stage':["Lost","Developing","Discussing","Starting","Discussing", "Starting","Developing",    "Discussing","Starting","Developing",   "Discussing","Starting","Developing",   "Developing","Discussing","Lost",   "Developing","Discussing"],
'Stage Number':[-1, 3,  2,  1,  2,  1,  3,  2,  1,  3,  2,  1,  3,  3,  2,  -1, 3,  2],
'Campaign Date':["2/8/2019","1/9/2019","1/3/2019","3/3/2018","2/14/2019","12/5/2018","7/25/2018","6/8/2018","3/4/2018","12/8/2018","9/9/2018","5/31/2018","6/7/2018","3/27/2018","1/6/2018","2/15/2019","12/15/2018","9/4/2018"]})

pvt = pd.pivot_table(df,values=['Campaign stage'],index=['Campaign ID','Campaign stage','Stage Number','Campaign Date'],aggfunc='count')
pvt.sort_values(['Campaign ID','Campaign Date'],ascending=[True,False])

Hi guys, I have the above dataframe and I'd like to calculate the number of days between campaign stage "starting" and "discussing" for each campaign and then calculate the average.
Because of the data quality, the campaign stages are not consistent. So, for campaigns don't have the two stages "starting" and "discussing", I want to set as 0.
I created a pivot table view of the data and sorted the campaign date descending order...But I don't know how to do next.
Thanks in advance for the help.

A: Here is my proposal, starting from your df:
df['Campaign Date'] = pd.to_datetime(df['Campaign Date'])
df = df[df['Campaign stage'].isin(['Starting', 'Discussing'])]

pvt = pd.pivot_table(df,values=['Campaign stage'],index=['Campaign ID','Campaign stage','Stage Number','Campaign Date'],aggfunc='count')
pvt = pvt.sort_values(['Campaign ID','Campaign Date'],ascending=True).reset_index(level=3)

pvt.groupby(level=0).diff().sum(level=0)

The output would be:
Campaign ID - Campaign Date
26380   71 days
39379   0 days
39529   96 days
46029   101 days
46724   0 days
48464   306 days

If what you are looking for is the total mean:
pvt.groupby(level=0).diff().sum(level=0).mean()

Which is:
95 days 16:00:00

A: df['Campaign Date'] =  pd.to_datetime(df['Campaign Date'],format='%m/%d/%Y')
compare= {}
for ids,gp in df.groupby('Campaign ID'):
    try:
        compare[ids]= gp.loc[gp['Campaign stage']=='Discussing']['Campaign Date'].iloc[0] - gp.loc[gp['Campaign stage']=='Starting']['Campaign Date'].iloc[0]
    except:
        compare[ids] =0

df['new_col'] = df['Campaign ID'].apply(lambda x:compare[x])

A: I am unsure in which form you would like your end result to be, the below sample assumes you want it in a new dataframe.
We can go multiple route, though, I chose to create a function below and decompose each step for clarity.

*

*Step 1: update your date data type to datetime for comparison

*Step 2: call out function    Step 2.1: define empty list to store our cids values and days between starting and discussing

*

*Step 2.2:
Get all unique cid and iterate through each one

*Step 2.3: Check if the cid has both staging we are interested with

*

*Step 2.3.1: if not assign 0 to this cid

*Step 2.3.2: else calculate the difference between discussing and starting

*Step 2.4: create our new dataframe and return it

*Step 2.5: Using df.loc create and calculate our average day index

Code
# First we need to modify your data type to compare the dates
df['Campaign Date'] = pd.to_datetime(df['Campaign Date'])

df_days = getDays(df)

# We create a new index called 'Average' that will assign values to the days column
df_days.loc['Average','days'] = df_days.days.mean()

def getDays(df):
    days = list()
    cids = list()

    for cid in df['Campaign ID'].unique():
        stages = df[(df['Campaign ID'] == cid) &
                    (df['Campaign stage'].str.lower().isin(['discussing', 'starting']))]['Campaign stage'].unique()

        if len(stages) < 2:
            d = 0
            c = cid

            days.append(d)
            cids.append(c)

        else:
            starting = df[(df['Campaign ID'] == cid) & (df['Campaign stage'].str.lower() == 'starting')]['Campaign Date'].dt.date.values
            discussing = df[(df['Campaign ID'] == cid) & (df['Campaign stage'].str.lower() == 'discussing')]['Campaign Date'].dt.date.values

            d = (discussing - starting)[0].days

            c = cid

            days.append(d)
            cids.append(c)

    dff = pd.DataFrame({
        'cids': cids,
        'days': days
    })

    return dff

Out
        cids    days
0       48464.0 306.00
1       26380.0 71.00
2       22676.0 0.00
3       39529.0 96.00
4       46029.0 101.00
5       17030.0 0.00
6       46724.0 0.00
7       39379.0 0.00
Average NaN   71.75


text:
Q: How to change the default colors created by groupOTU/groupClade in ggtree When grouping clades by any parameter in a tree file with groupClade or groupOTU, how can one select the colors displayed when plotting?

A: Use:
ggtree(tree, aes(color = group)) +
scale_color_manual(values =c ('#00000', '#AB274F')


text:
Q: Notepad++ doesn't color String type in my programs, why? I was looking at some code i've written, an example from a book:
public class Acquisto {
    private String nome;
    private int dimGruppo;
    private double prezzoGruppo;
    private int articoliAcquistati;

Well, Notepad++ doesn't color the String type like it does with the other types (int, char).
Is it normal ? Or is it because i moved all my documents from C: to D:, my hard disk ?

A: Since String is a java class not any reserve keyword, maybe that's the reason it's not showing any color on Notepad++
Try words like below, it will show in colors in notepad++ as those are the reserve keywords :
    switch
    strictfp
    short
    static
    synchronized
    super

While String wouldn't show as it's a predefined class in java.lang package
String str = "ABC";


text:
Q: Reformatting a list of dates from older to new I am trying to create a stock graph but im having some issues like, the y axis shows the numbers instead of the dates and the main issue is i want to change the format of strings in a list. They are dates but have been converted into strings.
Here is the data;
{"rates":{"2020-05-04":{"TRY":7.0308901481,"USD":1.0},"2020-03-25":{"TRY":6.4350235522,"USD":1.0},"2020-04-23":{"TRY":6.9428147048,"USD":1.0},"2020-03-31":{"TRY":6.5774917853,"USD":1.0},"2020-03-30":{"TRY":6.5683342396,"USD":1.0},"2020-04-22":{"TRY":6.9943866753,"USD":1.0},"2020-04-28":{"TRY":6.9977935092,"USD":1.0},"2020-03-27":{"TRY":6.4621481279,"USD":1.0},"2020-04-07":{"TRY":6.7581074874,"USD":1.0},"2020-04-09":{"TRY":6.7390264102,"USD":1.0},"2020-05-05":{"TRY":7.0889975099,"USD":1.0},"2020-04-01":{"TRY":6.6683430871,"USD":1.0},"2020-05-06":{"TRY":7.1414823725,"USD":1.0},"2020-05-11":{"TRY":7.0764966741,"USD":1.0},"2020-04-16":{"TRY":6.9347905952,"USD":1.0},"2020-04-14":{"TRY":6.7930311046,"USD":1.0},"2020-04-15":{"TRY":6.8873704485,"USD":1.0},"2020-03-23":{"TRY":6.5859222851,"USD":1.0},"2020-04-02":{"TRY":6.6628461397,"USD":1.0},"2020-04-17":{"TRY":6.9043278085,"USD":1.0},"2020-03-26":{"TRY":6.4117111374,"USD":1.0},"2020-03-24":{"TRY":6.4659227151,"USD":1.0},"2020-05-07":{"TRY":7.2143188352,"USD":1.0},"2020-04-21":{"TRY":6.9814524315,"USD":1.0},"2020-04-24":{"TRY":6.9782407407,"USD":1.0},"2020-04-03":{"TRY":6.7033843301,"USD":1.0},"2020-04-27":{"TRY":6.9825838555,"USD":1.0},"2020-04-06":{"TRY":6.7774997683,"USD":1.0},"2020-05-08":{"TRY":7.1245965139,"USD":1.0},"2020-04-20":{"TRY":6.926335175,"USD":1.0},"2020-04-30":{"TRY":6.9859323281,"USD":1.0},"2020-04-29":{"TRY":6.988286294,"USD":1.0},"2020-04-08":{"TRY":6.7885199154,"USD":1.0}},"start_at":"2020-03-23","base":"USD","end_at":"2020-05-12"}

I tried something like this,and many more things but it didn't work;
    gunler = []
    [gunler.append(key) for key in veri["rates"].keys()]

    sorted_gunler = (datetime.datetime.strptime(i, "%Y-%M-%d") for i in gunler)
    print(sorted_gunler)

The output was:
<generator object main.<locals>.<genexpr> at 0x7fcd0f0a8f68>

Tried this also:
new_list = [datetime.datetime.strptime(str(i), '%Y-%m-%d').strftime('%m-%d-%Y') for i in gunler]

Output:
['2020-05-04', '2020-03-25', '2020-04-23', '2020-03-31', '2020-03-30', '2020-04-22', '2020-04-28', '2020-03-27', '2020-04-07', '2020-04-09', '2020-05-05', '2020-04-01', '2020-05-06', '2020-05-11', '2020-04-16', '2020-04-14', '2020-04-15', '2020-03-23', '2020-04-02', '2020-04-17', '2020-03-26', '2020-03-24', '2020-05-07', '2020-04-21', '2020-04-24', '2020-04-03', '2020-04-27', '2020-04-06', '2020-05-08', '2020-04-20', '2020-04-30', '2020-04-29', '2020-04-08']

Then i came up with;
    veri = r.json()

    gunler = []
    [gunler.append(key) for key in veri["rates"].keys()]

    sorted(gunler, key=lambda x: datetime.datetime.strptime(x,'%Y-%M-%d'))
    print(gunler)

It gave me the same output:
['2020-05-04', '2020-03-25', '2020-04-23', '2020-03-31', '2020-03-30', '2020-04-22', '2020-04-28', '2020-03-27', '2020-04-07', '2020-04-09', '2020-05-05', '2020-04-01', '2020-05-06', '2020-05-11', '2020-04-16', '2020-04-14', '2020-04-15', '2020-03-23', '2020-04-02', '2020-04-17', '2020-03-26', '2020-03-24', '2020-05-07', '2020-04-21', '2020-04-24', '2020-04-03', '2020-04-27', '2020-04-06', '2020-05-08', '2020-04-20', '2020-04-30', '2020-04-29', '2020-04-08']

But i want something like;
['2020-05-04','2020-05-05','2020-05-06'....]

The code works fine, but the result is not correct;
def main(): #the main section
    anaBirim = input('\n' + 'Ana para birimini(kod cinsinden) giriniz: ').upper() #firstVal
    ikincilBirim = input('İkincil para birimini(kod cinsinden) giriniz: ').upper() #secondVal

if anaBirim in para_birimleri and ikincilBirim in para_birimleri:
    gun = int(input("Geriye dönük kaç günlük verinin hesaplanmasını istiyorsunuz: "))
    today = datetime.date.today()
    geriye_donuk = today - datetime.timedelta(days=gun)
    url = ''.join(['https://api.exchangeratesapi.io/history?start_at={}&end_at={}&base={}&symbols={},{}'.format(geriye_donuk,today,anaBirim,anaBirim,ikincilBirim)])
    ans = input("Ücüncü bir para birimi karşılaştırmak ister misiniz? E/H \n Cevap:   ").upper()
    r = requests.get(url)
    veri = r.json()

    prices = []
    [prices.append(value) for value in veri["rates"].values()]

    price_one = []
    price_two = []
    for price in prices:
        p_one = price["{}".format(anaBirim)]
        price_one.append(p_one)
        p_two = price["{}".format(ikincilBirim)]
        price_two.append(p_two)

    if ans == "H":
        plt.figure()

        # ana birimin karşısındaki değeri
        plt.plot(price_two,color="red")
        plt.xlabel("{}\'nin {} günlük süreçteki değişimi".format(ikincilBirim,gun))
        plt.ylabel("Değer")
        plt.title('{} {}\'nin {} olarak karşılığı '.format(int(price_one[0]),anaBirim,ikincilBirim))
        plt.show()

Any help would be greatly appreciated.

A: I think the answer might be much simpler than that. Since your dates are formatted as "year-month-day" and are in string format, you can simply pass the list to a sort function and it'll do the job, no need to parse as a datetime object.
Use this if you want to change it inplace:
gunler.sort()

Use this if you want to keep the current list without changing it:
new_list = sorted(gunler)


text:
Q: google spring oauth2 client works on local but not on internet
I am here after pulling some hair out.
The login with google oauth2 works fine in local but failed under public domain.
Here are the logs from both:
==== request in local
2022-04-28 17:11:26.080 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : HTTP POST https://www.googleapis.com/oauth2/v4/token
2022-04-28 17:11:26.080 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Accept=[application/json, application/*+json]
2022-04-28 17:11:26.080 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Writing [{grant_type=[authorization_code], code=[4/0AX4XfWghwFo-03F8JRldcp8xsqSzg31NkVZpHnPqpdXV4hNcTKehChPzrSaTqRVBfh8g4w], redirect_uri=[http://localhost:8080/login/oauth2/code/google]}] as "application/x-www-form-urlencoded;charset=UTF-8"
2022-04-28 17:11:26.225 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Response 200 OK
2022-04-28 17:11:26.225 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Reading to [org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse] as "application/json;charset=utf-8"
2022-04-28 17:11:26.226 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : HTTP GET https://www.googleapis.com/oauth2/v3/certs
2022-04-28 17:11:26.226 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Accept=[text/plain, application/json, application/*+json, */*]
2022-04-28 17:11:26.242 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Response 200 OK
2022-04-28 17:11:26.242 DEBUG 11004 --- [nio-8080-exec-6] o.s.web.client.RestTemplate              : Reading to [java.lang.String] as "application/json;charset=UTF-8"

=====request under public domain
2022-04-28 16:54:05.949 DEBUG 13353 --- [nio-8443-exec-3] o.s.web.client.RestTemplate              : HTTP POST https://www.googleapis.com/oauth2/v4/token
2022-04-28 16:54:05.956 DEBUG 13353 --- [nio-8443-exec-3] o.s.web.client.RestTemplate              : Accept=[application/json, application/*+json]
2022-04-28 16:54:05.957 DEBUG 13353 --- [nio-8443-exec-3] o.s.web.client.RestTemplate              : Writing [{grant_type=[authorization_code], code=[4/0AX4XfWjfng4hE-uzmk1CnWgRz922In29TeNs9efZxigfeSaVwvvoCrk-b56rOzFeMEDn0Q], redirect_uri=[https://www.clubspj.com/login/oauth2/code/google]}] as "application/x-www-form-urlencoded;charset=UTF-8"
2022-04-28 16:54:06.064 DEBUG 13353 --- [nio-8443-exec-3] o.s.web.client.RestTemplate              : Response 400 BAD_REQUEST

I made sure the url is matching

Using this library, version is 2.6.7
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>

Following are the requests made in order when trying to login with google oauth2
GET 302 https://www.clubspj.com/oauth2/authorization/google

GET 200 https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=294427952059-ngva8hkoa4cl1af249repefc8lnksl87.apps.googleusercontent.com&scope=openid%20profile%20email&state=hiwVEoh6pbzGA4HueQpsF_MydzpyJ5uxnS7FcAoRaKM%3D&redirect_uri=https://www.clubspj.com/login/oauth2/code/google&nonce=3S3BLRPDsdXB6orOGF52YFIHnbyaLLtO8NGjHEDILYo

GET 302 https://accounts.google.com/signin/oauth/consent?authuser=0&part=AJi8hANiL7v0LYZsyPvT1Vg6t-K2lzlwtCjwELEoi84mtcyDyjIAhY3FkooOuQ9YwoG10HrQyEv3f4H4ZNN_mVry937SfMm_68H1Zw9ZJfkgRVkPM5aTYsa7jdctKNJWe4I4mEJFxeQ0iqizcZfEXw-COkk3L_3wW1CxL2gwCygMud5-Qv1nDJMblMV1dl2CtaWamt30GyrWoaG_g14mRGLvcmHHruvQD3Uid7t0PI9hNtYYqewJLTdCi6dmn8pLa7MJPqEHdp2nyKJf5YSPqAskAn4BX-_aaLXKeNnQJhC2Cjzpwnux_zKol50e8ymHU5PQpP5hU23lArmBPXU3shEEi4m_yA2R41p8vFaB3f9HpOqp9ThEgMp8nv_po6C7Kk3qLMoWR2COAYvv4zflcA_157vUt6jhDpKoLw2cf7Fbq_4afG1QKiI8x9LOn4iJq6Q2JBh_AxlX9truJZb45fNbDI1nfnrOEQ&as=S-872222817%3A1651179243534195&pli=1&rapt=AEjHL4MtRiws0sgSbs9qRhpREDRpzEWcleEMkDeuoK78Ie-A3UissN40zZ2GdDLIIqoA4P7tjoqyQgVmVDmgmqt8a2qv_ElA-w
GET 302 https://www.clubspj.com/login/oauth2/code/google?state=hiwVEoh6pbzGA4HueQpsF_MydzpyJ5uxnS7FcAoRaKM%3D&code=4%2F0AX4XfWjfng4hE-uzmk1CnWgRz922In29TeNs9efZxigfeSaVwvvoCrk-b56rOzFeMEDn0Q&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=none

the last request caused error and redirected to login?error, details of the request:
Response Header:
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Location: https://www.clubspj.com/login?error
Content-Length: 0
Date: Thu, 28 Apr 2022 20:54:06 GMT
Keep-Alive: timeout=60
Connection: keep-alive

Request Header:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
Connection: keep-alive
Cookie: AWSALBTG=5EB4qie5RCxExuTp2gqDRZuZGDgJBVO8lBlofFhpkZA0J9iQ7JahcSn/jvAmef/eRSL0GALK9P9xcOZgNLSWIwcEEMSRslwigzMPrZQFpQ2pmLPKSx9Apn19TlEENuLOMFmRgG7bbIziTYB+RyqCLZosHMvIIU7Wbcmhsdlz6e1JL9NKYJU=; AWSALBTGCORS=5EB4qie5RCxExuTp2gqDRZuZGDgJBVO8lBlofFhpkZA0J9iQ7JahcSn/jvAmef/eRSL0GALK9P9xcOZgNLSWIwcEEMSRslwigzMPrZQFpQ2pmLPKSx9Apn19TlEENuLOMFmRgG7bbIziTYB+RyqCLZosHMvIIU7Wbcmhsdlz6e1JL9NKYJU=; JSESSIONID=7F3D126AA8A114A2EAB4937EB1A911DA
Host: www.clubspj.com
Referer: https://accounts.google.com/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Lastly I am running app on EC2 under elastic IP. Verified that all the JSESSIONID are the same between clubspj.com requests.
Thanks in advance!

A: It's always the little things!
To have google login work in local, you only needs client-id.
Works as expected after I added the long forgotten client-secret.


text:
Q: How to make a GridView snap scroll Is there a way to make a GridView snap to a row while scrolling?
It seems that applying the known fixes for a ListView does not suffice for a GridView.

A: Note: This code was tested for API 23
Note: listPaddingTop == 11, and listPaddingBottom == 10 for my GridView. Couldn't find where this is set, may be default (didn't see it in the style referenced by Android.Resource.Attribute.GridViewStyle in the below constructor chain (which points to Widget.GridView/Widget.AbsListView in res/values/styles.xml). Need to check source.
Note: Calling SetPadding(0,0,0,0) in constructor has no effect on listPaddingTop (Bottom).
public class SnapScrollGridView : GridView,
    //View.IOnScrollChangeListener
    AbsListView.IOnScrollListener
{
    private bool _bSnapScroll;

    public new int FirstVisiblePosition { get; set; }

    // ctor chain
    public SnapScrollGridView(Context context) : this(context, null) { }
    public SnapScrollGridView(Context context, IAttributeSet attrs) : this(context, attrs, Android.Resource.Attribute.GridViewStyle) { }
    public SnapScrollGridView(Context context, IAttributeSet attrs, int defaultStyleAttr) : this(context, attrs, defaultStyleAttr,0) { }
    public SnapScrollGridView(Context context, IAttributeSet attrs, int defaultStyleAttr, int defStyleRes) : base(context, attrs, defaultStyleAttr, defStyleRes)
    {
        _bSnapScroll = false;
        FirstVisiblePosition = 0;
        //SetOnScrollChangeListener(this);
        SetOnScrollListener(this);
        // no effect on listPaddingTop (or bottom)
        // SetPadding(0, 0, 0, 0);
    }

    void AbsListView.IOnScrollListener.OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
    {
        // firstVisibleItem and visibleItemCount not accurate
    }

    protected override void OnOverScrolled(int scrollX, int scrollY, bool clampedX, bool clampedY)
    {
        // - would be very useful, however is called after OnScrollStateChanged()
        // - may be able to refactor OnScrollStateChanged to work in conjuction with this
        base.OnOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }

    void AbsListView.IOnScrollListener.OnScrollStateChanged(AbsListView view, [GeneratedEnum] ScrollState scrollState)
    {
        switch (scrollState)
        {
            case ScrollState.TouchScroll:
            case ScrollState.Fling:
                break;

            case ScrollState.Idle:

                if (_bSnapScroll)
                {
                    _bSnapScroll = false;
                }
                else
                {
                    View item = view.GetChildAt(0);
                    int top = System.Math.Abs(item.Top);
                    int btm = System.Math.Abs(item.Bottom);

                    // OVERSCROLL TOP ("topping out")
                    // - user tried scrolling up (swiping down) past top

                    if (top == view.ListPaddingTop && view.FirstVisiblePosition == 0)
                    {
                        this.FirstVisiblePosition = 0;
                        return;
                    }

                    // OVERSCROLL BOTTOM ("bottoming out")
                    // - for now, user needs to hit bottom to force snap when last row wont like "normal"
                    // - this happens for certain GridView height and item/row height combinations
                    // - could smooth scroll in the same manner as below, but requires more code

                    // nRows, curRow round down (floor() not needed)
                    int nRows = view.Count / NumColumns;
                    int curRow = view.LastVisiblePosition / NumColumns;

                    if (curRow == nRows)
                    {
                        View item2 = view.GetChildAt(view.LastVisiblePosition-view.FirstVisiblePosition);
                        int top2 = System.Math.Abs(item2.Top);
                        int btm2 = System.Math.Abs(item2.Bottom);

                        if (btm2 == view.Height - view.ListPaddingBottom)
                        {
                            //view.SetSelection(view.LastVisiblePosition);
                            this.FirstVisiblePosition = view.LastVisiblePosition;
                            return;
                        }
                    }

                    // EXCEPTION CASE: smore info below
                    if (item.Top == 0)
                    {
                        view.SetSelection(0);
                        this.FirstVisiblePosition = 0;
                        return;
                    }

                    _bSnapScroll = true;

                    // Compensate for ListPaddingTop
                    // - initially gives a positive offset (11 for me),
                    //   observed when attempting to scroll upward from top
                    //   (swipe downward while at very top)
                    //   (break point will show item.Top = 11)
                    // - if scrolling down a tiny bit, item.Top lessens,
                    //   eventually becoming zero, then negative after that

                    int scrollBy = item.Top > 0
                        ? top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop - top)
                        : top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop + top);

                    // ALTERNATIVE SYNTAX - debug friendly (less cool)
                    //int scrollBy = 0;
                    //if (item.Top > 0)
                    //    scrollBy = top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop - top);
                    //else
                    //    scrollBy = top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop + top);

                    if (scrollBy <= 0)
                    {
                        this.FirstVisiblePosition = view.FirstVisiblePosition;
                    }
                    else
                    {
                        this.FirstVisiblePosition = view.FirstVisiblePosition + NumColumns;
                    }

                    view.Post(() => { view.SmoothScrollBy(scrollBy, 1000); });
                }
                break;

            default: break;
        }
    }

Example of exception case noted above
If user scrolls down, from very top, by exactly the padding amount, and SmoothScrollBy() is called with the resulting value calculated below (which is -view.ListPaddingTop since item.Top == 0), no scrolling occurs for some reason (leaving _bSnapScroll inconsistent since OnScrollStateChanged() subsequently misfires).
                    //if (item.Top == 0)
                    //{
                    //    view.SetSelection(0);
                    //    return;
                    //}

                    _bSnapScroll = true;

                    //int scrollBy = item.Top > 0
                    int scrollBy = item.Top >= 0
                        ? top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop - top)
                        : top >= btm ? btm - view.ListPaddingTop : -(view.ListPaddingTop + top);

Usage
private void GridViewAdapterLoad()
{
    int pos = ((SnapScrollGridView)_gridView).FirstVisiblePosition;

    _gridView.Adapter = new GridViewAdapter(
        Activity,
        Resource.Layout.GridItem,
        Model.GridItems);

    _gridView.SetSelection(pos);
}

Positing grid to bottom after adding a new item (to end)
private void GridViewLoad(bool bNewItem)
{
    _controller.LoadGridItems();

    _gridView.Adapter = null;

    GridViewAdapterLoad();

    if (bNewItem)
    {
        int count = _gridView.Count;
        int row = --count / _gridView.NumColumns; // floor not needed
        int pos = row * _gridView.NumColumns;

        ((SnapScrollGridView)_gridView).FirstVisiblePosition = pos;

        _gridView.SetSelection(pos);

        // Would be sweet to scroll from current position, but isn't.
        //_gridView.Post(() => { _gridView.SmoothScrollToPosition(pos); });
    }
}


text:
Q: Why is image very Dark with AVCaptureSession We have Xamarin Forms solution and in iOS project we are trying to create photo on button click. Problem is image is very dark. It is almost black. Why is this happening? Here is a code:
var _captureSession = new AVCaptureSession();
var _captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);
var _captureDeviceInput = AVCaptureDeviceInput.FromDevice(_captureDevice);
_captureSession.AddInput(_captureDeviceInput);
_captureSession.StartRunning();

private async void OnButtonClick()
{
    var output = new AVCaptureStillImageOutput { OutputSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecJPEG) };
    _captureSession.AddOutput(output);

    var buffer = await output.CaptureStillImageTaskAsync(output.Connections[0]);
    NSData data = AVCaptureStillImageOutput.JpegStillToNSData(buffer);

    UIImage image = UIImage.LoadFromData(data);
    //image = RotateImage(image);
    NSData imageData = image.AsPNG();
    byte[] byteArray = imageData.ToArray();

    IFolder folder = FileSystem.Current.LocalStorage;
    IFile file = await folder.CreateFileAsync("image.png", CreationCollisionOption.ReplaceExisting);

    using (Stream stream = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
    {
        stream.Write(image, 0, image.Length);
    }
}

Here is image:

A: Line:
_captureSession.AddOutput(output);

should go before button click (before StartRunning). With that change image has normal brightness and also rotation is not needed.


text:
Q: Collapse Multiple Same Answers to Question I've noticed users with higher reputations get their answers upvoted over others, even if they provide the same or very similar answer.  Why is their answer any more correct than another?
I would suggest that perhaps similar/same answers should be "collapsed" and upvotes credited to the original (chronologically) answer.  Thoughts?

A: How you answer is as important as what you say in your answer.

A: Personally, I try to make my answers stand out. Technically I provide the same answer as a lot of others, but I try to add more information, links, or something else to make it stand out.
For instance:

*

*My answer here technically has the same information as another

*Same thing here.

*and here.

These are all basically the same answer, but the differences are in the quality you provide.

A: All the collapsing would have to be done manually, and in a lot of cases, there is slightly different information, so a lot of judgement calls would have to be made on whether two answers are the same or not.

A: I could see that this would get ignored in a hurry.  There's no decent systematic approach to this, the coding would be quite complex.

A:
I would suggest that perhaps similar/same answers should be "collapsed" and upvotes credited to the original (chronologically) answer.

I suggest that if you post an answer and find that someone else has already posted one that's the same or very similar, you either improve yours to make it stand out, or delete it.
I also suggest that if you're reading a question and find two answers that are effectively the same, you down-vote the one posted later.
You can do this on your own or with friends; no special tools or moderator intervention needed!


text:
Q: Bounds on a set of points in the plane whose subsets all have a line of symmetry Suppose we have a set $S$ of points in the plane, not all colinear, with the property that any nonempty subset of $S$ has a line of symmetry. What is the maximum size of $S$?
I suspect that the unique maximal configuration is a regular pentagon along with its center:

However, I haven't had much luck proving this, and my attempts at providing an upper bound didn't seem to get below numbers around $20$ before devolving into horrible casework and intersection-counting.
Any thoughts on proofs, references, or larger sets $S$ with this property? If there are well-known generalizations, e.g. to 3-space, I'd be curious about that too.


text:
Q: How can I intercept log messages in Spring Boot? I am currently logging messages using a combination of:
private final Logger log = Logger.getLogger(this.getClass().getSimpleName());

[...]

if (log.isLoggable(Level.INFO)) {
    log.log(Level.INFO, message);
}

Is there a way I can intercept all log messages before they reach the console so that I can, for example, persist them in the database?
Similar to how HandlerInterceptor can intercept web requests?


text:
Q: How to correctly disable auto-hide in Unity 2d?
Possible Duplicate:
How do I set the launcher to always show in Unity 2d?

I'm using unity-2d in ubuntu 11.04 since 3d version is not working good in virtual machines (i use virtualbox from MacOS X). All works fine except auto-hide.
With windows and Mac OS i get user for taskbar to be permanently on the screen - so i have issued "gconf-editor" and changed auto-hide for unity from "2" to "0". This stops it from hiding, but now all windows that i start (firefox, explorer etc) completely ignores unity taskbar and alignes themself on the left side of screen as if taskbar is hidden :(.
Is it any way to fix it and make fullscreen / newly created windows to correctly align themselves on the right side of taskbar and not ignore it?

A: Alan's answer doesn't work on Unity 2D because it doesn't use Compize.
If I got you right this might be the solution for your question:
In gconf-editor enable "use_strut" in Unity 2D's settings (desktop -> unity-2d -> launcher). In addition Mariano Chavero has made "A simple GUI for Unity-2D Settings": http://marianochavero.wordpress.com/2011/04/20/a-simple-gui-for-unity-2d-settings-ubuntu-11-04/

A: *

*Install CompizConfig Settings Manager.
sudo apt-get install
compizconfig-settings-manager

*Navigate to the Ubuntu Unity
Plugin tab.

*Change Hide Launcher to
    Never, and go back.

*Scroll down to the Place Windows
tab.

*Experiment with the Placement
Mode until you find what you are
looking for.

I don't have Unity, otherwise I would know what Placement Mode you need.


text:
Q: Is double check lock broken for all use case? I understand that double check locking is broken for singleton lazy initialization:
// SingletonType* singleton;
// std::mutex mtx;
SingletonType* get()
{
  if(singleton == nullptr){
    lock_guard _(mtx);
    if(singleton == nullptr) {
      singleton = new SingleTonType();
    }
  }
  return singleton;
}

The above is broken because instructions may be re-arranged, so pointer assignment to singleton may happen before or during SingletonType constructor call, thus when thread1 acquires the lock and initialize, thread2 may see singleton no longer null while construction for the new SingleTon() has not been completed, leading to undefined behavior.
With this understanding, I think double-check-lock broken is only broken for the singleton initialization case. For example, I think the following usage is safe. Is this understanding correct?
// int id = 0;
// int threshold = 1000;
// std::mutex mtx;

void increment()
{
   int local = __atomic_fetch_add(&id, 1l, __ATOMIC_RELAXED);
   if(local >= threshold) {
      const std::lock_guard<std::mutex> _(mtx);
      if(local >= threshold) {
        // Do periodic job every 1000 id interval
        threshold += 1000;
      }
   }
}

A: The only undefined behaviour here is that you read from a pointer and you write to it on a different thread without synchronisation. Now this might be fine with most pointers (especially if writing to a pointer is atomic), but you can easily be explicit:
std::atomic<SingletonType*> singleton;
std::mutex mtx;

SingletonType* get()
{
    SingletonType* result = singleton.load(std::memory_order_relaxed);
    if (!result) {
        std::scoped_lock _(mtx);
        result = singleton.load(std::memory_order_relaxed);
        if (!result) {
            result = new SingletonType();
            singleton.store(result, std::memory_order_relaxed);
        }
    }
    return result;
}

// Or with gcc builtins
SingletonType* singleton;
std::mutex mtx;

SingletonType* get()
{
    SingletonType* result;
    __atomic_load(&singleton, &result, __ATOMIC_RELAXED);
    if (!result) {
        std::scoped_lock _(mtx);
        __atomic_load(&singleton, &result, __ATOMIC_RELAXED);
        if (!result) {
            result = new SingletonType();
            __atomic_store(&singleton, &result, __ATOMIC_RELAXED);
        }
    }
    return result;
}

However, there is an easier implementation:
SingletonType* get()
{
    static SingletonType singleton;
    return &singleton;
    // Or if your class has a destructor
    static SingletonType* singleton = new SingeltonType();
    return singleton;

}

Which is typically also implemented as a double-checked lock (except on a hidden isSingletonConstructed bool instead of whether the pointer is null)

Your initial worry seems to be that new SingletonType() is equivalent to operator new(sizeof(SingletonType)) and then calling the constructor on the acquired storage, and a compiler might reorder calling the constructor to after the pointer is assigned. However, the compiler is not allowed to reorder the assignment, because that would have observable effects (like you noted about another thread returning singleton while the constructor is still running).

Your increment function can concurrently read and write to threshold (In the first check in the double-checked lock and after acquiring the mutex and incrementing threshold += 1000), so it could have race conditions.
You can fix it like so:
void increment()
{
   int local = __atomic_fetch_add(&id, 1l, __ATOMIC_RELAXED);
   if (local >= __atomic_load_n(&threshold, __ATOMIC_RELAXED)) {
      const std::lock_guard<std::mutex> _(mtx);
      int local_threshold = __atomic_load_n(&threshold, __ATOMIC_RELAXED);
      if (local >= local_threshold) {
        // Do periodic job every 1000 id interval
        __atomic_store_n(&threshold, local_threshold + 1000, __ATOMIC_RELAXED);
      }
   }
}

But you don't really need atomics in this case, because local will be every integer exactly once (as long as it is only modified via increment), so you can instead do something like:
// int id = 0;
// constexpr int threshold = 1000;
// std::mutex mtx;  // Don't need if jobs can run in parallel

void increment()
{
   int local = __atomic_fetch_add(&id, 1l, __ATOMIC_RELAXED);
   if (local == 0) return;
   if (local % threshold == 0) {
      const std::lock_guard<std::mutex> _(mtx);
      // Do periodic job every 1000 id interval
   }
}