text:
Q: Display information of one user from the list There is such a list of users:

 {{user.surname_first_name}}

{{user.position}}

And next to it there is a block where full information about the user is displayed. Here's a small piece:

  <form>

           Surname
           <input type="text" class="form-control" [(ngModel)]='user.surname' name="surname" >

           Name
           <input type="text" class="form-control" [(ngModel)]='user.name' name="name" >

        ....

  </form>

Here's how to make it so that by clicking on a specific list user, its data is displayed in a block with information.

A: You could 'Output' the selected user from the list and then 'Input' this user to the information block you are making. Try making two different components and a parent component handling all delegations.
You may refer to https://embed.plnkr.co/OeUYze7djU90AWmc2Sno/ to get a feeling of how to use @Input and @Output.

A: You could add a click event binding to your .list-group-item, that updates a variable (selectedUser) with the selected user's data. Your block can then pull the data from selectedUser.
User List html:

 {{user.surname_first_name}}

{{user.position}}

Block html:

  <form>

           Surname
           <input type="text" class="form-control" [(ngModel)]='selectedUser.surname' name="surname" >

           Name
           <input type="text" class="form-control" [(ngModel)]='selectedUser.name' name="name" >

        ....

  </form>

Component TS file:
....
export class YourComponentName  {

  selectedUser = null;

  users = [
    {'id': 1, 'position': 1, 'first_name': 'John', 'last_name': 'Adams'},
    {'id': 2, 'position': 2, 'first_name': 'Joan', 'last_name': 'Smith'}
  ]

  updateSelectedUser(userId) {
    this.selectedUser = this.users.find(el => {
      return el.id === userId
    })
  }
}

Here's a stackblitz that shows a proof of concept https://stackblitz.com/edit/angular-hnjt3f


text:
Q: Functions not recognised inside Pandas UDF function I am using Pandas UDF on Pyspark.
I have a main file __main_.py with:
from pyspark.sql import SparkSession
from run_udf import compute

def main():
    spark = SparkSession.builder.getOrCreate()
    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))
    df = compute(df)
    df.show()
    spark.stop()

if __name__ == "__main__":
    main()

And a run_udf.py file that contains my UDF function and another function (that multiplies a  single variable by 2):
from pyspark.sql.functions import pandas_udf, PandasUDFType

def multi_by_2(x):
    return 2 * x

def compute(df):

    @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP)
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=multi_by_2(v) - v.mean())

    df = df.groupby("id").apply(subtract_mean)

    return df

By running main.py I get the following error: "No module named 'run_udf'".
In this configuration, subtract_mean() does not seem to access the function multi_by_2(). I found 2 ways but don't know if it follows best practice standards:
Method 1: (move the function inside compute - not ideal as I will have the copy the function each time I use another pandas_udf() function - we loose the concept of 'reusable' function).
def compute(df):
    def multi_by_2(x):
        return 2 * x
    @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP)
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=multi_by_2(v) - v.mean())

    df = df.groupby("id").apply(subtract_mean)

    return df

Method 2: Pass the multiplying function as parameter of compute.
__main_.py
from pyspark.sql import SparkSession
from run_udf import compute
def multi_by_2(x):
    return 2 * x

def main():
    spark = SparkSession.builder.getOrCreate()
    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))
    df = compute(df, multi_by_2)
    df.show()
    spark.stop()

if __name__ == "__main__":
    main()

run_udf.py
    from pyspark.sql.functions import pandas_udf, PandasUDFType
def compute(df, multi_by_2):
    @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP)
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=multi_by_2(v) - v.mean())

    df = df.groupby("id").apply(subtract_mean)

    return df

The two solutions I found seem to be a bit hacky. Is there any better way to tackle this issue?

A: I know this reply comes a while after you've posted the question but I hope it can still be helpful!
What is the reason you want to wrap this in a nested function? Also, calling a function with a spark dataframe as the argument is not commonly done as far as I am aware, so maybe you could try something like the following for your main script:
from pyspark.sql import SparkSession
from run_udf import substract_mean_udf

def main():
    spark = SparkSession.builder.getOrCreate()
    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))
    df =df.groupby("id").apply(subtract_mean_udf)
    df.show()
    spark.stop()

if __name__ == "__main__":
    main()

And the following for the run_udf.py script:
from pyspark.sql.functions import pandas_udf, PandasUDFType

def multi_by_2(x):
    return 2 * x

@pandas_udf(df.schema, PandasUDFType.GROUPED_MAP)
def subtract_mean_udf(pdf):
    # pdf is a pandas.DataFrame
    return pdf.assign(v=multi_by_2(pdf.v) - pdf.v.mean())

Most of this information is taken from the a Databricks notebook on Pandas UDFs.
You could probably also get away with
return pdf.assign(v=pdf.v*2 - pdf.v.mean())

but I haven't tested that so I am not 100% sure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I fix this regex? String input = "2012 AL REG TEXT 300535(NS)";
String regex = "^((\\d{4})\\s+)?((\\S+)\\s+(.+?)\\s+)\\s+((\\S+)(\\s+\\(.*?\\)))$";

I want to capture 2012 in a group, "AL REG TEXT" in another group, and "300535(NS)" in another group.

A: The error is that you have an extra \\s+ right before the expected parantheses and, as @cmonkey points out, an extra \\s+ in the middle. Remove these and it works. Also, to only get the groups you mention above, add ?: to the ones you don't want to capture:
String input = "2012 AL REG TEXT 300535(NS)";
String regex = "^(?:(\\d{4})\\s+)?((?:\\S+)\\s+(?:.+?))\\s+((?:\\S+)(?:\\(.*?\\)))$";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
    for (int i = 1; i <= m.groupCount(); i++) {
        System.out.format("Group %d: '%s'%n", i, m.group(i));
    }
}

prints
Group 1: '2012'
Group 2: 'AL REG TEXT'
Group 3: '300535(NS)'

A: In the middle of your regex, there is the portion:
\\s+)\\s+

Which is looking for two required consecutive spaces. This does not exist, so the regex fails.

A: Try this: ^(\\d{4})?\\s+(\\D+)\\s+(\\d.*)$
Here's the code:
    String input = "2012 AL REG TEXT 300535(NS)";
    String regex = "^(\\d{4})?\\s+(\\D+)\\s+(\\d.*)$";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);
    if(m.matches()) {
        System.out.println("Group count: "+m.groupCount());
        for(int i=0; i<=m.groupCount(); i++) {
            System.out.println("Group "+i+": "+m.group(i));
        }
    }
    else System.out.println("No match");


text:
Q: Powershell use "-match" to compare to an array? I'm trying to check if something inside the Array matches $File.FullName, but as soon as I use an Array, it returns nothing anymore.
How can I solve this?
EDIT: I eventually want to use it inside an if statement, so just making another foreach is no option.
Example:
$Test = Get-ChildItem -Path "Some\Path" | Select-Object -Property FullName, Length, LastWriteTime
foreach($File in $Test)
{
    if($File.FullName -match $ArrayofStringsThings)
    {
        echo $File
    }

}

A: This will work, though it isn't a well designed function and there are many ways to create a smaller/simpler ad hoc method:
$Test = Get-ChildItem -Path * | Select-Object -Property FullName, Length, LastWriteTime
$Patterns = 'Get','Csv','Storage'
$Width = -1 * ((measure-object -maximum length).maximum + 1)
foreach($File in $Test) {
  ForEach ($Pattern in $Patterns) {
    If ($File.FullName -match $Pattern) {   # Check each pattern
      write-warning ("Match: {0,$Width} {1}" -f $Pattern, $File.FullName)
      $File
      break # already matched so no need to check this file further
    }
  }
}

This will work as well:
$Test     = Get-ChildItem -Path *
$Patterns = 'Get', 'CSV', 'Storage'
$Test | Where-Object { $_.FullName -Match ('(' + ($Patterns -join ')|(') + ')' ) }

Just ignoring the Select-Object properties and leaving the original objects intact.
(Properties can be selected after the filtering completes giving more flexibility.)
Or perhaps this is easier to read and modify:
$Test            = Get-ChildItem -Path *
$Patterns        = 'Get', 'CSV', 'Storage'
$CombinedPattern = '(' + ($Patterns -join ')|(' ) + ')'
$Test | Where-Object { $_.FullName -Match $CombinedPattern }

A: From the following page about_comparison_operators

The -match operators search only in strings. They cannot search in arrays of integers or other objects.

What you can use:

-contains :   Returns true when reference value contained in a collection
-notcontains : Returns true when reference value not contained in a collection
-in :  Returns true when test value contained in a collection
-notin :   Returns true when test value not contained in a collection

Let me explain how you could have known it was returning an array:
When you would use the following command:
$test | gm

It would present you the following output
 TypeName: Selected.System.IO.DirectoryInfo
If you then google that typename you end up at https://msdn.microsoft.com/en-us/library/f3e2f6e5(v=vs.110).aspx
When you then look at the page you'll find:

Return Value
Type: System.IO.DirectoryInfo[]
An array of type DirectoryInfo matching searchPattern.


text:
Q: Continue consuming subsequent records in reactor kafka after deserialization exception I am using reactor kafka and have a custom AvroDeserializer class for deserialization of messages.
Now I have a case where for certain payloads the deserialization class throws an exception.
My Kafka listener dies as soon as it tries to read such records.
I tried handling this exception using onErrorReturn and using combination of (doOnError and onErrorContinue), however, it helped log the exception, but failed to consume subsequent records.
public class AvroDeserializer<T extends SpecificRecordBase> implements Deserializer<T> {
   public T deserialize( String topic, byte[] data ) {
       try {
         //logic to deserialize
       }
       catch {
          // throw new SerializationException("error deserializing" );
       }
   }
}

At the listener end, I'm trying to handle like this ->
@EventListener(ApplicationStartedEvent.class)

public class listener() {
   KakfaReceiver<String, Object> receiver; // kafka listener
   receiver.receive()
   .delayUntil(do something)//logic to update the record to db
   .doOnError(handle error)//trying to handle the exceptions including desrialization exception - logging them to a system
   .onErrorContinue((throwable, o) -> log.info("continuing"))
   .doOnNext(r->r.receiverOffset().acknowledge())
   .subscribe()

}

One option is not to throw exception from the Deserializer class, but I want to log such exceptions in a separate system for analytics, and hence want handling of such records at the kafka listener end.
Any thoughts on how this can be achieved?

A: Looks like the suggestion in the comment about using
spring.cloud.stream.kafka.streams.binder.deserializationExceptionHandler=logAndContinue

will work in most cases. But I couldnt figure out of the way to make it work in Reactor Spring Kafka. For now, I went ahead with the approach of not throwing an exception from the deserializer and adding the logic to log it there itself,and that solves the issue of Kafka consumer not being able to consume subsequent records after that on poison record

A: I think your problem is that you do throw an exception and any exception is a terminal even in context of a reactive stream. Just don't throw an exception.
Wrap your T (that you return from deserialize()) in a class, that can indicate whether deserialization was a success or failure. If you don't care for exact error you can use Optional<T> where empty optional will indicate deserialization error. If you are using vavr library, you can grab Option<T> from there or Try<T> to store the actual deserialization on the Failure side.
For example, your deserializer would look like
public class AvroDeserializer<T extends SpecificRecordBase> implements Deserializer<T> {
   public Optional<T> deserialize( String topic, byte[] data ) {
       try {
         //logic to deserialize
         return Optional.of(result);
       }
       catch {
          return Optional.empty();
       }
   }
}

Now that you are no longer throwing, your flux stays alive and you can for example filter out empty Optional instances.
P.S.
If you don't want to use wrapper types, you can return null instead of throwing and filter out null values. I wound not recommend that though - easier to forget about that deserialize() behavior and get NullPointerException later.


text:
Q: KVM / Extender needed... with no lag I need to extend a PS/2 and Mouse, KB and VGA 220 feet (cat5 in place) to an audio editing console that is in a remote rack in a closet.
Audio from the unit is alredy extended. So thats not a problem.
My currect KVM system (avocent) has just enough lag to make audio editing painfull.
So the requrements are.

*

*must be over CAT5 (not IP)

*little or no lag (its used for audio editing so needs to be real time / instant repsonce)

*Ps/2 support (USB not needed) and VGA support

Any suggestions?

A: We've always used Raritan KVMs and we have a couple of their Cat5 extenders:
Cat5 Reach
I've never noticed any lag in anything I've done, but then I've never tested it w/ audio since I'm using it to get to our KVM in the server room from my office.
It's not cheap, though, it looks like it's $300 for each end.

A: I have one of these Belkin KVM extenders. It runs fine over CAT5 (not IP), I've never experienced any lag on it (however I don't have it on a long run of CAT5). It has both PS/2 and VGA.
There is a adjustment screw on the side that lets you tune the display (i.e. remove the shadow effect).
I'd certainly recommend it, however bear in mind that I never seen any other similar devices in use to be able to compare them.


text:
Q: Force HTTP protocol to HTTPS on response to AdRequest How and where can I change the HTTP protocol of the response I get for my (Publisher)Adview from HTTP to HTTPS?
This to enable my adview to show ads from third party networks which are now being blocked.
I have had contact with the Google Mobile Ads SDK support team and their answer was that adding an S to the HTTP protocol of the response of the ad request will make it possible to show the ads.
But I can't find where and how I can do this.
Below is the error I receive in the logcat:

10-23 19:56:15.813 18492-18492/com.koeck.verdienapp W/chromium:
  [WARNING:web_contents_impl.cc(2990)] https://pubads.g.doubleclick.net
  ran insecure content from
  http://ib.adnxs.com/ttj?id=4433225&size=300x250&referrer=com.koeck.android&cb=774743058&psa=false&position=above
  10-23 19:56:15.823 18492-18492/com.koeck.verdienapp W/chromium:
  [WARNING:web_contents_impl.cc(2990)] https://.. ran insecure content
  from http://.. 10-23 19:56:15.823 18492-18492/com.koeck.verdienapp
  W/Ads: JS: Mixed Content: The page at 'https://..' was loaded over
  HTTPS, but requested an insecure script

At this point I have come up with this code so far to change HTTP to HTTPS:
public void changeHTTP(URL url) throws IOException {
            if ("http".equals(url.getProtocol())) {
                String urlSource = "";

            try {
                urlSource = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace(); // This should not happen.
            }

            Log.d(TAG, "decoded: " + urlSource);

            String urlNew = urlSource.replace("http","https");
            }
    }

Thanks for taking the time to read my question.
Kind regards,
Rogier van den Brink

A: It's even easier than you think:
public URL changeHTTP(URL url) throws IOException {
     String strUrl = url.toString();
     if (strUrl.indexOf("http://", 0) == 0)
     {
         strUrl = strUrl.replace("http://", "https://");
         url = new URL(strUrl);
     }
     return url;
}


text:
Q: React / React Native: How to Map over array and show Data on Cards Im trying to .map() over my array and render cards to the dom. I can show everything in the second object on my card but i cant show source.name ("Engadget") on the card.
I guess because its an Object inside of an object?
So how do iterate over the 'source' object and how it on my cards?
Data Example
"articles": [
-{
  -"source": {
   "id": "engadget",
   "name": "Engadget"
 },

"author": "Igor Bonifacic",
"title": "Apple Wallet's hotel keycard support is now live, starting at Hyatt hotels",
"urlToImage": "https://s.yimg.com/os/creatr-uploaded-images/2021-12/5d0536d0-5855-11ec-bbe4-0bcb4305d433",

  }
]

Working card example
dataArray.map((newsStory)=> {
    const {  url, urlToImage, title} = newsStory

      return (
         <>
        <Card style={styles.card} onPress={()=> {Linking.openURL(url)}}>
            <Card.Cover source={{ uri: urlToImage }} />
//trying to show source in this 'Text'
            <Text style={styles.source}>{source?}</Text>
            <Title style={styles.cardTitle}>{title}</Title>
        </Card>

        </>

A: Since source is an object, use source.name
dataArray.map((newsStory)=> {
    const {  url, urlToImage, title} = newsStory

      return (
         <>
        <Card style={styles.card} onPress={()=> {Linking.openURL(url)}}>
            <Card.Cover source={{ uri: urlToImage }} />
//trying to show source in this 'Text'
            <Text style={styles.source}>{newsStory.source.name}</Text>
            <Title style={styles.cardTitle}>{title}</Title>
        </Card>

        </>


text:
Q: How to add a dropdown I get a nullpointerexception with this code. I'm trying to add a spinner / dropdown to the white area of my screen. The offending code is:
package dev.android.gamex;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    CatchGame cg;
    public TextView textView;
    public LinearLayout mainLayout;
    private Spinner spinner1, spinner2;

    // add items into spinner dynamically
    public void addItemsOnSpinner2() {

    }

    // start app
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);

        LinearLayout menuLayout = new LinearLayout(this);
        menuLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));

        textView = new TextView(this);
        textView.setVisibility(View.VISIBLE);
        String str = "Score: 0";
        textView.setText(str);
        menuLayout.addView(textView);

        Button button = new Button(this);
        button.setText("Pause");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePausePlay();
            }
        });
        menuLayout.addView(button);

//        addItemsOnSpinner2();

        spinner2 = (Spinner) findViewById(R.id.spinner2);
        List<String> list = new ArrayList<String>();
        list.add("list 1");
        list.add("list 2");
        list.add("list 3");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);

        menuLayout.addView(spinner2);

        mainLayout.addView(menuLayout);

        cg = new CatchGame(this, 5, "Jamie", onScoreListener);
        cg.setBackground(getResources().getDrawable(R.drawable.bg_land_mdpi));
        mainLayout.addView(cg);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getSupportActionBar().hide();
        setContentView(mainLayout);
    }

    private void togglePausePlay() {
        if (cg.paused) {
            // play
            //  getSupportActionBar().hide();
            Toast.makeText(MainActivity.this, "Play", Toast.LENGTH_SHORT).show();
        } else {
            // pause
            //    getSupportActionBar().show();
            Toast.makeText(MainActivity.this, "Pause", Toast.LENGTH_SHORT).show();
        }

        cg.paused = !cg.paused;
    }

    private OnScoreListener onScoreListener = new OnScoreListener() {
        @Override
        public void onScore(int score) {
            textView.setText("Score: " + score);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    // method called when top right menu is tapped
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        int difficulty = cg.NBRSTEPS;
        String name = cg.heroName;

        switch (item.getItemId()) {
            case R.id.item11:
                cg = new CatchGame(this, 3, name, onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item12:
                cg = new CatchGame(this, 5, name, onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item13:
                cg = new CatchGame(this, 7, name, onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item14:
                cg = new CatchGame(this, 9, name, onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item15:
                cg = new CatchGame(this, 11, name, onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item21:
                cg = new CatchGame(this, difficulty, "Jamie", onScoreListener);
                setContentView(cg);
                mainLayout.addView(cg);
                getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                setContentView(mainLayout);
                return true;
            case R.id.item22:
                cg = new CatchGame(this, difficulty, "Spaceship", onScoreListener);
                setContentView(cg);
                //mainLayout.addView(cg);
                //getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
                getSupportActionBar().hide();
                //setContentView(mainLayout);
                return true;
            default:
                cg.paused = true;
                return super.onOptionsItemSelected(item);
        }
    }

}

interface OnScoreListener {
    void onScore(int score);
}

class CatchGame extends View {
    int NBRSTEPS; // number of discrete positions in the x-dimension; must be uneven
    String heroName;
    int screenW;
    int screenH;
    int[] x; // x-coordinates for falling objects
    int[] y; // y-coordinates for falling objects
    int[] hero_positions; // x-coordinates for hero
    Random random = new Random();
    int ballW; // width of each falling object
    int ballH; // height of ditto
    float dY; //vertical speed
    Bitmap falling, hero, jamie2, jamieleft, jamieright;
    int heroXCoord;
    int heroYCoord;
    int xsteps;
    int score;
    int offset;
    boolean gameOver; // default value is false
    boolean toastDisplayed;
    boolean paused = false;

    OnScoreListener onScoreListener;

    // constructor, load images and get sizes
    public CatchGame(Context context, int difficulty, String name, OnScoreListener onScoreListener) {
        super(context);
        NBRSTEPS = difficulty;
        heroName = name;
        this.onScoreListener = onScoreListener;

        x = new int[NBRSTEPS];
        y = new int[NBRSTEPS];
        hero_positions = new int[NBRSTEPS];
        int resourceIdFalling = 0;
        int resourceIdHero = 0;
        if (heroName.equals("Jamie")) {
            resourceIdFalling = R.mipmap.falling_object2;
            resourceIdHero = R.drawable.left_side_hdpi;
            setBackground(getResources().getDrawable(R.mipmap.background));
        }
        if (heroName.equals("Spaceship")) {
            resourceIdFalling = R.mipmap.falling_object;
            resourceIdHero = R.mipmap.ufo;
            setBackground(getResources().getDrawable(R.mipmap.space));
        }
        falling = BitmapFactory.decodeResource(getResources(), resourceIdFalling); //load a falling image
        hero = BitmapFactory.decodeResource(getResources(), resourceIdHero); //load a hero image
        jamieleft = BitmapFactory.decodeResource(getResources(), R.drawable.left_side_hdpi); //load a hero image
        jamieright = BitmapFactory.decodeResource(getResources(), R.drawable.right_side_hdpi); //load a hero image

        ballW = falling.getWidth();
        ballH = falling.getHeight();
    }

    public CatchGame(Context context, int difficulty, String name, OnScoreListener onScoreListener, Drawable background) {
        this(context, difficulty, name, onScoreListener);
        this.setBackground(background);
    }

    // set coordinates, etc.
    void initialize() {
        if (!gameOver) { // run only once, when the game is first started
            int maxOffset = (NBRSTEPS - 1) / 2;
            for (int i = 0; i < x.length; i++) {
                int origin = (screenW / 2) + xsteps * (i - maxOffset);
                x[i] = origin - (ballW / 2);
                hero_positions[i] = origin - hero.getWidth();
            }
            int heroWidth = hero.getWidth();
            int heroHeight = hero.getHeight();

            hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true);
            hero = Bitmap.createScaledBitmap(hero, heroWidth * 2, heroHeight * 2, true);
            jamieleft = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth()* 2, jamieright.getWidth() * 2, true);
            jamieright = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth()* 2, jamieright.getWidth() * 2, true);

            heroYCoord = screenH - 2 * heroHeight; // bottom of screen

        }
        for (int i = 0; i < y.length; i++) {
            y[i] = -random.nextInt(1000); // place items randomly in vertical direction
        }

        offset = (NBRSTEPS - 1) / 2; // place hero at centre of the screen
        heroXCoord = hero_positions[offset];

        // initialize or reset global attributes
        dY = 2.0f;
        score = 0;
        gameOver = false;
        toastDisplayed = false;
    }

    // method called when the screen opens
    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        screenW = w;
        screenH = h;
        xsteps = w / NBRSTEPS;
        initialize();
    }

    // method called when the "game over" toast has finished displaying
    void restart(Canvas canvas) {

        toastDisplayed = true;
        initialize();
        draw(canvas);
    }

    // update the canvas in order to display the game action
    @Override
    public void onDraw(Canvas canvas) {
        if (toastDisplayed) {
            restart(canvas);
            return;
        }
        super.onDraw(canvas);

        int heroHeight = hero.getHeight();
        int heroWidth = hero.getWidth();
        int heroCentre = heroXCoord + heroWidth / 2;

        Context context = this.getContext();

        // compute locations of falling objects
        for (int i = 0; i < y.length; i++) {
            if (!paused) {
                y[i] += (int) dY;
            }
            // if falling object hits bottom of screen
            if (y[i] > (screenH - ballH) && !gameOver) {
                dY = 0;
                gameOver = true;
                paused = true;
                int duration = Toast.LENGTH_SHORT;

                final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
                toast.show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        toast.cancel();
                        toastDisplayed = true;
                    }
                }, 3000);
                //Vibrator v = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
                // Vibrate for 3000 milliseconds
                //v.vibrate(3000);

            }
            // if the hero catches a falling object
            if (x[i] < heroCentre && x[i] + ballW > heroCentre &&
                    y[i] > screenH - ballH - heroHeight) {

                y[i] = -random.nextInt(1000); // reset to new vertical position
                score += 1;
                onScoreListener.onScore(score);
            }

        }

        canvas.save(); //Save the position of the canvas.

        for (int i = 0; i < y.length; i++) {
            canvas.drawBitmap(falling, x[i], y[i], null); //Draw the falling on the canvas.
        }
        canvas.drawBitmap(hero, heroXCoord, heroYCoord, null); //Draw the hero on the canvas.

        canvas.restore();
        //Call the next frame.
        invalidate();
    }

    // event listener for when the user touches the screen
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (paused) {
            paused = false;
        }
        int action = MotionEventCompat.getActionMasked(event);
        if (action != MotionEvent.ACTION_DOWN || gameOver) { // non-touchdown event or gameover
            return true; // do nothing
        }
        int coordX = (int) event.getX();
        int xCentre = (screenW / 2) - (hero.getWidth() / 2);
        int maxOffset = hero_positions.length - 1; // can't move outside right edge of screen
        int minOffset = 0; // ditto left edge of screen

        if (coordX < xCentre && offset > minOffset) { // touch event left of the centre of screen
            offset--; // move hero to the left

            if(coordX < heroXCoord)// + heroWidth / 2)
                hero = Bitmap.createScaledBitmap(jamieleft, jamieleft.getWidth() , jamieleft.getHeight() , true);

        }
        if (coordX > xCentre && offset < maxOffset) { // touch event right of the centre of screen
            offset++; // move hero to the right

            if(coordX > heroXCoord)
                hero  = Bitmap.createScaledBitmap(jamieright, jamieright.getWidth() , jamieright.getHeight() , true);

        }
        heroXCoord = hero_positions[offset];

        return true;
    }
}

The trace:
 main
                  Process: dev.game.adventure, PID: 5294
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{dev.game.adventure/dev.android.gamex.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
                      at dev.android.gamex.MainActivity.onCreate(MainActivity.java:78)
                      at android.app.Activity.performCreate(Activity.java:6975)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

The repository is available online.
My XML is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >

    <Spinner android:id="@+id/Spinner01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

My layout is supposed to look like this. The dropdown is supposed to appear to the right of the pause button.

A: You should call findViewById after calling setContentView .
And remove other setContentView(mainLayout); in your code .
Try
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...
    setContentView(R.layout.activity_main);
    // you should call findViewById after calling setContentView
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    ...
}

Edit
You can try like this
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);

LinearLayout menuLayout = new LinearLayout(this);
menuLayout.setOrientation(LinearLayout.HORIZONTAL);

TextView textView = new TextView(this);
Button button = new Button(this);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

menuLayout.addView(textView);
menuLayout.addView(button);
menuLayout.addView(spinner2);

mainLayout.addView(menuLayout);

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/tv_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="score"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/btn_pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="pause"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Spinner>
</LinearLayout>

<your_package.CatchGame
    android:id="@+id/catch_game"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>

Add CatchGame as a class .
MainActivity
private CatchGame mCatchGame;
private TextView mTextView;
private Button mButton;
private Spinner mSpinner;

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

    mCatchGame = (CatchGame) findViewById(R.id.catch_game);
    mTextView = (TextView) findViewById(R.id.tv_score);
    mButton = (Button) findViewById(R.id.btn_pause);
    mSpinner = (Spinner) findViewById(R.id.spinner);

    // do something here you want
}


text:
Q: Por que except no salta cuando el if statemant es false en la fuccion update_age? Mi problema es con el try except. Estoy intentando que el except salte en el momento cuando introduzca otra cosa ca int. En mi codigo el except salta solo cuando self.estimated_insurance_cost() es accionada y da error por que no puedes multiplicar en mi ejemplo int con str.
Por favor explinqueme como resuelvo el problema.
Muchas gracias.
class Patient:
      def __init__(self, name, age, sex, bmi, num_of_children, smoker):
        self.name = name
        self.age = age
        self.sex = sex
        self.bmi = bmi
        self.num_of_children = num_of_children
        self.smoker = smoker

      # method used to calculate an estimation of the insurance cost

      def estimated_insurance_cost(self):
        estimated_cost = 250 * self.age - 128 * self.sex + 370 * self.bmi + 425 * self.num_of_children + 24000 * self.smoker - 12500
        print("{}'s estimated insurance costs is {} dollars.".format(self.name,estimated_cost))

    # method meant to update the age

      def update_age(self, new_age):
          if type(new_age) is 'int':
            self.age = new_age
            print("{} is now {} years old.".format(self.name, self.age))
            self.estimated_insurance_cost()

    patient1 = Patient("John Doe", 25, 1, 22.2, 0, 0)
    #patient1.estimated_insurance_cost()
    # Try to catch error
    try:
      patient1.update_age("age")
    except:
      print("Error! Please insert an integer")

Lo que sale :
John Doe is now age years old.
Error! Please insert an integer

A: Python no puede saber de la nada que el dato ingresado deberia de generar un error. Para lograr eso la forma correcta en tu función update_age sería:
  def update_age(self, new_age):
      # Notese que cambié por completo el condicional con el que evaluas el tipo de dato
      if isinstance(new_age, int):
          self.age = new_age
          print("{} is now {} years old.".format(self.name, self.age))
          self.estimated_insurance_cost()
      else:
          raise ValueError("La edad debería ser un entero")

La forma correcta de saber de que tipo es un valor especifico sería la función isinstance, que recibe como primer argumento un objeto y como segundo el tipo o tupla de tipos que debería ser.
Para decirle a python que debe de mandar una excepción se usa la declaración raise, que acepta como "argumento" el tipo de error y entre parentesis el mensaje a mostrar.
Para saber más sobre errores y excepciones, puedes leer la documentación oficial de Python


text:
Q: All files gone after running fsck. How can I recover my files? I installed Ubuntu server 10.04 LTS. It worked great for many months, until today I decided to run fsck on the system partition and although it warned me, I kept pressing yes and now it will only boot into grub prompt.
I read some article that recommended trying grub reinstall. But before performing grub reinstall, i decided to run fsck again from Ubuntu 10.04 LTS for desktop live CD. The fsck painfully passes, now my drive is recognized as ext4 system and I am able to mount it again. However, all i can see is just boot directory and lost&found. I tried to perform grub reinstalling by doing grub-install stuff, now my grub is still not loading right, my files are missing, and the weird thing is that the amount I found used by boot and lost n found is only 5gb and the amount used in he hdd is 8 gb.
So my files must be somewhere in the hdd.
Is there any simple way maybe a GUI tool or something that can recover my files? I only need to retrieve my database backup and everything else can go.

A: In general I'd suggest burning and booting a live CD such as Ubuntu or SystemRescueCD and using extundelete to recover any deleted files.

A: Foremost may be able to find the files you care about. I used it to help a friend extract files from a drive that had physically failed with some unrecoverable sectors.

A: It is time to restore from backup.  Failing that, it sounds like your files are in /lost+found so you will need to look through there and try to identify them ( their original names have been lost ).

A: I recently had a coworker recover data using 'scalpel'.  You can see some info on it and others here: https://help.ubuntu.com/community/DataRecovery .  This is the Ubuntu community documentation for Data Recovery.
Currently, it also covers

*

*Ubuntu-rescue-remix

*Gnu parted

*testdisk

*Gnu ddrescue

*foremost

*magic rescue

*photorec

*ntfsprogs

*autopsy

*sleuthkit

and a few others.


text:
Q: How to create nested schema? Currently the Schema definition is not documented at all, the only resources i could find are these:
http://support.apiary.io/knowledgebase/articles/147279-json-schema-validation
https://github.com/apiaryio/api-blueprint/issues/112
but none of those examples discuss how to create nested schema.
I would like to validate this response:
{
    date: (datetime),
    url: (url),
    changes: [
        {
            date: (datetime),
            url: (url)
        },
        ...
    ],
    items: [
        {
            name: (string),
            url: (url)
        },
        ...
    ]
}

based on my current knowledge, i've started to create schema what looks like this
{
    "type": "object",
    "required": true,
    "properties": {
        "date": {
            "type": "datetime",
            "required": true
        },
        "url": {
            "type": "string",
            "required": true
        },
        "changes": {
            "type": "array",
            "required": true
        },
        "items": {
            "type": "array",
            "required": true
        }
    }
}

but how to create schema for nested item and change?
what types can i use?
how to validate datetime? expected value is YYYY-MM-DD HH:MM:SS

A: so far i ended up doing this. still i have to test it once my API end point will be up and working
{
    "type": "object",
    "required": true,
    "properties": {
        "date": {
            "type": "string",
            "format": "date-time",
            "required": true
        },
        "url": {
            "type": "string",
            "format": "url",
            "required": true
        },
        "changes": {
            "type": "array",
            "required": true,
            "items": {
                "type": "object",
                "required": true,
                "properties": {
                    "date": {
                        "type": "string",
                        "format": "date-time",
                        "required": true
                    },
                    "url": {
                        "type": "string",
                        "format": "url",
                        "required": true
                    }
                }
            }
        },
        "items": {
            "type": "array",
            "required": true,
            "items": {
                "type": "object",
                "required": true,
                "properties": {
                    "name": {
                        "type": "string",
                        "required": true
                    },
                    "url": {
                        "type": "string",
                        "format": "url",
                        "required": true
                    }
                }
            }
        }
    }
}

A: The test response is the following JSON snippet based on your example. The arrays include two objects so modifications you'd like to test are easier.
{
  "date": "2015-02-05T00:00:00.000Z",
  "url": "mysite.com",
  "changes": [
    {
      "date": "2015-03-05T00:00:00.000Z",
      "url": "mysite.com/edit/1"
    },
    {
      "date": "2015-03-04T00:00:00.000Z",
      "url": "mysite.com/edit/4"
    }
  ],
  "items": [
    {
      "name": "Item One",
      "url": "mysite.com/items/1"
    },
    {
      "name": "Item Two",
      "url": "mysite.com/items/2"
    }
  ]
}

The following schema will validate the above JSON using the draft-04 specification.
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Nested Example",
  "type": "object",
  "properties": {
    "date": {
      "type": "string",
      "format": "date-time"
    },
    "url": {
      "type": "string",
      "format": "uri"
    },
    "changes": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "date": {
            "type": "string",
            "format": "date-time"
          },
          "url": {
            "type": "string",
            "format": "uri"
          }
        },
        "required": ["date", "url"]
      }
    },
    "items": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "url": {
            "type": "string",
            "format": "uri"
          }
        },
        "required": ["name", "url"]
      }
    }
  },
  "required": ["date", "url", "changes", "items"]
}

The following types are available:

*

*array

*boolean

*integer

*number

*null

*object

*string

Primitive Types

Validation

I haven't had time to research the tools and workflow to do this locally so I've been using this for validation.


text:
Q: How do I sort data in Firebase? so I try to sort data from with most likes to the least. How do I do that if don't have an object name? because currently I only have the ID of the object?
here's my Firebase json:
["-KfSODzRPjy46ayCFRBH": {
      "_createdAt" = 1489773065234;
      "_updatedAt" = 1489773065234;
      content =     (
                     "<null>",
                     Tittle,
                     "why not there is the nnnd ksksks lalalalalkdkdkdkdk kadsjfakl;",
                     whhhhhhalalallala
                    );
      imageTitle = 1489773064177;
      like = 2;
      title = "Third Post";
},

["-KfSODzRPjy46ayCFRBH": {
      "_createdAt" = 1489773065234;
      "_updatedAt" = 1489773065234;
      content =     (
                     "<null>",
                     Tittle,
                     "why not there is the nnnd ksksks lalalalalkdkdkdkdk kadsjfakl;",
                     whhhhhhalalallala
                    );
      imageTitle = 1489773064177;
      like = 3;
      title = "Third Post";
},

this is how I read:
        let handleref = databaseRef.child("v1/postmodel").observe(.value, with: { (snapshot) in
        let postDict = snapshot.value as! [String : AnyObject]
        print(postDict)
    })


text:
Q: Does it make any sense to use the LFENCE instruction on x86/x86_64 processors? Often in internet I find that LFENCE makes no sense in processors x86, ie it does nothing , so instead MFENCE we can absolutely painless to use SFENCE, because MFENCE = SFENCE + LFENCE = SFENCE + NOP = SFENCE.
But if LFENCE does not make sense, then why we have four approaches to make Sequential Consistency in x86/x86_64:

*

*LOAD (without fence) and STORE + MFENCE

*LOAD (without fence) and LOCK XCHG

*MFENCE + LOAD and STORE (without fence)

*LOCK XADD ( 0 ) and STORE (without fence)

Taken from here: http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
As well as performances from Herb Sutter on page 34 at the bottom: https://skydrive.live.com/view.aspx?resid=4E86B0CF20EF15AD!24884&app=WordPdf&wdo=2&authkey=!AMtj_EflYn2507c
If LFENCE did not do anything, then the approach (3) would have the following meanings: SFENCE + LOAD and STORE (without fence), but there is no point in doing SFENCE before LOAD. Ie if LFENCE does nothing , the approach (3) does not make sense.
Does it make any sense instruction LFENCE in processors x86/x86_64?
ANSWER:
1. LFENCE required in cases which described in the accepted answer, below.
2. The approach (3) should be viewed not independently, but in combination with the previous commands. For example, approach (3):
MFENCE
MOV reg, [addr1]  // LOAD-1
MOV [addr2], reg  //STORE-1

MFENCE
MOV reg, [addr1]  // LOAD-2
MOV [addr2], reg  //STORE-2

We can rewrite the code of approach (3) as follows:
SFENCE
MOV reg, [addr1]  // LOAD-1
MOV [addr2], reg  //STORE-1

SFENCE
MOV reg, [addr1]  // LOAD-2
MOV [addr2], reg  //STORE-2

And here SFENCE makes sense to prevent reordering  STORE-1 and LOAD-2. For this after STORE-1 command SFENCE flushes Store-Buffer.

A: Consider the following scenario - this is the critical case where speculative load execution can theoretically harm sequential consistency
initially [x]=[y]=0
CPU0:                              CPU1:
store [x]<--1                      store [y]<--1
load  r1<--[y]                     load r2<--[x]

Since x86 allows loads to be reordered with earlier stores to different addresses, both loads may return 0's. Adding an lfence alone after each store wouldn't prevent that, since they only prevent reordering within the same context, but since stores are dispatched after retirement you can have both lfences and both loads commit before the stores are performed and observed.
An mfence on the other hand would force the stores to perform, and only then allow the loads to be executed, so you'll see the updated data on at least one context.
As for sfences - as pointed out in the comment, in theory it's not strong enough to prevent the load from reordering above it, so it might still read stale data. While this is true as far as the memory official ordering rules apply, I believe that current implementation of x86 uarch makes it slightly stronger (while not committing to do so in the future, I guess). According to this description:

Because of the strong x86 ordering model, the load buffer is snooped
  by coherency traffic. A remote store must invalidate all other copies
  of a cache line. If a cache line is read by a load, and then
  invalidated by a remote store, the load must be cancelled, since it
  potentially read invalid data. The x86 memory model does not require
  snooping the store buffer.

Therefore, any load not yet committed in the machine should be snoopable by stores from other cores, thereby making the effective observation time of the load at the commit point, and not the execution point (which is indeed out of order and may have been performed much earlier). Commit is done in order, and therefore the load should be observed after previous instructions - making lfences pretty much useless as I said above in the comments, since the consistency can be maintained the same way without them.
This is mostly speculation, trying to explain the common conception that lfences are meaningless in x86 - I'm not entirely sure where it originated and if there are other considerations at hand - would be happy for any expert to approve / challenge this theory.
All the above applies only for WB mem types of course

A: Bottom line (TL;DR): LFENCE alone indeed seems useless for memory ordering, however it does not make SFENCE a substitute for MFENCE. The "arithmetic" logic in the question is not applicable.

Here is an excerpt from Intel's Software Developers Manual, volume 3, section 8.2.2 (the edition 325384-052US of September 2014), the same that I used in another answer

*

*Reads are not reordered with other reads.

*Writes are not reordered with older reads.

*Writes to memory are not reordered with other writes, with the following exceptions:

*

*writes executed with the CLFLUSH instruction;

*streaming stores (writes) executed with the non-temporal move instructions (MOVNTI, MOVNTQ, MOVNTDQ, MOVNTPS, and MOVNTPD); and

*string operations (see Section 8.2.4.1).

*Reads may be reordered with older writes to different locations but not with older writes to the same location.

*Reads or writes cannot be reordered with I/O instructions, locked instructions, or serializing instructions.

*Reads cannot pass earlier LFENCE and MFENCE instructions.

*Writes cannot pass earlier LFENCE, SFENCE, and MFENCE instructions.

*LFENCE instructions cannot pass earlier reads.

*SFENCE instructions cannot pass earlier writes.

*MFENCE instructions cannot pass earlier reads or writes.

From here, it follows that:

*

*MFENCE is a full memory fence for all operations on all memory types, whether non-temporal or not.

*SFENCE only prevents reordering of writes (in other terminology, it's a StoreStore barrier), and is only useful together with non-temporal stores and other instructions listed as exceptions.

*LFENCE prevents reordering of reads with subsequent reads and writes (i.e. it combines LoadLoad and LoadStore barriers). However, the first two bullets say that LoadLoad and LoadStore barriers are always in place, no exceptions. Therefore LFENCE alone is useless for memory ordering.

To support the last claim, I looked at all places where LFENCE is mentioned in all 3 volumes of Intel's manual, and found none which would say that LFENCE is required for memory consistency. Even MOVNTDQA - the only non-temporal load instruction so far - mentions MFENCE but not LFENCE.

Update: see answers on Why is (or isn't?) SFENCE + LFENCE equivalent to MFENCE? for correct answers to the guesswork below
Whether MFENCE is equivalent to a "sum" of other two fences or not is a tricky question. At glance, among the three fence instructions only MFENCE provides StoreLoad barrier, i.e. prevents reordering of reads with earlier writes. However the correct answer requires to know more than the above rules; namely, it's important that all fence instructions are ordered with respect to each other. This makes the SFENCE LFENCE sequence more powerful than a mere union of individual effects: this sequence also prevents StoreLoad reordering (because loads cannot pass LFENCE, which cannot pass SFENCE, which cannot pass stores), and thus constitutes a full memory fence (but also see the note (*) below). Note however that order matters here, and the LFENCE SFENCE sequence does not have the same synergy effect.
However, while one can say that MFENCE ~ SFENCE LFENCE and LFENCE ~ NOP, that does not mean MFENCE ~ SFENCE. I deliberately use equivalence (~) and not equality (=) to stress that arithmetic rules do not apply here. The mutual effect of SFENCE followed by LFENCE makes the difference; even though loads are not reordered with each other, LFENCE is required to prevent reordering of loads with SFENCE.
(*) It still might be correct to say that MFENCE is stronger than the combination of the other two fences. In particular, a note to CLFLUSH instruction in the volume 2 of Intel's manual says that "CLFLUSH is only ordered by the MFENCE instruction. It is not guaranteed to be ordered by any other fencing or serializing instructions or by another CLFLUSH instruction."
(Update, clflush is now defined as strongly ordered (like a normal store, so you only need mfence if you want to block later loads), but clflushopt is weakly ordered, but can be fenced by sfence.)


text:
Q: Profile doesn't include certificate Using Xcode 9.1, after building an iOS app, I try to archive it.
But I get the following error message:

Provisioning profile "MyAppProfile" doesn't include signing
  certificate "iPhone Developer: My Name (X1YZ2AB3CD)".

What is the simplest way to solve this?

A: Open key chain in your mac and check your  development certificate...I think  your certificate is expired using which you have created your Provisioning profile..thats why it is showing "MyAppProfile" doesn't include signing certificate.
1.To solve this issue go to your developer account and download  the latest development certificate and add it to keychain and remove all expired certificates from keychain.
                                Or

2.This issue also comes when you have multiple developer accounts in your keychain and the expired developer certificate name is same as that of active developer certificate. After removing the expired certificates, you must restart Xcode to let it reload the remaining certificates.

A: Try enabling automatic signing. It will take care these things mostly.
The reason for this error is you may have chosen a developer certificate(which the provisioning profile doesn't intended to use with) for distributing/release build.

A: I have just encountered the same problem. What fixed it for me is to go to the xcodeproj file>Select the correct build target>Build settings>Code signing identity>select the correct identity for the build configuration (If you didn't change it in the edit scheme screen, it would be "Release" for archiving).


text:
Q: React Encountered two children with the same key I am making a test news app with infinite scroll react but when I scroll for more news I got the same news that I have seen above and get the error in console like:

react-dom.development.js:67 Warning: Encountered two children with the
same key,
https://www.nytimes.com/2022/04/01/movies/oscars-will-smith-slap.html.
Keys should be unique so that components maintain their identity
across updates. Non-unique keys may cause children to be duplicated
and/or omitted — the behavior is unsupported and could change in a
future version.
at div
at div
at div
at div
at InfiniteScroll (http://localhost:3000/static/js/bundle.js:35314:24)
at New (http://localhost:3000/static/js/bundle.js:590:5)
at Routes (http://localhost:3000/static/js/bundle.js:37042:5)
at Router (http://localhost:3000/static/js/bundle.js:36975:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:36451:5)
at div
at App (http://localhost:3000/static/js/bundle.js:36:5)

The place where I am using the keys is app
import NewsIItem from './NewsIItem'
import InfiniteScroll from 'react-infinite-scroll-component';
import ScrollLoader from './ScrollLoader';
export class New extends Component {

  static defaultProps = {
    category: "general"
  }
  // static propTypes = {
  //   category : PropTypes.string
  // }
  constructor() {
    super();
    this.state = {
      articles: [],
      loading: false,
      page: 1,
      totalResults: 0

    }
  }
  async componentDidMount() {
    // console.log("Inside the cdm");
    let myUrl = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&apiKey={private}&page=1&pageSize=${this.props.pageSize}`
    let data = await fetch(myUrl)
    let parsedData = await data.json()
    console.log(parsedData);
    this.setState({ articles: parsedData.articles, totalResults: parsedData.totalResults })
  }

  fetchData = async () => {
    this.setState({
      page: this.state.page + 1
    })
    let myUrl = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&api= {private}&page=1&pageSize=${this.props.pageSize}`
    this.setState({ loading: true })
    let data = await fetch(myUrl)
    let parsedData = await data.json()
    console.log(parsedData);
    this.setState({ articles: this.state.articles.concat(parsedData.articles), totalResults: parsedData.totalResults, loading: false })
  }
  render() {
    return (
      <>

Newsers Most updated ~ Headlines

        <InfiniteScroll
          dataLength={this.state.articles.length} //This is important field to render the next data
          next={this.fetchData}
          hasMore={this.state.articles.length !== this.state.totalResults}
          loader={<ScrollLoader />}
        >

              {this.state.articles.map((element) => {
                return

                  <NewsIItem title={element.title} description={element.description} imageUrl={!element.urlToImage ? "https://i.pinimg.com/originals/d1/a6/2a/d1a62a6d8969170025f279115470e34b.jpg" : element.urlToImage} newsId={element.url} />

              })}

        </InfiniteScroll>

      </>

    )
  }
}

export default New

A: Just update this line of code:
{this.state.articles.map((element) => return

To this
{this.state.articles.map((element,index)=> {
  return

A: Yo have this line twice:
<Route exact path="/sports" element={<New key= "sports" pageSize={this.pageSize} category="sports" />} />

Remove one or change the key values.


text:
Q: How to configure mod_evasive to show HTTP status 429 instead of 403? Some search engine spiders like Bingbot crawl too rapidly and does not seem to obey robots.txt crawl-delay directive. This triggers the DOS defence mechanism in mod_evasive to generate HTTP 403 forbidden errors. But showing 403 errors to bots for perfectly valid pages is not ideal and may affect page rank. Is there a way to configure mod_evasive to show HTTP status 429 instead of 403?

429 Too Many Requests
The 429 status code indicates that the user has sent too many requests in a given amount of time ("rate limiting").
The response representations SHOULD include details explaining the
  condition, and MAY include a Retry-After header indicating how long to wait before making a new request.

A: Basically you just change the HTTP_FORBIDDEN to HTTP_TOO_MANY_REQUESTS in mod_evasive20.c and compile again.

A: I forked mod_evasive and made the response status configurable (along with some other features), check it out: https://github.com/jvdmr/mod_evasive
To configure this, install the new version and add DOSHTTPStatus 429 to your config (either globally or in the virtualhost you want to protect).


text:
Q: разбить и соединить Есть несколько строк их нужно разбить проверить и соединить
Пример
Характеристики|Регулирование мощности, до|100.0(%)
Характеристики|Тип котла|Пиролизный
Характеристики|Вид топлива|Твердое

Проблема в том что из нескольких таких строк нужно соединить в одну
Пример
Характеристики|Регулирование мощности, до|100.0(%):300 %:600%
Характеристики|Тип котла|Пиролизный:Буржуйский:Обычный
Характеристики|Вид топлива|Твердое:Мягкое:Твердое

Что и как
Характеристики| - всегда одинаково и присутствует в каждой строке
Регулирование мощности, до - Название характеристики называются одинаково но могут находится то на 5 строке, а то и на 2
100.0(%) - значение строки всегда разные и нужно собрать и разделить :
Каждый блок строк берем из разных массивов
    $one_post = $_POST['one'];
    $two_post = $_POST['two'];
и так до 10 массивов

Я пытаюсь реализовать так все разбиваю Название характеристики перевожу в ключ потом сравниваю ключи и собираю все значения к ключу и получаю один общий блок.

A: // Парсим один массив строк
function parseStrings(&$data, $strings) {
  // Пробегаем по всем строкам
  foreach ($strings as $str) {
    // Разбиваем строку по разделителю
    $row = explode('|', $str);
    // Первую часть отбрасываем, вторая будет ключом подмассива
    if (!isset($data[$row[1]]))  // если такого подмассива нет - создаем
      $data[$row[1]] = [];
    // добавляем значение в нужный массив характеристик
    $data[$row[1]][] = $row[2];
  }
}

$strings1 = [
  "Характеристики|Регулирование мощности, до|100.0(%)",
  "Характеристики|Тип котла|Пиролизный"
  "Характеристики|Вид топлива|Твердое"
];

$strings2 = [
  "Характеристики|Регулирование мощности, до|300.0(%)",
  "Характеристики|Тип котла|Обычный"
  "Характеристики|Вид топлива|Мягкое"
];

$data = [];
// Парсим каждый из массивов и собираем все в $data
parseStrings($data, $strings1);
parseStrings($data, $strings2);

$res = [];  // конечный массив строк
// цикл по всем характеристикам.
// $name - название, $vals - массив всех значений
foreach($data as $name => $vals) {
  // Формируем новую строку
  $res[] = 'Характеристики|' . $name . '|' . implode(':', $vals);
}


text:
Q: mousePressed() on a button to change gameStates I am trying to change the gameStates with a button pressed, this doesn't seem to be working. The error appears to be that, "startButton.mousePressed is not a function".
function draw(){
    if (gameState === "start"){
        startButton.mousePressed(() => { stateChange() });
    }
}

function stateChange() {
  gameState = "playing";
}

I am also familiar with making buttons with html but the use of mousePressed() doesn't seem to be working.

A: If I understand it correctly startButton is an HTML element and you want to trigger stateChange function every time startButton is clicked. There are two DOM events which can be used.
onmousedown:
This will be triggered when any of the mouse button is clicked(left, right, center)
onclick:
This will be triggered only on the left click.
you can find usage info for both in the links provided.


text:
Q: A functional equation in a TST exam Find all functions $f:\Bbb {R} \rightarrow \Bbb {R} $ such that:
   $$f(f(xy-x))+f(x+y)=yf(x)+f(y)$$
Source: 2018 Hong Kong TST 2 problem 3

I recently proved that $f(x+1)=f(x)+f(1).$

A: To recap your result: setting $x=y=0$ shows us that
\begin{align*}
f(f(0))+f(0)&=0\cdot f(0)+f(0) \\
f(f(0))+f(0)&=f(0) \\
f(f(0))&=0.
\end{align*}
Now from the original equation we set $y=1$ to obtain
\begin{align*}
f(f(0))+f(x+1)&=f(x)+f(1) \\
f(x+1)&=f(x)+f(1).
\end{align*}
Let us set $x=0$ in this equation to obtain
\begin{align*}
f(1)&=f(0)+f(1) \\
0&=f(0).
\end{align*}
So the function must go through the origin.
$f(x+1)=f(x)+f(1)$ is a straight-forward recurrence relation. If we assume $f(x)=b\cdot a^x$ and plug in, we obtain
\begin{align*}
b\cdot a^{x+1}&=b\cdot a^{x}+b\cdot a \\
a^{x+1}&=a^x+a \\
a^{x+1}-a^x-a&=0.
\end{align*}
This must hold for $x=1,$ which forces $a^2-a-a=0,$ or $a^2-2a=0,$ the solutions of which are $a=0,$ not very exciting, or $a=2,$ which is much more interesting. Indeed, we can handle the $a=0$ case by simply letting $b=0$. So we will say that the solutions are $$f(x)=b\cdot 2^x.$$
We can say something more, though: we proved that the function must go through the origin. In looking at this formula, it is evident that the trivial solution is the only solution of this type, since $2^x\not=0.$ Hence, one answer is that
$$\boxed{f(x)=0\quad\forall\,x\in\mathbb{R}.} $$
Another special answer (thanks to mfl in the comments!) we can obtain by inspection: $\boxed{f(x)=x},$ the identity function. To see this, we compute:
\begin{align*}
f(f(xy-x))+f(x+y)&=yf(x)+f(y) \\
f(xy-x)+x+y&=yx+y \\
xy-x+x+y&=yx+y \\
xy+y&=xy+y,
\end{align*}
which is true.

A: If we put $x=0$ then we get $$f(f(0)) = yf(0)\quad \forall y \implies f(0)=0$$
If we put $y= 0$ we get $$ f(f(-x)) =-f(x)\implies \boxed{f(f(x))= -f(-x)}$$
If we put $y=1$ and mark $a=f(1)$ we get $$ f(x+1) = f(x)+a \implies \boxed{f(x+2)= f(x)+2a}$$
If we put $y=2$ and mark $b=f(2)$ we get $$f(f(x)) + f(x+2) =2f(x)+b$$
Plugging in last formula both boxed equations we get:
$$ -f(-x)+f(x)+2a = 2f(x)+b \quad \overset{x=0}{\implies} \quad 2a=b \quad \implies \quad f(-x)=-f(x)$$
So from the first boxed equation we have now $$f(f(x)) = f(x)$$ and the starting equation is now: $$f(xy-x)+f(x+y)= yf(x)+f(y)$$
Plug in to this equation $x=-1$:
$$ f(-y+1)+f(-1+y) = yf(-1)+f(y)$$
and if we take into consideration that $f$ is odd we have $\boxed{f(y)= ay}$ for all $y$ and some $a$ which we can get if we plug this function in starting equation.


text:
Q: $\int_{-\infty}^\infty \frac{e^{ax}}{1+e^x}dx$ with residue calculus I'm trying to compute $\displaystyle \int_{-\infty}^\infty \frac{e^{ax}}{1+e^x}dx$, $(0<a<1)$
Let $f$ denote the integrand.
I'm using the rectangular contour given by the following curves:
$c_1: z(t) = R+it, t \in [0, 2\pi]$
$c_2: z(t) = -t+2\pi i, t \in [-R, R]$
$c_3: z(t) = -R + i (2\pi - t), t \in [0, 2\pi]$
$c_4: z(t) = t, t \in [-R, R]$
There is one singularity within the contour, at $z = \pi i$.
Expanding out the denominator as a power series shows that it's a simple pole, and allows us to evaluate the residue as
$\displaystyle \lim_{z \rightarrow \pi i} f(z)(z-\pi i) = - e^{a \pi i}$
This is computed by expanding $1+e^z$ as a Taylor series around $\pi i$. The first coefficient will be 0, and the second will be $-1$. The rest will have orders of $(z - \pi i)$ greater than 1, and will thus vanish when we take the limit.
So the integral over the entire contour is $- 2\pi i e^{a \pi i}$
An easy enough estimate on the $c_1$ shows that the integral vanishes as $R \rightarrow \infty$.
With a variable change, c_3 is the same as c_1 and also vanishes.
$c_4$ becomes the integral we want when we take a limit.
$c_2$ becomes $c_4$ with a constant:
\begin{align*} \int_{c_2} f(z)dz &= \int_{-R}^{R} \frac{e^{-at}e^{a 2\pi i}}{1+e^{-t}e^{2\pi i}}dt
\\ &= e^{a 2 \pi i}\int_{-R}^{R} \frac{e^{-at}}{1+e^{-t}}dt
\\ &=e^{a 2 \pi i}\int_{R}^{-R} - \frac{e^{au}}{1+e^{u}}du \ \ \ (u = -t, du = -dt)
\\ &= e^{a 2 \pi i}\int_{-R}^{R} \frac{e^{au}}{1+e^{u}}du
\\ &= e^{a 2 \pi i} I(R)
\end{align*}
Where $I(R)$ is the line integral over $c_4$.
Putting it all together and taking the limit gives us
$\displaystyle \lim_{R \rightarrow \infty} I(R) = \frac{- 2\pi i e^{a \pi i}}{(1 + e^{a 2 \pi i}) }$
But this can't be the value of the integral, because it's a real-valued function integrated over $R$. I can't figure out where I'm going wrong. Note that I've avoided posting all the details of my solution since this is from a current problem set for a class on complex analysis.

A: The residue can also be calculated without the use of a taylor series expansion
$$\lim_{z \to \pi i} \frac{(z-\pi i)\exp(az)}{1+\exp(z)} = \lim_{z \to \pi i} \frac{\exp(az)+ (z-\pi i) ~ a ~ \exp(az)}{\exp(z)} = - \exp(a ~ \pi~ i)$$
Since we can use L'Hôpital's rule.

A: I think you may just have a simple sign error.  Using the same contour you describe, I get that
$$\int_{-R}^R dx \frac{e^{a x}}{1+e^x} + i \int_0^{2 \pi} dy \frac{e^{a (R + i y)}}{1+e^{R+i y}} - e^{i a 2 \pi} \int_{-R}^R dx \frac{e^{a x}}{1+e^x} - i \int_0^{2 \pi} dy \frac{e^{a (-R + i y)}}{1+e^{-R+i y}} = -i 2 \pi e^{i a \pi}$$
As $R \to \infty$, the second integral (because $a \lt 1$) and the fourth integral (because $a \gt 0$) vanish.  Thus we have
$$\int_{-\infty}^{\infty} dx \frac{e^{a x}}{1+e^x} = - i 2 \pi \frac{e^{i a \pi}}{1-e^{i 2 a \pi}} = \frac{\pi}{\sin{\pi a}}$$

A: Would it help you to make a change of variable $$x = \operatorname{Log}[y - 1]$$ ?
The integrand just becomes
$$\frac{(y - 1)^{a-1}}{ y}$$
and the integral has to be taken from $1$ to infinity.


text:
Q: Simple regex negation I'm having trouble with a regex, so I figured I'd ask here. Basically, I need it to match URI's for a collection, except for a certain one (/new).
i.e.:
/properties     # match
/properties/25  # match
/properties/new # rejected

I've tried variations on the following, to no avail:
/properties(^(/new)).*

I think my trouble is with the negation, but I can't quite grok what I'm meant to be doing.. An explanation with the solution would be much appreciated!

A: ^ negates inside a character class (a group of characters in any order surrounded by [ ]. You need to use ?!. You also shouldn't use .*. It doesn't add anything. If you want to match anything you just don't put anything :).  Also you don't need to capture the match. Depending on how you're setting it up you may also need to escape the slashes ( / )
Try this:
\/properties(?!\/new)

A: You could simply use an additional RewriteCond:
RewriteCond $2 !=new
RewriteRule ^/properties(/(.*))?$ …

This will match /properties, /properties/, and /properties/… followed by anything else but not /properties/new.

A: How about this one:
/properties(?!/new)(?:/.*){0,1}

the: `(?!/new) is a negative forward lookup, and essentially says: make sure this cannot be matched
the following: (?:/.+){0,1} allows for the matching of additional paths (ie. /25) and is a non-capturing group that says match / followed by zero or more characters, and match it zero to one times as a group.  The {0,1} allows it to match even if there is no /25.


text:
Q: TextInputLayout with EditText is decreasing when user touch My TextInputLayout with EditText is decreasing when i touch this place.
I have 2 questions, what i should fix if i want this same size EditText, and what i should add for always keyboard on screen.

xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="pl.xd.hello.WeatherActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="6"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Podaj miejscowość" />
            </android.support.design.widget.TextInputLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"
            android:gravity="center"
            android:orientation="horizontal">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/floatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:clickable="true"
                app:backgroundTint="@android:color/holo_red_dark"
                app:fabSize="mini"
                app:srcCompat="@drawable/ic_check_circle_black_24dp" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

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

A: for your first question make your EditText like below to fix it with its parent size
<android.support.design.widget.TextInputLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
<EditText
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="Podaj miejscowość" />
</android.support.design.widget.TextInputLayout>

For the second question you should add android:windowSoftInputMode="stateAlwaysVisible" to your activity in the AndroidManifest.xml file like below:
<activity android:name=".MainActivity"
 android:label="@string/app_name"
 android:windowSoftInputMode="stateAlwaysVisible" />

this would open the softkeyboard for your whole app,
you can take a look at this post for more info.
but if you want to open the keyboard only for this activity or fragment you can add a method to open keyboard manually like below :
public static void showKeyboard(EditText editText) {

    if (editText != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
}


text:
Q: Iterating over and reducing values of a Java map via Stream API Java 8 here. I have an array of Strings:
String[] animals = getsomehow(); // "dogs", "cats", "sheep", etc.

Then I have a map where the keys are Strings (specifically, the same literal values as some of the animals in the array above), and the values are a count (representing the number of those animals):
Map<String,Integer> animalCounts = new HashMap<String,Integer>();
animalCounts.put("sheep", 4);
animalCounts.put("dogs", 2);
animalCounts.put("cats", 0);
animalCounts.put("porcupines", null);
animalCounts.put("dolphins", 43);

I am trying to figure out how to use the Stream API to iterate over my animals array, and come up with a total number of animals. For instance, if my animals array had "sheep" and "dolphins" in it, then the total number of animals would be 4 + 43 = 47.
My best attempt so far:
int totalAnimals = Arrays.stream(animals)
    .reduce(
        0,
        (subtotal, animal) -> subtotal + animalCounts.get(animal));

However this yields a compiler error for the identity value of 0:

"Required type: String"

Can anyone spot where I'm going awry?

A:
Can anyone spot where I'm going awry?

You're using the 2-argument version of reduce:
T reduce(T identity,
         BinaryOperator<T> accumulator)

As you can see, the identity value and the output has to be of the same type as the input, so it must be String.
Solution would be to use the 3-argument version of reduce:
<U> U reduce(U identity,
             BiFunction<U,? super T,U> accumulator,
             BinaryOperator<U> combiner)

As an alternative, you can do it like this:
int totalAnimals = Arrays.stream(animals)
        .map(animalCounts::get)
        .filter(Objects::nonNull)
        .mapToInt(Integer::intValue)
        .sum();

A: The stream returned by Arrays.stream(animals) is of type Stream<String>, while you are reducing the stream with an identity of zero which is an int.
A simple way of doing this is mapping each animal to its count, and reduce the resulting Stream<Integer> to its sum:
int totalAnimals = Arrays.stream(animals)
                         .map(animalCounts::get)
                         .filter(Objects::nonNull)
                         .collect(Collectors.summingInt(Integer::intValue));

Note the use of getOrDefault(animal, 0) in the map, because the array may have elements not present in the map.


text:
Q: Firestore rules : check the existence of a value in array I want to give permission of read and write just to users whom exist in the members group but I don't know why it doesn't work ?
This is the rules in firestore :
    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  match /Users/{uid} {
  allow write: if request.auth != null && request.auth.uid == uid;
  allow read : if request.auth != null;
  }

    match /GroupChat/{document=**} {
      allow read,create,update: if request.auth != null && request.auth.uid in request.resource.data.Members;

    }
  }
}

This is a screen of my data base
The query :
FirebaseFirestore.instance
          .collection("GroupChat")
          .where("Members",
              arrayContains: FirebaseAuth.instance.currentUser!.uid)
          .snapshots(),

when I want to display the information in my APP, I get this error :

W/Firestore(14600): (24.0.0) [Firestore]: Listen for Query(target=Query(GroupChat where Members array_contains 0FQhApDgWMVNTpOiDewF3qJX7IA3 order by name);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

A: As mentioned in the documentation,

The resource variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.

However, request.resource.data contains data that is being added in document in update/write operations. You should be using resource.data because you want to check existing data.
match /GroupChat/{document=**} {
  allow read,create,update: if request.auth != null && request.auth.uid in resource.data.Members;
}


text:
Q: Git repository file size is larger after migrating to git-lfs I have a fairly large repository that takes quite awhile to clone from remote. I decided I might benefit from Git LFS so I went and migrated the repo. Though, after migrating, pushing and re-cloning, the repository takes up more disk space than the original repository. The culprit on the FS is .git/lfs/objects.
Before the migration my .git folder was 846MB, after migration it was 2GB, which is counter-intuitive.
I've tried two methods of migration. One was BFG and the other was using git filter-branch (which took three days x_x). Both ended up with the same results.
Am I missing something? Is this normal?

A: The answer is quite simple - objects in git are compressed while objects in lfs are not.
I myself in the same situation but much worse: original .git folder was 5.7GB, after migrating it skyrocketed to 26GB.


text:
Q: How do you set a smaller window size after hiding a widget in PyQt5? I am trying to implement a functionality where you can hide or show a figure with the click of a button. However, the size of the dialog window does not change back when the figure is hidden again. The self.resize() statement seems to be ignored. How can I accomplish that? Using setFixedSize() works, however, I don't want the size to be fixed. I thought I could 'unfix' it somehow using setSizePolicy() but that didn't help.
import sys
import matplotlib.pyplot as plt

from PyQt5.Qt import QSizePolicy
from PyQt5.QtWidgets import (
    QDialog, QApplication, QGridLayout, QWidget, QGroupBox, QPushButton
)
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas

class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.settings = QGroupBox('Settings:')
        self.settingsLayout = QGridLayout()
        self.settings.setLayout(self.settingsLayout)
        self.showFigureBtn = QPushButton('Show Figure')
        self.settingsLayout.addWidget(self.showFigureBtn)
        self.layout.addWidget(self.settings)

        self.figureWidget = QWidget()
        self.figureWidget.setMinimumSize(300, 300)
        self.figureLayout = QGridLayout(self.figureWidget)
        self.fig, self.ax = plt.subplots()
        self.canvas = FigureCanvas(self.fig)
        self.figureLayout.addWidget(self.canvas)
        self.figureWidget.setLayout(self.figureLayout)
        self.layout.addWidget(self.figureWidget)
        self.figureWidget.setVisible(False)

        self.showFigureBtn.clicked.connect(self.toggle_figure)

        self.min_size = (300, 100)
        self.resize(*self.min_size)

    def toggle_figure(self):
        state = not self.figureWidget.isVisible()
        if state:
            self.showFigureBtn.setText('Hide Figure')
            self.min_size = self.size()
            self.figureWidget.setVisible(state)
        else:
            self.showFigureBtn.setText('Show Figure')
            self.figureWidget.setVisible(state)
            self.resize(self.min_size)
            # self.setFixedSize(self.min_size)
            # self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    GUI = MainWindow()
    GUI.show()
    sys.exit(app.exec_())

A: One possible way is to adjust the size with adjustSize() and then set the desired size:
def toggle_figure(self):
    state = not self.figureWidget.isVisible()
    if state:
        self.showFigureBtn.setText("Hide Figure")
        self.min_size = self.size()
        self.figureWidget.setVisible(state)
    else:
        self.showFigureBtn.setText("Show Figure")
        self.figureWidget.setVisible(state)
        self.adjustSize()
        self.resize(self.min_size)


text:
Q: How to make text strikethrough when hovered in elm (elm-ui)? Basically I want to make the text strikethrough when hovered. This doesn't work easily with
el [ mouseOver [Font.strike] ] (text "some text")

as it would with
el [ mouseOver [Background.color someColor] ] (text "some other text")

because Font.strike is a Attribute msg whereas Background.color is of type Attr decorative msg
Does anyone konw how to achieve described behavior with something like Font.strike?
I would also accept non elm-ui solutions if not possible otherwise.

A: Like you already pointed out, mouseOver requires a Attr decorative msg. It uses CSS for the hover (hence the limitations), which takes care of applying the style on mouse over and clears it on mouse out.
For the general case, we have to detect mouse over/out ourselves, using Element.Events. We also need to keep track of this state in our Model. Then we can apply the Font.strike attribute conditionally depending on the model.
We can listen for these events on an Element.el
Events.onMouseEnter Enter
  :: Events.onMouseLeave Leave
  :: style

, where style is either [ Font.strike ] or [], depending on the model.
Full code and working demo here: https://ellie-app.com/bNjP6CbGrLJa1


text:
Q: Parallel.for Loop - result varies for each click .. why does this happen? Following parallel.for loop uses data of a bitarray which is 300000 bits in length. and the data is fixed not to change. So the produced results "Count_of_Found_Pattern1" must be same no matter how many times I execute the function "check"
But, the issue is the values of "Count_of_Found_Pattern1" & "Count_of_Found_Pattern2" produce different values every time I execute the function "check" .. what have I done wrong?
when I check it using small amount of bits (about 16 bits instead of 300000) it produces good results. But, when the bitarray length is lengthier, it produces a total mess.
For Example:
1st execution --> Count_of_Found_Pattern1 = 150526 , Count_of_Found_Pattern2 = 97855
2nd execution --> Count_of_Found_Pattern1 = 45855 , Count_of_Found_Pattern2 = 187562
Regards!
Private Function check()

        Dim Count_of_Found_Pattern1 As Int64 = 0
        Dim Count_of_Found_Pattern2 As Int64 = 0
        Dim stopwatch As New Stopwatch

        stopwatch.Start()

        Dim Current_Position1 As Int64 = 0
        Dim Current_Position2 As Int64 = 1

        Parallel.For(0, lastbitarrayover2, Sub(countbits, loopstate)

                                               If BitArray(Current_Position1) = False And BitArray(Current_Position2) = True Then

                                                   Count_of_Found_Pattern1 = Count_of_Found_Pattern1 + 1
                                               End If

                                               If BitArray(Current_Position1) = True And BitArray(Current_Position2) = False Then

                                                   Count_of_Found_Pattern1 = Count_of_Found_Pattern1 + 1
                                               End If

                                               If BitArray(Current_Position1) = True And BitArray(Current_Position2) = True Then

                                                   Count_of_Found_Pattern2 = Count_of_Found_Pattern2 + 1

                                               End If

                                               If BitArray(Current_Position1) = False And BitArray(Current_Position2) = False Then

                                                   Count_of_Found_Pattern2 = Count_of_Found_Pattern2 + 1

                                               End If

                                               Current_Position1 = Current_Position1 + 2
                                               Current -Position2 = Current_Position2 + 2
                                               Numer_of_Completed_Iterations = Numer_of_Completed_Iterations + 1

                                           End Sub)

        Numer_of_Completed_Iterations = 0 'reset counter to 0

        stopwatch.Stop()
        TextBox1.Text = stopwatch.Elapsed.ToString

    End Function

A: Have you tried System.Threading.Interlocked.Increment to make this thread safe? For example:
If BitArray(Current_Position1) = False And BitArray(Current_Position2) = True Then
    Interlocked.Increment(Count_of_Found_Pattern1)
End If

A: When you increment Count_of_Found_Pattern1 (or Pattern2), first the value is read, then it is incremented, then it assigned.  But the thread that is executing can change during those three steps.
Thread 1: Read Count_of_Found_Pattern1
Thread 2: Read Count_of_Found_Pattern1
Thread 2: Increment
Thread 2: Write to Count_of_Found_Pattern1
...
Thread 1: Increment its old value
Thread 1: Write to Count_of_Found_Pattern1

Now Count_of_Found_Pattern1 is wrong.  And if Thread 2 had control of execution for more than just one iteration, it could be very wrong.
Consider doing as much as possible within PLINQ, avoiding any mutation of global state until all the threads have joined back up. The following code assumes you're interested in comparing adjacent entries in BitArray:
Dim counts = Enumerable.
             Range(0, lastbitarrayover2 / 2).Select(Function(i) i * 2).
             AsParallel().
             Aggregate(
                 Function()
                     ' We're using an object of anonymous type to hold
                     ' the results of the calculation so far.
                     ' Each thread calls this function, so each thread
                     ' gets its own object for holding intermediate results
                     Return New With {.Pattern1 = 0, .Pattern2 = 0, .Iterations = 0}
                 End Function,
                 Function(accumulator, i)
                     ' accumulator is this thread's intermediate-result-holder.
                     ' i is one of the even numbers from our big set of even numbers.
                     ' Each thread will call this function many times, building up its own accumulator object
                     ' the four conditionals from your code reduce to this If block
                     If (BitArray(i) = BitArray(i + 1)) Then
                         accumulator.Pattern2 += 1
                     Else
                         accumulator.Pattern1 += 1
                     End If
                     accumulator.Iterations += 1
                     Return accumulator
                 End Function,
                 Function(acc1, acc2)
                     ' Once each thread has built up its own accumulator object,
                     ' this function makes a new accumulator object that
                     ' combines the results from two threads.
                     ' This is called repeatedly until all the threads' results
                     ' have been combined.
                     Return New With {
                         .Pattern1 = acc1.Pattern1 + acc2.Pattern1,
                         .Pattern2 = acc1.Pattern2 + acc2.Pattern2,
                         .Iterations = acc1.Iterations + acc2.Iterations}
                 End Function,
                 Function(acc)
                     ' The last function here is supposed to take the combined results
                     ' and turn them into what you ultimately want to use.
                     ' Since the combined results are already in the form we want,
                     ' we'll just use the "identity" function here: it returns its
                     ' argument unchanged
                     Return acc
                 End Function)

Count_of_Found_Pattern1 = counts.Pattern1
Count_of_Found_Pattern2 = counts.Pattern2
Number_of_Completed_Iterations = counts.Iterations

This might seem like a lot, but it's really not too bad.  The main thing is that we are giving each thread its own set of variables to work with; that way we don't have to worry about the problems I outlined at the top of my answer.  Then, we combine the work done by each thread at the end.


text:
Q: How to draw upright annotation on a rotated PDFKit.PDFPage in iOS 1. Summarize the problem:
I'm trying to draw annotations on PdfPage in iOS from a sample JSON data like this:
"annotations": [
    {
        "id": "1024",
        "start_x": 1.60162,
        "start_y": 565.139,
        "end_x": 131.333,
        "end_y": 610.398,
        "page": 1
    },
]

The API side understands that a pdf page coordinate system always has its origin at the bottom-left corner of the visible page regardless of its rotation angles. Therefore it's expected that with the above JSON the annotation will be drawn near the top-left corner of the page. I've highlighted both the API coordinate system and the expected annotation position in yellow color.
The PDFKit.PdfPage has a rotation property that cause both the page and its coordinate system rotated (highlighted in green color). The rotation property of PdfPage on iOS increase clockwise. As shown in the image, the pdfPage.rotation = 90 and the annotion is drawn rotated. The sample pdf show in the image has 2 pages where page no. 2 (shown near the first section of the image above the red line) has its rotation = 0 so annotions are drawn exactly as expected from JSON data response.
With that being said, I need to adress two main problems to draw an upright annotation on a rotated pdf page:

*

*Problem #1: The green rectangle annotation need to be rotated and/or translated to its expected position regardless of the page's rotation. In this case the page's rotation is 90 degree and its coordinate origin is at the top-left corner, but it can be 180 degree rotation with origin at top-right corner and 270 degree rotation with origin at bottom right corner. The API side always nail the coordinate origin at the bottom-left of the visible page regardless of the page's rotation and can response annotation positions anywhere on the visible page.

*Problem #2: The text "Sample Anno" also needs to be drawn upright according to API's coordinate system and again, regardless of the page's rotation angles. Currently I'm using a PDFKit.pdfAnnotation to draw a bound of type CGRect, set it background color to green and its contents is "Sample Anno". Inside this annotation I draw a UILabel which fit inside the specified bound and it's drawing upright according to the page's coordinate system.

2. What I've tried:
First thing that come to my mind is set pdfPage.rotation to "0" and run but it also rotate the whole visible page, and this does not qualified to my expected result because the page needs to keep its current rotation angle to match with response from API.
Then I've tried to rotate the annotation bound using this formula, with the rotation of 53 degree (purely random) around the anchor point is A (center of the page's media box) as show in the bottom section of the image, the bound is rotated horizontally but still far from the expected position which is highlighted in yellow color. And this approach also make the text smaller because it still being drawn upright according to page's rotation and needs to fit inside the new bound (problem #2). Now I'm using CGAffineTransform.MakeRotation() and context.RotateCTM() functions from this answer to problem #2 but so far the text disappear.
I also have thought of proposing the API side coordinate system to change according to pdfkit rotation but that would be double the work since this problem is unique to iOS and both the web and Xamarin.Android are drawing annotation the same way.
3. My questions are:
Q1: Are there any general rules or formulas that can convert a point from any pdfPage.rotation coordinate system (be it 90, 180 or 270) to the bottom-left coordinate system?
Q2: If the answer to Q1 is none. How can I draw both annotation bound and text upright in each of the three pdfPage.rotation angle? Because each rotation angle has differnt effect on how the annotation is drawn. For example with 180 degree rotation angle, annotation that expected to be on the top left of the page will be flipped and rotated to the bottom-right area of this page. 270 degree rotation is similar to 90 degree rotation but the difference is that annotation is rotated counter-clockwise.
I'm developing this in Xamarin.iOS so answers in both C# and Swift are great. Thank you guys so much!