text:
Q: How to design a view transition like this in android I'm working on a project where I want to add a View transition like below. I have no idea where to start, can anybody help me out?

A: There are several ways you could achieve this type of effect, no idea how that vocabulary app is handling it, but a pretty easy way to get a very similar effect is to use multiple RecyclerView.ViewHolder types and then let DefaultItemAnimator take care of the animation work. Here's one way to go about that:
Model
Our model is going to contain the data we're display as well as a type to inform our RecyclerView.Adapter which ReclerView.ViewHolder to inflate. So, it might look something like this (AutoValue):
@AutoValue
public abstract class ExpandableModel {

    public static final int TYPE_STATIC = 0;
    public static final int TYPE_EXPANDED = 1;
    public static final int TYPE_COLLAPSED = 2;

    @Nullable public abstract List<ExpandableModel> data();
    public abstract String title();
    public abstract int progress();
    public abstract int max();
    public abstract int type();

    public static ExpandableModel createExpanded(List<ExpandableModel> data,
                                                 String title, int progress, int max) {
        return new AutoValue_ExpandableModel(data, title, progress, max, TYPE_EXPANDED);
    }

    public static ExpandableModel createCollapsed(List<ExpandableModel> data,
                                                  String title, int progress, int max) {
        return new AutoValue_ExpandableModel(data, title, progress, max, TYPE_COLLAPSED);
    }

    public static ExpandableModel createExpanded(ExpandableModel model) {
        return new AutoValue_ExpandableModel(
                model.data(), model.title(), model.progress(), model.max(), TYPE_EXPANDED);
    }

    public static ExpandableModel createCollapsed(ExpandableModel model) {
        return new AutoValue_ExpandableModel(
                model.data(), model.title(), model.progress(), model.max(), TYPE_COLLAPSED);
    }

    public static ExpandableModel createStatic(String title, int progress, int max) {
        return new AutoValue_ExpandableModel(null, title, progress, max, TYPE_STATIC);
    }

}

ViewHolder
We can define a basic ReclerView.ViewHolder that will bind some ExpandableModel data as well as provide us with a nice OnClickListener callback.
public abstract class ExpandableViewHolder extends RecyclerView.ViewHolder {

    public ExpandableViewHolder(ViewGroup parent, int layout) {
        super(LayoutInflater.from(parent.getContext()).inflate(layout, parent, false));
    }

    public void setItemClickListener(OnItemClickListener clickListener) {
        itemView.setOnClickListener(v -> {
            final int adapterPosition = getAdapterPosition();
            if (adapterPosition != RecyclerView.NO_POSITION) {
                clickListener.onItemClick(itemView, adapterPosition);
            }
        });
    }

    public abstract void bind(ExpandableModel model);

    public interface OnItemClickListener {
        void onItemClick(View itemView, int position);
    }

}

ExpandedViewHolder
public class ExpandedViewHolder extends ExpandableViewHolder {

    private final TextView title;
    private final TextView completion;
    private final ProgressBar progress;
    private final RecyclerView recycler;

    public ExpandedViewHolder(ViewGroup parent) {
        super(parent, R.layout.adapter_view_expanded);
        title = itemView.findViewById(R.id.expanded_category);
        completion = itemView.findViewById(R.id.expanded_completion);
        progress = itemView.findViewById(R.id.expanded_progress);
        recycler = itemView.findViewById(R.id.expanded_recycler);
        recycler.addItemDecoration(new SpaceItemDecoration(10));
    }

    @Override
    public void bind(ExpandableModel model) {
        title.setText(model.title());
        completion.setText(model.progress() + "/" + model.max());
        progress.setMax(model.max());
        progress.setProgress(model.progress());
        recycler.setAdapter(new ExpandableAdapter(model.data()));
    }

}

ExpandedViewHolder layout
<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:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="#ffFFC857"
    android:orientation="vertical">

    <TextView
        android:id="@+id/expanded_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:textColor="#ffffffff"
        android:textIsSelectable="false"
        android:textSize="28sp"
        tools:text="Basic Words" />

    <TextView
        android:id="@+id/expanded_completion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textColor="#ffffffff"
        android:textIsSelectable="false"
        android:textSize="18sp"
        tools:text="174/174 mastered" />

    <ProgressBar
        android:id="@+id/expanded_progress"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        tools:progress="100" />

    <android.support.v4.widget.Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/expanded_recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginBottom="4dp"
        android:orientation="horizontal"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

</LinearLayout>

CollapsedViewHolder
public class CollapsedViewHolder extends ExpandableViewHolder {

    private final TextView title;
    private final TextView completion;
    private final ProgressBar progress;

    public CollapsedViewHolder(ViewGroup parent) {
        super(parent, R.layout.adapter_view_collapsed);
        title = itemView.findViewById(R.id.collapsed_category);
        completion = itemView.findViewById(R.id.collapsed_completion);
        progress = itemView.findViewById(R.id.collapsed_progress);
    }

    @Override
    public void bind(ExpandableModel model) {
        title.setText(model.title());
        completion.setText(model.progress() + "/" + model.max());
        progress.setMax(model.max());
        progress.setProgress(model.progress());
    }

}

CollapsedViewHolder layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="165dp"
    android:layout_margin="4dp"
    android:background="#ffffffff"
    android:orientation="vertical">

    <TextView
        android:id="@+id/collapsed_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:textColor="#ff066FA5"
        android:textIsSelectable="false"
        android:textSize="28sp"
        tools:text="Basic Words" />

    <TextView
        android:id="@+id/collapsed_completion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textColor="#ffAEB8C3"
        android:textIsSelectable="false"
        android:textSize="18sp"
        tools:text="174/174 mastered" />

    <ProgressBar
        android:id="@+id/collapsed_progress"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        tools:progress="100" />

</LinearLayout>

Adapter
Now we can create our RecyclerView.Adapter. Basically, whenever an item is clicked we're going to replace it with either a TYPE_EXPANDED or TYPE_COLLAPSED ExpandableModel and because DefaultItemAnimator is already applied to RecyclerView, calling RecyclerView.Adapter.notifyItemChanged will nicely animate between the two types of RecyclerView.ViewHolder.
public class ExpandableAdapter extends RecyclerView.Adapter<ExpandableViewHolder> {

    private final List<ExpandableModel> data = new ArrayList<>(0);

    private int expandedPosition;

    public ExpandableAdapter(Collection<ExpandableModel> data) {
        this.data.addAll(data);
    }

    @Override
    public ExpandableViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_EXPANDED:
                final ExpandedViewHolder expandedHolder = new ExpandedViewHolder(parent);
                expandedHolder.setItemClickListener((itemView, position) -> collapse(position));
                return expandedHolder;
            case TYPE_COLLAPSED:
                final CollapsedViewHolder collapsedHolder = new CollapsedViewHolder(parent);
                collapsedHolder.setItemClickListener((itemView, position) -> {
                    collapseCurrent();
                    expand(position);
                });
                return collapsedHolder;
            case TYPE_STATIC:
                final CollapsedViewHolder staticHolder = new CollapsedViewHolder(parent);
                staticHolder.setItemClickListener((itemView, position) -> {
                    final ExpandableModel model = data.get(position);
                    Snackbar.make(itemView, model.title(), Snackbar.LENGTH_SHORT).show();
                });
                return staticHolder;
            default:
                throw new IllegalArgumentException("unknown type");
        }
    }

    @Override
    public void onBindViewHolder(ExpandableViewHolder holder, int position) {
        holder.bind(data.get(holder.getAdapterPosition()));
    }

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

    @Override
    public int getItemViewType(int position) {
        return data.get(position).type();
    }

    private void collapseCurrent() {
        final ExpandableModel curr = data.get(expandedPosition);
        data.set(expandedPosition, ExpandableModel.createCollapsed(curr));
        notifyItemChanged(expandedPosition);
    }

    private void collapse(int position) {
        final ExpandableModel curr = data.get(position);
        data.set(position, ExpandableModel.createCollapsed(curr));
        notifyItemChanged(position);
    }

    private void expand(int position) {
        final ExpandableModel curr = data.get(position);
        data.set(position, ExpandableModel.createExpanded(curr));
        notifyItemChanged(position);
        expandedPosition = position;
    }

}

Dummy data
    final Random ran = new SecureRandom();

    final List<ExpandableModel> basic = new ArrayList<>(0);
    for (int i = 0; i < 10; i++) {
        final int max = 10;
        final int progress = ran.nextInt(max + 1);
        final String title = ("Basic Words: " + (i + 1));
        basic.add(ExpandableModel.createStatic(title, progress, max));
    }

    final List<ExpandableModel> intermediate = new ArrayList<>(0);
    for (int i = 0; i < 10; i++) {
        final int max = 10;
        final int progress = ran.nextInt(max + 1);
        final String title = ("Intermediate Words: " + (i + 1));
        intermediate.add(ExpandableModel.createStatic(title, progress, max));
    }

    final List<ExpandableModel> advanced = new ArrayList<>(0);
    for (int i = 0; i < 10; i++) {
        final int max = 10;
        final int progress = ran.nextInt(max + 1);
        final String title = ("Advanced Words: " + (i + 1));
        advanced.add(ExpandableModel.createStatic(title, progress, max));
    }

    final List<ExpandableModel> data = new ArrayList<>(0);
    data.add(ExpandableModel.createCollapsed(basic, "Basic Words", 7, 10));
    data.add(ExpandableModel.createCollapsed(intermediate, "Intermediate Words", 5, 10));
    data.add(ExpandableModel.createCollapsed(advanced, "Advanced Words", 3, 10));

    final RecyclerView recycler = findViewById(android.R.id.list);
    recycler.setAdapter(new ExpandableAdapter(data));

Extra
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int space;

    public SpaceItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        final int childPosition = parent.getChildLayoutPosition(view);
        if (childPosition == RecyclerView.NO_POSITION) {
            return;
        }
        if (childPosition < 1 || childPosition >= 1) {
            outRect.left = space;
        }
        if (childPosition == getTotalItemCount(parent) - 1) {
            outRect.right = space;
        }
    }

    private static int getTotalItemCount(RecyclerView parent) {
        return parent.getAdapter().getItemCount();
    }

}

Results (video)


text:
Q: Apache Spark isEmpty false but collection is empty I am experiencing problems with Apache Spark when I call isEmpty on JavaRDD collection it returns false even though collection is empty.
Here's sample code (modified as it's from my final year project and I'm not allowed to publish any code):
sampleRdd = inputRdd.filter(someFilterFunction)
if(sampleRdd.isEmpty()) {
       return inputRdd.first();
} else {
        return sampleRdd.first(); // JVM points error on this line
}

Problem is sometimes condition is false so sampleRdd.isEmpty() returns false meaning it's not empty therefore execution proceeds to return statement where it's trying to retrieve first() element of that collection but it throws exception:
Exception in thread "main" java.lang.UnsupportedOperationException: empty collection
at org.apache.spark.rdd.RDD$$anonfun$first$1.apply(RDD.scala:1314)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:147)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:108)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:306)
at org.apache.spark.rdd.RDD.first(RDD.scala:1311)
at org.apache.spark.api.java.JavaRDDLike$class.first(JavaRDDLike.scala:510)
at org.apache.spark.api.java.AbstractJavaRDDLike.first(JavaRDDLike.scala:47)
.
.
.

Is there a bit I am missing? I'm currently running it on local machine as it's still not fully developed.
Thanks
EDIT: To add more info JVM points to line sampleRdd.first() when I get this error so initial inputRdd is not empty
EDIT2: I wrote some extra lines that print size of inputRDD before filter and sampleRDD after filter like that:
System.out.println(inputRdd.count());  // Returns nonzero possitive int eg.100
sampleRdd = inputRdd.filter(someFilterFunction)
System.out.println(sampleRdd.count()); // Returns int eg. 1
System.out.println(sampleRdd.count()); // Sometimes returns different int than first call eg.3
if(sampleRdd.isEmpty()) {
       return inputRdd.first();
} else {
        return sampleRdd.first(); // JVM points error on this line
}

And I observed very interesting behaviour and that is that sometimes inputRdd.count() returns 100 but first sampleRdd.count() returns 1 and second sampleRdd.count() returns 3 or basically different number from the first call. So basically looks like size of sampleRdd changes between two calls and therefore I assume sometimes it might change to after passing condition and trying to call first() returns error.
Any idea what might be causing that?

A: What if inputRdd is originally empty?
In that case, sampleRdd is also empty. Therefore samplerdd.isEmpty evaluates to true and inputRdd.first() throws the Exception.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Duplicate asynchronous component twice render the last I create the same component (Recipes) or Screen twice, sending different properties.
<Recipes setRecipes = {this.setRecipes} id="1" />
<Quantity setQuantity = {this.setQuantity} />
<Recipes setRecipes = {this.setRecipes2} id="2" />
<Quantity setQuantity = {this.setQuantity} />

The properties-functions are the following. Only states change.
setRecipes = (recipe) => {
    this.setState({recipe:recipe})

  }

  setRecipes2 = (recipe2) => {
    this.setState({recipe2:recipe2})

  }

In mty component called Recipes, I get my local database (I use pouchdb), my recipes and products asicronically.
import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import style from './Styles/styleNew';
import PouchDB from 'pouchdb-react-native';

PouchDB.plugin(require('pouchdb-find'));

const gThis = null;
const db = new PouchDB('X')

export default class Recipes extends Component {

   constructor(props) {
      super(props);
      gThis = this;
      this.state = {
         setRecipes: this.props.setRecipes,
         id: this.props.id,
         recipeID: null,
         options: [ ],
      };
   }

   getRecipes() {
      let data = []
      db.find({
         selector: {
            type: {
               "$eq": this.state.id,
            },
            owner: {
               "$in": ['user']
            },
         },

      }).then(function (recipes) {
         recipes = recipes.docs

         for (let i = 0; i < recipes.length; i++) {

            recipe = recipes[i]

            let current = {
               id: recipe._id,
               name: recipe.name,
               recipe: recipe,
            }
            data.push(current)

         }
         gThis.setState({ options: data })

      }).catch(function (err) {
         console.warn(err.toString())
      });
   }

   componentDidMount() {
      this.getRecipes()
   }

   handleBackPress = () => {
      this.props.navigation.goBack();
   }

   defineRecipe(recipe, index) {
      this.setState({ recipeID: recipe._id });
      this.state.setRecipes(recipe)
   }

   render() {

      return (

         <View style={{ flex: 1 }}>
            <Text style={style.listText}>RECIPES {this.state.id} </Text>
            <ScrollView style={style.listScroll}>

               {this.state.options.length >0 &&
                  this.state.options.map((item, index) => {
                     key = index + '-' + this.state.id
                     //key = new Date().toISOString()
                     console.log(key)
                     return (
                        <TouchableOpacity
                           style={this.state.recipeID === item.id ? style.listOptionSelected : style.listOption}
                           onPress={() => { this.defineRecipe(item.recipe, index);}}
                           key={key} >
                           <Text style={style.listOptionText}>{item.name}</Text>
                        </TouchableOpacity>
                     );
                  })
               }
            </ScrollView>
         </View>
      );
   }
}

But the second Screen Recipe is rendered twice.

*

*Render 1

*Render 2
As you can see, the content is replaced.

A: I think it might have something to do with you gThis which I assume is a global this?
A better way to try and access this inside your class members is to either use lexical arrow functions in your class like this:
getRecipes = () => {
  // implementation
}

Or bind your class members to this in the constructor as follows
constructor(props) {
  super(props);
  gThis = this;
  this.state = {
      id: this.props.id,
      recipeID: null,
      options: [ ],
  };

  this.getRecipes = this.getRecipes.bind(this);
  this.defineRecipe = this.defineRecipe.bind(this);
}

On a different node, you have babel transpiling your ES6 code from as far as I can see.
I would strongly recommend replacing your for loops with es6 variants such as a map or forEach for readability
const options = recipes.map(recipe => {
  const { _id: id, name } = recipe;
  data.push({
    id,
    name,
    recipe,
  });
});

this.setState({ options });


text:
Q: instanceof in Grails How to determine Class type of Object in collection?
class Human{...}
class Man extends Human{...}
class Women extends Human{...}

def humans = Human.findAll()
humans.each(){ human ->

    // ??? , it is not work
   if ( human instanceof Man ) { println "Man" }
   if ( human instanceof Woman ) { println "Woman" }
}

Thanks a lot,
Tom

A: It looks as if it should work.
A couple random thoughts: are your humans correctly built? Maybe they are really not instances of Man or Woman.
You can do some tests using polymorphism:
class Human{ ...
  def speak() { println "Human" }
}
class Man extends Human{ ...
  def speak() { println "Man" }
}
class Women extends Human{ ...
  def speak() { println "Woman" }
}
def humans = humanService.all()
humans.each(){ human ->
  human.speak()
}

If the last line prints "Human Human Human", then the humans are not correctly built, and they are all human instances, instead of Man / Woman. If it shows an error, then they are something else (like nulls or something)
Good luck!

A: Based on your description, I would say you are running into Hibernate proxy objects (ie. class name is: Human_$$javaassist*). Solution would be to use the GORM provided version of insatnceOf. No need to eager fetch or use a different method.
def planet = Planet.get(1)
planet.humans.each(){ human ->
    if (human.instanceOf(Man)) { println "is Man"}
    if (human.instanceOf(Woman)) { println "is Woman"}
}

Notice the difference human.instanceOf(Man) rather than human instanceof Man. Use the gorm method rather than the java keyword.
You can see this section of the reference documentation for an [explanation][1]. See subsection "Lazy Single-Ended Associations and Proxies"
[1]: http://grails.org/doc/latest/guide/single.html#5.5.2.8 Eager and Lazy Fetching

A: There's nothing wrong with the code above, so my guess is that Human.findAll() is returning an empty collection, which would explain why nothing is being printed. Can you try this code instead?
class Human{...}
class Man extends Human{...}
class Women extends Human{...}

println "You have ${Human.findAll().size()} humans"

If this prints "You have 0 humans", then my guess is correct. If you want to get a list of all instances of Human, then it's probably better to use Human.list() instead of Human.findAll()

A: in Grails with Hibernate is really problem with instanceof. I have again trouble with it. I find this article:
http://community.jboss.org/wiki/ProxyVisitorPattern
I mean that trouble is appear when your class has some relations.
For example:
def planet = Planet.get(1)
planet.humans.each(){ human ->

   //it is not work, see the link above
   if (human instanceof Man) { println "is Man"}
   if (human instanceof Woman) { println "is Woman"}
}

Tom

A: thank for your help. I try your test. Method speak() return expected results.
For Man return "Man", for Woman return "Woman".
Your test finished ok, but my trouble is always here.

Maybe I forgot get more information:
This code is from Grails project. I mean that it is not important.
Exactly I use GORM call:
def humans = Human.findAll()

Tomas

A: Which version of Grails? I just tried this in the Grails 1.2.2 console and it works:
new Woman(name: "Julie").save()
new Woman(name: "Xena").save()
new Woman(name: "Mary").save()
new Man(name: "James").save()
new Man(name: "Tony").save(flush: true)

def people = Human.list()
for (p in people) {
    println ">> ${p.name} (${p.getClass()})"

    if (p instanceof Man) println "It's a man"
    if (p instanceof Woman) println "It's a woman"
}

Perhaps it's an issue that has been fixed?


text:
Q: High Charts Center Series Label I'm working with High Charts (http://www.highcharts.com/) to get some interactive charts for my webpage. I'm attempting to create a timeline of sorts using a column range chart and a bunch of series.
http://jsfiddle.net/asrm5zL0/
dataLabels: {
                enabled: true,
                align: 'middle',
                crop: false,
                style: {
                    fontWeight: 'bold'
                },
                verticalAlign: 'middle',
                formatter: function () { return 'CenterThis' }
            }

Currently I've created the above example. I've been trying to find a way to center the labels for a given series in the bar itself, however it seems to always want to label each data point. Is there a simple way to do this that I'm not seeing? The high charts documentation for series (http://api.highcharts.com/highcharts#plotOptions.series.dataLabels) didn't seem to have a property for this sort of thing.
Thank you for any help.

A: Try setting inside to true for dataLabels.
             ...
             dataLabels: {
                 align: 'center',
                 inside: true,
             ...

API reference, example: http://jsfiddle.net/asrm5zL0/7/

A: Example using a scatter series to split the difference:

*

*http://jsfiddle.net/jlbriggs/asrm5zL0/9/
.
{
    linkedTo: ':prev',
    name: 'Data Label Series',
    type: 'scatter',
    enableMouseTracking: false,
    marker: { radius : 0 },
    dataLabels: {
        enabled: true,
        align: 'center',
        verticalAlign: 'middle',
        style: {
            fontSize:'.75em',
            fontWeight: 'normal'
        },
        formatter: function () { return 'CenterThis' }
    },
    data: [[3, Date.UTC(2015, 09, 01, 17, 30, 0)]]
}


text:
Q: How to recognize binaries installed in `~/bin`? I am trying to execute some binaries manually installed in a bin directory in my $HOME (normal user).
Files are present in /home/user/bin and have exec permission:
$ ls -la ~/bin/
total 120
drwxr-xr-x  2 my_user my_user  4096 déc.   8 12:04 .
drwxr-xr-x 94 my_user my_user  4096 déc.   8 12:23 ..
-rwxr-xr-x  1 my_user my_user  4843 déc.   8 12:04 dplx
-rwxr-xr-x  1 my_user my_user  6515 déc.   8 12:04 dprint
-rwxr-xr-x  1 my_user my_user  2123 déc.   8 12:04 dprintm
-rwxr-xr-x  1 my_user my_user 15494 déc.   8 12:04 duplex
-rwxr-xr-x  1 my_user my_user  6501 déc.   8 12:04 kmprb
-rwxr-xr-x  1 my_user my_user 11069 déc.   8 12:04 kmprb_one
-rwxr-xr-x  1 my_user my_user  5543 déc.   8 12:04 krmpq
-rwxr-xr-x  1 my_user my_user  8267 déc.   8 12:04 mpr
-rwxr-xr-x  1 my_user my_user 25452 déc.   8 12:04 mprb
-rwxr-xr-x  1 my_user my_user  2953 déc.   8 12:04 pqnext
-rwxr-xr-x  1 my_user my_user   896 déc.   8 12:04 rmpq

And ~/.profile contains the call for ~/bin (it's the default on debian).
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

However, binaries are not recognized after a reboot:
$ duplex
bash: duplex : commande introuvable

I also tried source .bashrc and source .profile. The second one works but just for the terminal (if I close it and reopen a new one, the command isn't recognize anymore).
How could I permanently install these binaries?

A: The file(s) profile are meant to be read by all shells on start for login shells. Either the system wide /etc/profile (and /etc/profile.d) or the user added file ~/.profile.
For interactive, non-login shells, (most of the shells) you should use the file(s) .bashrc.
Just move the code:
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

from ~/.profile to ~/.bashrc.
Or, alternative (I really do not recommend that) source ~/.profile in ~/.bashrc.
To better understand the way the files are used, please look at this image.


text:
Q: php string replace quotes Hello I am trying to get all single quotes to be double quotes using the php str_replace however it does not seem to be working no matter what I do, suggestions
$page = str_replace("/'/", '/"/', $page);

A: You don't need to escape the quote character (in fact it is \, not /, unless you were confused with the standard regex delimiters) if the string isn't delimited with the same character.
$page = str_replace("'", '"', $page);

A: This should work:
str_replace("'",'"',$text);

A: Update: I'd agree with others that the following is an easier-to-read alternative for most folks:
$page = str_replace("'", '"', $page);

My original answer:
$page = str_replace(chr(39), chr(34), $page);

A: $page = str_replace("'", "\"", $page);

A: I think you should do replacements with preg_replace();
$str = "'Here 'it' goes'";
echo preg_replace("/'/", '"', $str);

A: This works. You actually don't need any escaping character.
$page = str_replace("'", '"', $page);

A: You only need the start and end / for preg_...() (and other regex) functions. For basic functions such as str_replace, simply use the characters:
str_replace("'", '"', $text);


text:
Q: BFS (Breadth First Search) Time complexity at every step BFS(G,s)

1   for each vertex u ∈ G.V-{s}
2       u.color = WHITE
3       u.d = ∞
4       u.π = NIL
5   s.color = GRAY
6   s.d = 0
7   s.π = NIL
8   Q ≠ Ø
9   ENQUEUE(Q, s)
10  while Q ≠ Ø
11      u = DEQUEUE(Q)
12      for each v ∈ G.Adj[u]
13          if v.color == WHITE
14              v.color = GRAY
15              v.d = u.d + 1
16              v.π = u
17              ENQUEUE(Q, v)
18      u.color = BLACK

The above Breadth First Search code is represented using adjacency lists.
Notations -

* G : Graph

* s : source vertex

* u.color : stores the color of each vertex u ∈ V

* u.π : stores predecessor of u

* u.d = stores distance from the source s to vertex u computed by the algorithm
Understanding of the code (help me if I'm wrong) -
 1. As far as I could understand, the ENQUEUE(Q, s) and DEQUEUE(Q) operations take O(1) time.<br>

 2. Since the enqueuing operation occurs for exactly one time for one vertex, it takes a total O(V) time.

 3. Since the sum of lengths of all adjacency lists is |E|, total time spent on scanning adjacency lists is O(E).

 4. Why is the running time of BFS is O(V+E)?.

Please do not refer me to some website, I've gone through many articles to understand but I'm finding it difficult to understand.
Can anyone please reply to this code by writing the time complexity of each of the 18 lines?

A: Lines 1-4: O(V) in total
Lines 5-9: O(1) or O(constant)
Line 11: O(V) for all operations of line 11 within the loop (each vertice can only be dequeued once)
Lines 12-13: O(E) in total as you will check through every possible edge once. O(2E) if the edges are bi-directional.
Lines 14-17: O(V) in total as out of the E edges you check, only V vertices will be white.
Line 18: O(V) in total
Summing the complexities gives you
O(4V + E + 1) which simplifies to O(V+E)
New:
It is not O(VE) because at each iteration of the loop starting at line 10, lines 12-13 will only loop through the edges the current node is linked to, not all the edges in the entire graph. Thus, looking from the point of view of the edges, they will only be looped at most twice in a bi-directional graph, once by each node it connects with.


text:
Q: Bounded-waiting Mutual Exclusion with test and set I am reading the famous Operating System Concepts book of (Avi Silberschatz, Peter Baer Galvin, Greg Gagne) edition 9: http://codex.cs.yale.edu/avi/os-book/OS9/
In the process synchronization chapter, there is an algorithm for "Bounded-waiting Mutual Exclusion with test_and_set" as follow:
do {
    waiting[i] = true;
    key = true;  // <-- Boolean variable that I do not see its utility
    while (waiting[i] && key) // <-- the value of the key variable here is always true
        key = test_and_set(&lock); // <-- it might become false here, but what is the point?
    waiting[i] = false;

    /* critical section */

    j = (i + 1) % n;
    while ((j != i) && !waiting[j])
        j = (j + 1) % n;
    if (j == i)
        lock = false;
    else
        waiting[j] = false;

    /* remainder section */
} while (true);

I can't see the role of the boolean variable key (used in the 3rd, 4th and 5th lines of the code above), I see that we can remove it without any particular effect on the algorithm, am I right or I have missed something?

A: You could simplify the algorithm to:
do {
    waiting[i] = true;
    while (waiting[i] && test_and_set(&lock)) ;
    waiting[i] = false;

    /* critical section */

    j = (i + 1) % n;
    while ((j != i) && !waiting[j])
        j = (j + 1) % n;
    if (j == i)
        lock = false;
    else
        waiting[j] = false;

    /* remainder section */
} while (true);

and it would be the exact same.  I guess the authors used key because they thought it would make the code easier to read.
As asked in the comments:
Generally, when using test_and_set you simply do while(test_and_set(&lock)) ;.  However in this case you want to ensure that the thread only waits a bounded amount of time for the lock.  This is accomplished with the waiting array.  At the end of the critical section when we unlock, we do not simply set lock to false which is how you typically unlock it.  Instead we try to find the next thread that is waiting for the lock.  By next, I mean incrementing the thread ID and then looping around when we hit n (the j = (j + 1) % n; part).  If such a thread j is found we set waiting[j] to false instead of lock.
This prevents scenarios where 2 or more threads are constantly grabbing the lock while another thread or group of threads are always waiting.  For example, say 3 threads are waiting for the same lock (threads 0, 1 and 2).  Say thread 0 releases the lock and then thread 1 grabs it.  While thread 1 has the lock thread 0 then tries to grab the lock again and when thread 1 releases the lock thread 0 grabs it instead of thread 2.  This could repeat indefinitely and thread 2 never gets the lock.
In this bounding wait algorithm by using the waiting array this behavior cannot occur.  If three threads are constantly grabbing the lock the next thread in terms of thread ID will go next, e.g. thread 0 will grab and release the lock followed by thread 1 and then followed by thread 2.  This is because each thread is waiting for either lock or its entry in the waiting array to become false.  If another thread is waiting for the lock when a thread is about to release the lock it sets the waiting entry instead of lock releasing only that thread from the spin wait.  This prevents the pathological case of one or more threads waiting indefinitely for the lock.


text:
Q: fetch not sending body in React Native I'm trying to post some JSON to an endpoint on the local network from a react native app but it doesn't seem to actually be POSTing the body.
    fetch( 'http://192.168.4.1/access-points', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify( {
            ssid: 'SSIDNAME',
            password: 'SSIDPASSWORD',
        } ),
    } );

It hits the endpoint ok, with the right method and content type but the body is no where to be found.
Below is what the endpoint seems to receive when I make the request from the react native app.
POST /access-points HTTP/1.1
Host: 192.168.4.1
Content-Type: application/json
Connection: keep-alive
Accept: */*
User-Agent: Hame/1 CFNetwork/808.2.16 Darwin/15.6.0
Content-Length: 45
Accept-Language: en-us
Accept-Encoding: gzip, deflate

When I make the request using Paw this is what I get
POST /access-points HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: 192.168.4.1
Connection: close
User-Agent: Paw/3.0.16 (Macintosh; OS X/10.11.6) GCDHTTPRequest
Content-Length: 45

{"ssid":"SSIDNAME","password":"SSIDPASSWORD"}

As you can see though, both are reporting the correct Content-Length

A: I had a similar issue -- The Spring Boot service was receiving POST body from Postman just fine but the call from my React app was received with no body and a Content-Length of -1.
After some hunting, I came across https://github.com/github/fetch/issues/318#issuecomment-335086509. This led me to learning more about CORS and adding the following to the @RestController class in my Spring Boot app:
@CrossOrigin(origins = WHITELISTED_AUTHORITY)

Alternatively, the React client fetch call could have:
    headers: {
      Origin: AUTHORITY,
    }

Setting it from the server would request the clients to send that info making it one less thing client programmers would have to do but it could (I don't know how all this works deeply enough to be sure -- those who do, please edit this answer) lead to more round trips between the client and server.

A: I had the same issue, then I checked request.form and request.data and I found out that the body was sent to request.data, so request.form returned None
So the solution is either change request.form to request.data or change the fetch options to send the body to request.form
If you want to send the body to request.form, set the headers:
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'

For example, the data is
const data = {
    ssid: 'SSIDNAME',
    password: 'SSIDPASSWORD',
}

Then create the form-data:
const formData = new FormData();
for (key in data) {
    formData.append(key, data[key]);
}

And the fetch will be:
fetch(url, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
    },
    body: formData
})


text:
Q: Why is ServiceModel sometimes declared in Framework folder's Web.config and sometimes not? We're deploying an ASP.NET 4.0 web application that has this declaration in the <httpModules> section of its Web.config file:
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler"/>

On most installations, this is both fine and necessary.  However, on two installations we got the below error about duplicate entries.  In the two installations that had this error, we found this declaration already existed here:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config

The installations that do not have the error, most installations, don't have that line in the above file.  Why is the Framework's Web.config file inconsistent across installations?  We haven't been able to identify the exact difference yet.  These are are mostly servers with either Windows Server 2003 or Windows Server 2008 but also some test boxes with Windows 7.  The working installations are a mix of the above, the two non-working ones are Windows Server 2008 and Windows 7.  All installations have .NET 4 Full Profile installed.

Detailed Error Information
Module    IIS Web Core
Notification    BeginRequest
Handler    Not yet determined
Error Code    0x800700b7
Config Error    Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'ServiceModel'
Config File    \\?\C:\Inetpub\wwwroot\web.config
Requested URL    http://localhost:80/
Physical Path    C:\Inetpub\wwwroot
Logon Method    Not yet determined
Logon User    Not yet determined
98:       <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler"/>

A: That module is installed (into the base .NET Framework config file) when you enable the following Windows Feature:
Microsoft .NET Framework 3.5.1 -> Windows Communication Foundation HTTP Activation
When you enable WCF HTTP Activation it registers WCF with IIS.  This includes adding the WCF Activation module, adding the script mapping for .svc files, etc.


text:
Q: FactoryGirl is making weird emails I have a factory set up like so:
require 'faker'

FactoryGirl.define do

factory :user do |u|
u.sequence(:name) { |n| "User #{n}"}
u.sequence(:email) { |n| "user#{n}@example.com"}
u.password "password"
end

factory :student_group do |student_group|
  sequence(:name) {|n| "class #{n}"}
end

end

And a rake task to populate my database:
require 'factory_girl_rails'

namespace :db do

desc "Fill db with sample data"

task :populate, :environment do

# reset the database
puts "Resetting the database"
Rake::Task['db:reset'].invoke

# create 100 users
puts "Creating users"
new_users = FactoryGirl.create_list :user, 100

#create 3 student_groups for each user
puts "Creating student groups for each user"
new_users.each do |u|
  FactoryGirl.create_list :student_group, 3, :user_id => u.id
end

# success message
puts "The database has been populated successfully"
end
end

It runs okay, but all the email fields are populated with this: ---
- user3@example.com
- User 3
It was just working - I'm not sure what's changed, and actually I copied and pasted things back from my github repository (which makes me think the error is elsewhere) - what could be causing the email to be formed like this?  if you need more files, just ask, i'm quite confused as to what could be the trouble.
EDIT to make sure the error is not from something left over in the database, i did rake db:reset and checked the db table again...it was empty, so it's not that!  still looking.

A: The output looks like a hash. You don't need argument u in the defining block according to latest FactoryGirl - maybe your old repo used old syntax.
It should look like this:
factory :user do
  sequence(:name) { |n| "User #{n}"}
  sequence(:email) { |n| "user#{n}@example.com"}
  password "password"
end


text:
Q: Mostrar y ocultar un div laravel Necesito ocultar o mostrar un div que contiene un select solo si en otro select elijo una opcion en particular, de lo contrario ocultarlo.
para este caso el que quiero ocultar o mostrar es el div que tiene el id="bancos" y esto que suceda al tener seleccionado en el anterior el valor <option value="Factoring" id="topic">Factoring</option> estaba probando con un script pero no me funciona, como deberia ser utilizando el script?
@extends('layouts.frontend')
@section('main-content')

            Volver

            EDITAR COBRO

        @include('frontend.layouts.partials.alerts')

ID: {{ request()->DocEntry }}

        <form method="POST" action="{{ route("frontend.billing.update")}}">
            <input type="text" class="form-control" name="DocEntry" id="DocEntry" value="{{ request()->DocEntry }}" hidden>

                Cambiar tipo de cobro
                <select class="form-control select2" name="tipodecobro" id="tipodecobro" required>
                        <option value="Vencimiento en 30 días">Vencimiento en 30 días</option>
                        <option value="Factoring" id="topic">Factoring</option>
                        <option value="Confirming">Confirming</option>
                </select>
                @if($errors->has('name'))

                        {{ $errors->first('name') }}

                @endif

                Seleccione un banco
                <select class="form-control select2" name="banco" id="banco" required>
                    @foreach($bancos as $banco)
                        <option value="{{$banco->name}}">{{$banco->name}}</option>
                    @endforeach
                </select>
                @if($errors->has('name'))

                        {{ $errors->first('name') }}

                @endif

                    Cancelar

                <input type="submit" value="Guardar" class="btn button button--primary button--large font-weight-bold" href="{{route('frontend.billing.pending')}}">

            @csrf
        </form>

@endsection
@section('scripts')
@parent

@endsection

A: puedes hacer la verificacion de la siguiente forma. Selecciona el input que contiene el valor del option, y verifica, si es Factoring, muestra el input o el div que tiene como id:topic:

A: Al menos con el código mostrado, la función actual no se está ejecutando en ningún momento y, en caso de ejecutarse, no vas a ver cambios, porque agregas y quitas una clase a uno (o más elementos) con clase topic:
function show(bancos) {
    $('.topic').addClass('d-none');
    $('.topic').removeClass('d-none');
}

Al tener esto: <option value="Factoring" id="topic">Factoring</option> deberías usar $('#topic') para acceder al elemento por ID, pero no es este el que deseas modificar, sino el div de bancos.
Necesitas asignar un evento al selector de tipo de cobro y analizar el valor para saber si mostrar o no el div de bancos:
$('#tipodecobro').on('change', function() {
    // $(this) es el select tipo de cobro, se analiza el valor
    if($(this).val() == 'Factoring')) {
        // Mostrar
        $('#banco').show();
    } else {
        // Ocultar
        $('#banco').hide();
    }
});


text:
Q: data is not retrieving while change environment from mysql to mysqli I would like to replace codes from mysql to mysqli. My earlier codes:
$query  = mysql_query("SELECT * FROM  table1,table2 WHERE table1.username = '" . $_SESSION['user_logged']. "' AND table2.info_id='$info_id'");
while($row = mysql_fetch_array($query)){
extract($row);}

I migrate the codes in the following way:
$query  = mysqli_query($conn,"SELECT * FROM  table1,table2 WHERE table1.username = '" . $_SESSION['user_logged']. "' AND table2.info_id='$info_id'");
while($row = mysqli_fetch_array($query)){
extract($row);
}

My earlier codes were working fine but present codes not working. I could not figure out where I am doing wrong.
connection:
$servername = 'localhost';
$username = 'XXXX';
$password = 'XXXXX';
$dbname = 'XXXXX';
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


text:
Q: Adde authenticity token manually but it is not verified in backend I had the <%= csrf_meta_tags %> in my HEAD tag, but I created the form manually, so the authenticity_token hidden field was not getting inserted in my form.
So I added the authenticity_token manually:
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">

When I send my website's default contact form (user is not logged in)   the action that handles it should verify the token and allow/deny the request. But it is not: I use jQuery to empty the field and submit the form but not error or exception are thrown.
I got this line protect_from_forgery with: :exception in application_controller.rb and put the same in the foo_controller.rb that extends application_controller and has the action that responds to the contact form.
So what am I missing? What do I have to do to have this form verified in the backend?
Thanks a lot!

A: When the submitted auth token is missing or not matching the one in session, Rails does what protect_from_forgery with: specifies but the request handling is not terminated. What happens is session gets destroyed so request is handled as belonging to a non-logged in user.
Here is an excellent writeup discussing how protect_from_forgery works.
It's hard to tell without looking at the code but I'd say your form submission code either does not pickup the auth token input value or it becomes stale before the request is made. The latter can happen for in a number of scenarios such as page loaded from the browser cache or browser tabs used to login/logout in parallel with the page in question.


text:
Q: Not able to import proj4 in angular project When I am trying to import proj4 in my angular project I am getting an error

Error: export 'defs' (imported as 'proj4') was not found in 'proj4' (possible exports: default)

I am importing as

import * as proj4 from 'proj4';

Though I have installed the proj4 as

npm install --save @types/proj4

How can I solve this issue? Am I missing something here ?

A: According to https://github.com/proj4js/proj4js/issues/247, for Typescript:

*

*the import statement should be import proj4 from 'proj4';

*and compiler option allowSyntheticDefaultImports: true must be set in tsconfig.json
This solved the issue for me for TypeScript 4.8 and Proj4 2.8.

A: This import statement import * as proj4 from 'proj4'; used to work before year 2017 for v2.4 of proj4.
To use it for 2.4 and above, import it this way: -
import proj4 from 'proj4';

Also, you might need to do the following changes to your TypeScript compiler i.e. inside tsconfig.json: -
"allowSyntheticDefaultImports": true

These changes should do it.


text:
Q: many-to-many and one-to-many mapping in java springboot I have those 3 entities that I want to transform to tables with relations
------user------
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_Id")
    private int userId;
    @Column(name="name")
    private String name;
    @Column(name="lastname")
    private String lastname;
    @Column(name="email")
    private String email;
    @Column(name="password")
    private String password;
    @Column(name="isActive")
    private boolean isActive;
    @Column(name="lastActive")
    private String lastActive;
    @Column(name="createdDate")
    private String createdDate;
    @Column(name="isBlocked")
    private boolean isBlocked;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "institution_id", nullable = false)
    private Institution institution;

    @ManyToMany(mappedBy = "users")
    private Set<Role> roles;

}

-----role------
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue
    @Column(name="role_Id")
    private int roleId;
    @Column(name="name")
    private String name;
    @Column(name="description")
    private String description;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable
    private Set<User> users;

}

-----institution------
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "institution")
public class Institution {
    @Id
    @GeneratedValue
    @Column(name="institution_Id")
    private int institutionId;
    @Column(name="name")
    private String name;
    @Column(name="type")
    private String type;
    @Column(name="location")
    private String location;
    @OneToMany(mappedBy = "institution", fetch = FetchType.LAZY)
    private Set<User> user;

}

But when I run my project as a java application, no tables are created in mySQL workbench  (the error occurred after adding he many-to-many annotation it was creating the tables before I add it).
Any ideas on why my code isn't working ?
And this is my application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mydb
spring.datasource.username = root
spring.datasource.password = pass123
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port=9090

A: @OneToMany does not create table.
@ManyToMany creates a table, you have to specify its details, like:
In user class:
 @ManyToMany
 @JoinTable(name = "users_roles",
    joinColumns = { @JoinColumn(name = "user_id") },
    inverseJoinColumns = { @JoinColumn(name = "role_id") })
 private Set<Role> roles;

In role class:
@ManyToMany(mappedBy="roles")
private Set<User> users;


text:
Q: splitting a string using the regex but ignore the separators within the quotes and the separators should be dynamic I'm using the following regex expression to split the delimiters in the string but ignoring the separators within the quotes
re.split('''[|,](?=(?:[^'"]|'[^']*'|"[^"]*")*$)'', data)

but the delimiters which i declared manually should be dynamic ,how will i use a variable in the above regex expression instead of specifying the delimiters in the regex expression itself
data="\"john\"|\"100032487\"|\"ab|cdef\"|\"ghijkl\""
output = re.split('''[|,](?=(?:[^'"]|'[^']*'|"[^"]*")*$)'', data)

instead of [|,] i should assign these delimiters to a variable and use the variable in the above regex expression

A: It looks like you are trying to use a regex to parse CSV styled data. The Python csv library is able to parse that.
For example the following approach:
import csv
from io import StringIO

data = "\"john\"|\"100032487\"|\"ab|cdef\"|\"ghijkl\""
print(next(csv.reader(StringIO(data), delimiter='|')))

would return the data as four items in a list:
['john', '100032487', 'ab|cdef', 'ghijkl']

As the third item is enclosed in quotes, it normally means that delimiters inside should be ignored. This kind of required logic is why using a regex for this is not recommended.
The csv.reader() takes a file object, so as data is a string I first use StringIO() to make data like a file.


text:
Q: DISTINCT em uma WHERE Oracle Preciso retornar as últimas duas compras de cada item da tabela NOTA_FISCAL_ENTRADA_ITEM, porém que retorne os valores da coluna VL_UNITARIO_ENTRADA_EST diferentes.
Ou seja, se nas últimas duas compras o valor for o mesmo, buscar a próxima compra mais recente com o valor diferente.
No SELECT abaixo, consegui retornar somente as duas compras mais recentes.
Como faço para trazer as ultimas duas compras com valores diferentes? Tentei com o DISTINCT, mas sem sucesso.
SELECT *
from    (
    SELECT CD_ITEM,
    DT_ENTRADA,
    VL_UNITARIO_ENTRADA_EST,
    row_number () over (partition by CD_ITEM order by DT_ENTRADA DESC) ULT_REG
    FROM NOTA_FISCAL_ENTRADA_ITEM
    )
WHERE ULT_REG <= 2

Resultado do SELECT atual:

A: Reaproveitando a maioria dos passos dados. A ideia aqui é usar o campo da data para retirar os duplicados, de seguida  ao mesmo tempo que obtemos o ordenação.
Na parte exterior, mantemos só as primeiras N entradas (2).
SELECT *
FROM (
  SELECT
    CD_ITEM,
    VL_UNITARIO_ENTRADA_EST,
    DT_ENTRADA,
    row_number () over (partition by CD_ITEM order by DT_ENTRADA DESC) ULT_REG
  FROM (
    SELECT
      CD_ITEM,
      VL_UNITARIO_ENTRADA_EST,
      MAX(DT_ENTRADA) AS DT_ENTRADA
    FROM NOTA_FISCAL_ENTRADA_ITEM
    GROUP BY
      CD_ITEM,
      VL_UNITARIO_ENTRADA_EST
    ORDER BY MAX(DT_ENTRADA) DESC
  ) NOTA_FISCAL_ENTRADA_ITEM_FILTERED
)
WHERE ULT_REG < 3;


text:
Q: How to check a immediate value if it is a valid EA in ida? For example:
68 38 30 42 00    push    offset aUser32_dll_0 ; "USER32.DLL"

If I get an operand value using GetOperandValue(), how can I check this immediate value is a valid linear address?

A: A possible script could be as follow:
#!/usr/bin/env python
from __future__ import print_function
import idaapi

def main():
    # get instruction at mouse pos
    current_ea = idaapi.get_screen_ea()
    print("[*] Current screen ea: {:#x}".format(current_ea))

    #get instruction operand
    insn = idaapi.decode_insn(current_ea)
    op = idaapi.cmd.Operands[0]

    # check if immediate value
    if op.type == idaapi.idaapi.o_imm:
        # get operand value
        imm_value = op.value
        print("[*] current operand is an immediate: {:#x}".format(imm_value))

        # check if addres is loaded in idb
        print("[*] {:#x} is loaded in IDB? -> {}".format(imm_value,
            idaapi.isLoaded(imm_value)))

        # get segment for immediate value
        seg = idaapi.getseg(imm_value)
        print("[*] Segment start for {:#x} is {:#x}".format(imm_value,
            seg.startEA))
    else:
        print("[-] Not an immediate")

if __name__ == "__main__":
    main()

Select an address in IDA view and then run the above script.
The script verifies that the instruction first operand is an immediate value. If it is, then it just checkq that the address of this immediate value is known by IDA (there are multiple ways of checking this, I just used isLoaded() and getseg()).
This obviously checks that the address is located inside the IDB. An address might be a valid virtual address in program context but located outside the IDB, and IDA has no way to know this.
Example (selecting the address 0x1019D5B1 in IDA view):
.text:1019D5B1    push    offset aAddr@P  ; " Addr @ %p\n"
.text:1019D5B6    call    pOutputRoutine

The offset aAddr@Pis located at 0x100A4ECC:
.text:100A4ECC aAddr@P         db ' Addr @ %p',0Ah,0

Script output:
[*] Current screen ea: 0x1019d5b1
[*] current operand is an immediate: 0x100a4ecc
[*] 0x100a4ecc is loaded in IDB? -> True
[*] Segment start for 0x100a4ecc is 0x10001000


text:
Q: Does my wrapper library .dll depend on the external .lib file I link? I have built a C++/CLI wrapper for a static library in a .lib file. The .lib file is listed as an external dependency in my project, but when I use my compiled .dll, do I still need to somehow include the .lib file in projects I use it in, or will the .lib be embedded in my final .dll?
Thanks

A: You're linking statically against your .lib, so everything needed by your wrapper will be "embedded". That's what statically linking is all about.


text:
Q: wordpress theme installing issue from a .zip file While I was installing a theme for Wordpress from .zip file, I got this error:
Warning: POST Content-Length of 11979500 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Can anybody help me?

A: PHP's default max post size is 8MB (or 8388608 bytes).
You need to change/set the post_max_size variable inside of your php.ini file. You just need to set it to more than 12MB for this particular file.
For example:
post_max_size=16M

Alternatively, you could upload the zip file through FTP to your /wp-content/themes/ folder and activate from inside of the WordPress Admin Panel.


text:
Q: Equality of a random variable implies equality on conditional expectation? I had this basic conjecture about random variables. Let $X$, $Y$ random variables on the same measure space.
Original claim: If for elementary events $\omega_1,\omega_2$ we have $Y(\omega_1)=Y(\omega_2)$, then also $E[X|Y](\omega_1)=E[X|Y](\omega_2)$.
I think the claim as it is cannot be correct since the expectation value is a random variable, defined therefore up only to equivalence, and we can change representative changing the value on a zero measure set. Nevertheless I think intuitively there should be a related statement because what the expectation value $E[X|Y]$ is doing, to my understanding, is taking a local mean of $X$ over a set where $Y$ assumes the same value. My questions are:

*

*does it exist a version of this claim that makes sense from a measure-theoretic point of view ? If this version of the claim exists, this new version is also true?

A: The conjecture is basically right. The conjecture, phrased differently, is that $E[X|Y]$ is a function of $Y$. A version of the conditional expectation (by definition) is measurable wrt the conditioning variable, thus a function of the conditioning variable.


text:
Q: Show that for $M=S^2$, $L$ is a plus or minus the identity.
Show that for $M=S^2$, the Weingarten map $L$ is a plus or minus the identity by computing the $L_{ik}$ in a coordinate patch and raising an index.

We know $L(x_k)=\Sigma {L_k}^l x_l$ and ${L_k}^k = \Sigma L_{ik} g^{il}$
Any help would be appreciated.

A: So pick some nice coordinate patches covering $S^2$ and work through them.
For example. let's do the stereographic projection from north pole:
$$
\mathbf{X}(u,v)=\left(\frac{2u}{u^2+v^2+1}, \frac{2v}{u^2+v^2+1}, \frac{u^2+v^2-1}{u^2+v^2+1}\right).
$$
The metric is
$$
\left(\frac{2}{u^2+v^2+1}\right)^2(du^2+dv^2)
$$
and with $\mathbf{n}=\mathbf{X}$, by explicit computation yields
\begin{align*}
\mathbf{n}\cdot\mathbf{X}_{uu}=\mathbf{n}\cdot\mathbf{X}_{vv}&=-\frac{4}{(u^2+v^2+1)^2},\\
\mathbf{n}\cdot\mathbf{X}_{uv}&=0.
\end{align*}
giving $L$ as desired.


text:
Q: Identify Object dependencies between a SQL Server database and Oracle over a Linked Server? I'm working with a SQL Server database Engine, which has a database containing approximately 2,000 Views. The majority of these Views use the OpenQuery statement to select data from an Oracle database via a Linked Server.
I have a new requirement to identify the dependencies between the SQL Server Views & the Oracle Objects referenced in the OpenQuery statements. This is not going to be a one-off requirement, so I will need to be able to refresh this on occasion. The Objects within Oracle change frequently and new Views are regularly added or modified in SQL Server too.
Some of the Views (about 0.5% of them) are structured as below (without OpenQuery):
CREATE VIEW [dbo].[SampleViewType1] AS

SELECT  ColX,
        ColY
FROM OracleLinkedServerName..OracleSchemaName.SampleOracleTable1

For these Views, I have stumbled across a useful query which can pick up the Views and the Oracle Objects it references.
SELECT
    Distinct
    referenced_Server_name As LinkedServerName,
    referenced_schema_name AS LinkedServerSchema,
    referenced_database_name AS LinkedServerDB,
    referenced_entity_name As LinkedServerTable,
    OBJECT_NAME (referencing_id) AS ObjectUsingLinkedServer
FROM sys.sql_expression_dependencies
WHERE referenced_database_name IS NOT NULL
And referenced_Server_name = 'OracleLinkedServerName'

It can give me results like below:
sys.sql_expression_dependencies result
However, the majority of the Views are structured as per the sample below and use OpenQuery. Unfortunately, sys.sql_expression_dependencies does not pick up these types of references.
CREATE VIEW [dbo].[SampleViewType2] As

SELECT
    ColA,
    ColB
FROM OPENQUERY
(
    OracleLinkedServerName,
    'SELECT *
    FROM SampleOracleTable2
    WHERE TestDate BETWEEN TRUNC(SYSDATE, ''month'') AND TRUNC(SYSDATE)'
);

Has anyone any suggestions on how I may obtain this information? At the moment, I'm not sure if it is possible. I'm open to using other technologies outside SQL such as C#, VB, etc.

A: You can get the view definition and check if the text has the name 'OracleLinkedServerName'. Please refer below query
SELECT *
FROM (
    SELECT OBJECT_DEFINITION(OBJECT_ID(CONCAT (
                    ss.name
                    ,'.'
                    ,so.name
                    ))) [Definition]
        ,so.name
    FROM sys.objects so
    JOIN sys.schemas ss ON so.schema_id = ss.schema_id
    WHERE type = 'V'
    ) a
WHERE a.DEFINITION LIKE '%OracleLinkedServerName%'

Query to get all the objects that are used in the view definition
DECLARE @objects TABLE (name NVARCHAR(max))

INSERT INTO @objects
SELECT so.name
FROM sys.objects so

-- You have to do this manually for all the oracle object
-- copy all your objects in excel and use excel funtions to form this
-- Remember last select should not have UNION All
INSERT INTO @objects
SELECT 'Oracle object 1'

UNION ALL

SELECT 'Oracle object 2'

SELECT *
FROM @objects so
INNER JOIN (
    SELECT *
    FROM (
        SELECT OBJECT_DEFINITION(OBJECT_ID(CONCAT (
                        ss.name
                        ,'.'
                        ,so.name
                        ))) [Definition]
            ,so.name
        FROM sys.objects so
        JOIN sys.schemas ss ON so.schema_id = ss.schema_id
        WHERE type = 'V'
        ) a
    WHERE a.DEFINITION LIKE '%OracleLinkedServerName%'
    ) a ON a.DEFINITION LIKE '%' + so.name + '%'


text:
Q: How to get the list of all 4 letter words in the English language in C# I am a beginner and have been playing around with C#. I have recently written the code for the very popular 'Cows and Bulls' word game. Its working for 2 players i.e; One player thinks of a word and the other person has to guess it. I am giving only 10 chances for guessing.
I now want to make the game for a single player(Computer v Human). I was wondering if there was anyway of getting all the 4 letter words in the English Language without Letter repetition(I have limited the game to 4 Letter words only). I know I can use an Enumeration and write down all the 4 letter words. But that's Hard Coding the Words. That would be my last option.I could type all the words in,but I would then have some idea of the word if I play the game.

A: Assuming you have a list of words called words list
You can use regex to select 4 letter unique words
 List<string> 4letterUniqueWords=words
.Where(x=>Regex.IsMatch(x,"^(?=^[a-zA-Z]{4}$)(?!^.*?(.).*?\1.*?$).*?$"))
.Select(y=>y)
.ToList<string>();

^(?=^[a-zA-Z]{4}$)(?!^.*?(.).*?\1.*?$).*?$
  ---------------  ------------------ ---
        |                  |           |->matches if both the lookaheads are true
        |                  |->checks if there are any repeating words
        |->checks if the words contains 4 letter alphabetic words


text:
Q: mod_rewrite subdomain (WITH a path) to URL Struggling with this and have already done about 30+ min of Googling.
I would like to redirect:
sub.domain.com/path1 to https://anotherdomain.com/path3
sub.domain.com/path2 to https://anotherdomain.com/path4

This code below does not work but demos my approach/thinking so far
#CLIENT 1
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^mockups.domain.com$
    RewriteCond %{REQUEST_URI} ^/client1/
    RewriteRule (.*) https://xd.adobe.com/view/xxxxxxxxxxxx/ [L,R]
</IfModule>

# CLIENT 2
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^mockups.domain.com$
    RewriteCond %{REQUEST_URI} ^/client2/
    RewriteRule (.*) https://xd.adobe.com/view/xxxxxxxxxxxx/ [L,R]
</IfModule>

Can anyone sort me out on this?

A: With your shown samples only, could you please try following.
Make sure you keep these rules on TOP of your .htaccess file and keep other rules below these.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mockups\.domain\.com$ [NC]
RewriteRule ^client1 https://xd.adobe.com/view/your_new_path_here [L,R=302,NE]

RewriteCond %{HTTP_HOST} ^mockups\.domain\.com$ [NC]
RewriteRule ^client2 https://xd.adobe.com/view/your_2nd_path_here [L,R=302,NE]

</IfModule>

Also please do clear your browser cache before testing your URLs.


text:
Q: Complicated Mysql Database Joins I'm creating a new system using an old database and need some help (because of inexperience)
This might be overly complicated but that's how the database is setup and I cannot change it.
There are 3 tables. Session 1, Session 2, and Registrants.
Session 1 and Session 2 are the same apart from content. So how it worked was that if a person wanted to book session 1 and session 2 on a specific day, the database would insert say "5" in both session 1's and session 2's 'id' rows. 'id' is the primary index.
There are 2 rows in 'Registrants' that contains a list (ex. 5,6,7) that contains the registrant names and some of the id's found in session 1 and session 2. So if you wanted to know if the person booked for session 1, the session's id would be in the registrants session 1 list.
Like I said. complicated.
I can do separate queries without trouble with
SELECT * FROM Session_1 WHERE id IN ($registrant_session_1 /* This is a single quote implode for the ouput of registrant_session_1 */ )"

and
SELECT * FROM Session_2 WHERE id IN ($registrant_session_2 /* This is a single quote implode for the ouput of registrant_session_2 */)

I need help with creating a query that joins them for simultaneous output. So the theory is that I first do the session checks and then join them based on the id's.

A: Perhaps you can use "union" clause
FROM Session_1 WHERE Session_1.id IN ($registrant_session_1 /* This is a single quote implode for the ouput of registrant_session_1 */ ) UNION (SELECT * FROM Session_2 WHERE Session_2.id IN ($registrant_session_2 /* This is a single quote implode for the ouput of registrant_session_2 */)

A: Here is a site I found particularly useful when I was first learning MySQL http://www.tizag.com/mysqlTutorial/mysqljoins.php


text:
Q: Scale legend box border, dashed and dotted lines when the figure size is changed with matplotlib I'm trying to use matplotlib to prepare some figures for publication. In order to make the font sizes match the text of the manuscript I'm trying to create the figure in the final size to begin with, so that I avoid scaling the figure when inserting it into the manuscript.
The problem I'm having is that as the figure is then pretty small, I can scale font sizes, axis  sizes, line widths etc., but what I've been unable to figure out is how to scale dashed or dotted lines, as well as the thickness of the legend border box. For a simplified and somewhat exaggerated example, consider

#!/usr/bin/python

small = True

from matplotlib import use
use('pdf')

from matplotlib import rc
rc('ps', usedistiller='xpdf')
rc('text', usetex=True)

if small:
    figsize = (1.0, 0.5)
    rc('font', size=2)
    rc('axes', labelsize=2, linewidth=0.2)
    rc('legend', fontsize=2, handlelength=10)
    rc('xtick', labelsize=2)
    rc('ytick', labelsize=2)
    rc('lines', lw=0.2, mew=0.2)
    rc('grid', linewidth=0.2)
else:
    figsize = (8,8)

import numpy as np

x = np.arange(0, 10, 0.001)
y = np.sin(x)

import matplotlib.pyplot as plt
f = plt.figure(figsize=figsize)
a = f.add_subplot(111)
a.plot(x, y, '--', label='foo bar')
a.legend()
f.savefig('mplt.pdf')

If you change the first executable line to small = False you can see how it should look in "normal" size. Compared to the normal size, the small plot suffers from a legend box with too thick borders, and the dashed line is too coarse, i.e. too long dashes and too long distance between the dashes.
So my question is, is there a way to fix these two problems?
The matplotlib version I'm using is 0.99.1.2.

A: To adjust the dashes, use
a.plot(x, y, '--', label='foo bar', dashes=(2,2))

and the legend box line width,
lg = a.legend()
fr = lg.get_frame()
fr.set_lw(0.2)


text:
Q: Magento 2 Adminhtml Grid Create like Magento 1 I am new to Magento 2. I want to create a simple Grid where will be 3 columns, ID, Full Name, Email. How can I do that?
As a new comer i found its lil hard for me to create grid using UI Components & XML Layout. I want to create the grid like magento 1, I am familiar with Magento 1.
Can anyone help me with any tutorials??
Thanks in Advance.

A:
To Create Magento2 Admin Grid Please follow the instructions of below blog:
  [Simple follow this blog steps]
  [1]: https://www.mageplaza.com/magento-2-module-development/create-admin-grid-magento-2.html
[Simple follow this blog steps][2]: How to create Admin Grid in Magento2?


text:
Q: What do you call a subset of a collection? I get confused with this. A set, is a collection of distinct objects. But what if I have a collection that contains duplicates but I need to check if another collection have items that matches all items in the other collect. Can I still call it as subset?
Example:
A = [1,2,2,3,3,3];
B = [1,2]; B ⊆ A = true
C = [1,2,2] C ⊆ A = true
D = [1,1,2]; D ⊆ A = still true
Basically, if I considered A as a set, then B, C and D are subset of A. But if I counted the duplicates, then can I consider D as not a part of A? What term should I use instead of set and subset?
In this scenario, what principle/theory should I use to check matches between two collections if I want to consider the number of the duplicates as part of criteria? In my example, would make the case D as false


text:
Q: How does computer sleep mode works? How RAM holds information even if power is cut off in sleep mode? How does computer sleep mode works? How RAM holds information even if power is cut off in sleep mode? RAM is volatile memory which erases everything when power is cut off but if i put my computer to sleep and shut down power it holds all the information when it turns on again.How RAM maintains its state during sleep mode?

A: Power to RAM isn't cut off in regular sleep mode. If it is, the data is lost.
However, there are several possible modes that could be called 'sleep':

*

*In traditional S3 "Suspend-to-RAM" sleep mode, everything is powered off except the RAM. If you cut the power supply, RAM contents are lost.

*In hibernation mode everything is powered off, but the RAM contents are stored to disk (e.g. Windows puts them in a file "hiberfil.sys") before powering off, and are read back during power-on (resume).

*In the "hybrid sleep" mode, the RAM contents are first stored to disk (as if hibernating), but then the computer goes into regular S3 sleep mode (leaving the RAM powered on).
When you click "Sleep" in Windows, many desktops (and occassionally laptops) are configured to use the hybrid sleep mode – which means they keep the RAM powered, but also store its contents on disk while going to sleep. So as long as the computer has power, it'll keep RAM contents in place; but if you lose power, it'll simply read the same RAM contents from the hibernation file on disk. With modern fast HDDs you hardly notice the difference.


text:
Q: How to insert text nodes at specific locations with lxml? If tostring(root) is something like:
<root><child1></child1><child2></child2></root>

and one wants to insert plain, (maybe even already escaped) text before child1; between the two children; and after child2 with lxml, how one should do that exactly? I'm asking, because it looks like, there is no separate text-node in lxml, one can only access the text property of an Element, and I couldn't find any solutions in the API documentation either...
Anyway, the desired end result would look something like this:
<root>text1<child1></child1>text2<child2></child2>text3</root>

A: To insert text before any children of a node, use the node's text attribute.
To insert text after the child of a node, use that child's tail attribute.
from lxml import etree
s = "<root><child1></child1><child2></child2></root>"
root = etree.XML(s)
root.text = "text1"
child1, child2 = root.getchildren()
child1.tail = "text2"
child2.tail = "text3"
print(etree.tostring(root, method="c14n")) #use this method to prevent self-closing tags in output

Result:
b'<root>text1<child1></child1>text2<child2></child2>text3</root>'

A: The text attribute seems to do the job. Setting it seems simple enough.
test="<root><child1></child1><child2></child2></root>"
from lxml import etree
root = etree.fromstring(test)
etree.tostring(root)
b'<root><child1/><child2/></root>'
print(root.text)
None
root.text = '1'
print(root.text)
1
etree.tostring(root)
b'<root>1<child1/><child2/></root>'
for child in root:
    child.text = 'test'
etree.tostring(root)
b'<root>1<child1>test</child1><child2>test</child2></root>'

Now if you need text after the element ended, then you need the tail attribute of the element.
for child in root:
    child.text = None
    child.tail = 'tail'


text:
Q: Как снять активность с других элементов?

 $('img.img_table').click(function(){
      var $this = $(this);
      var newSource = $this.data('src');
      $this.data('src', $this.attr('src'));
      $this.attr('src', newSource);
  });

Допустим кликнули на первую картинку, она выделилась, как сделать чтобы при клике на вторую, у первой пропадала активность,а вторая была активная.
В примере две картинки но может быть больше

A: Без сохранения дополнительной инфомации о статусе элемента - никак. Пометим активный элемент классом "active". Поменяем картинки для всех активных элеменов кроме щелкнутого (и уберем с них класс "active") перед тем, как обрабатывать элемент, на который щелкнули.
 $('img.img_table').click(function(){
   var $this = $(this);

   $('img.img_table.active').not($this).each(function() {
     var newSource = $(this).data('src');
     $(this).data('src', $(this).attr('src'));
     $(this).attr('src', newSource);
     $(this).removeClass("active");
   });

   var newSource = $this.data('src');
   $this.data('src', $this.attr('src'));
   $this.attr('src', newSource);
   $this.toggleClass("active");
});


text:
Q: error in bitbucket-pipelines.yml at [pipelines > step > condition]. To be precise: At least one condition is required I created a bitbucket pipelines that looks like this:
pipelines:
  custom:
    dbt-run:
      - step:
          name: 'Validate'
          script:
            - cd dbt_4flow
            - dbt compile
          condition:
            changesets:
            includePaths:
             - "dbt_4flow/*"

However, when I try to run it via the UI, I get this error even though I have already given a condition. What am I doing wrong? Is it the syntax?
There is an error in your bitbucket-pipelines.yml at [pipelines > custom > dbt-run > 0 > step > condition]. To be precise: At least one condition is required

A: It might be an indentation issue. The following indentation should work.
pipelines:
  custom:
    dbt-run:
      - step:
          name: 'Validate'
          script:
            - cd dbt_4flow
            - dbt compile
          condition:
            changesets:
              includePaths:
                - "dbt_4flow/*"


text:
Q: Автоматическое обновление сертификатов letsencrypt на сайтах NIC Появилась потребность автоматического обновления сертификата от Let's Encrypt на сайте с хостингом от NIC. Хотел посоветоваться с Вами, каким образом проще и эффективнее это сделать. Была мысль использовать certbot, но , как я понял, он используется на веб серверах. А у нас веб-хостинг. Также думал использовать питон, который каждые 3 месяца будет ставить крон на обновление сертификата на сайте, но нашёл только как им проверить сертификат на актуальность. Как его обновить не нашёл(
Буду рад любым советам! Спасибо!


text:
Q: Google Apps Script - JDBC to Google cloud DB connection failed I have experienced an error when using Google Apps scripts to make connection to Google Cloud Database. The script working just fine before 2021/5/11 11:00AM. After that, the connection cannot be established and return "Failed to establish a database connection. Check connection string, username and password." I have no idea what could be the problem ;-(
The database has no issue using DB Client to connect.
Jdbc.getConnection('jdbc:mysql://' + CFG.IP_ADDR + ':' + CFG.PORT + '/' + CFG.DB_NAME, CFG.ACCOUNT, CFG.PASSWWD);
var CFG = {
IP_ADDR: 'ip address',
PORT: '3306',
DB_NAME: 'DBname',
ACCOUNT: 'account',
PASSWWD: 'pwd',
DRIVER_STRING: 'org.mariadb.jdbc.Driver',
CONNECT_PROPERTIES: 'useSSL=false'
}

A: This appears to be a bug!
There is already a report on Google's Issue Tracker which detail the same kind of behaviour:

*

*AppScripts get a "Failed to establish a database connection. Check connection string, username and password."
Google does seem to know about this issue but if it's causing problems you can also hit the ☆ next to the issue number in the top left on the aforementioned page which lets Google know more people are encountering this and so it is more likely to be seen to faster.
There is a proposed workaround in this issue thread - which is to include the string ?useSSL=false as a URL parameter, (as suggested by spcsLrg in their answer) but it has been reported that this does not work for everyone (and in most cases, if a third-party Database is being used).


text:
Q: const pointer in C I am trying to understand one pointer example in the o'reilly "Practical C" book regarding "const pointers".
const char *answer_ptr = "Forty-Two";

answer_ptr = "Fifty-One"; /* Legal because the pointer is a var and not constant
*answer_ptr = 'X'; /* Illegal because defined as constant.

What I don't understand is, what exactly is the "Forty-One"? Where is it stored, and what can I used it for?
If I try it out in CodeBlocks:
const char *answer_ptr = "Forty-One";
printf("Pointer: %s, Content: %c, Address %p.\n", answer_ptr, *answer_ptr, &answer_ptr);

answer_ptr = "Twenty-Two";
printf("Pointer: %s, Content: %c, Address %p.\n", answer_ptr, *answer_ptr, &answer_ptr);

The output is:
Pointer: Forty-One, Content: F, Address 0060FF0C.
Pointer: Twenty-Two, Content: T, Address 0060FF0C.

So it seems I can change the content of the variable the pointer is pointing to, even that I defined it as "const".
Is my understanding correct or do I miss here an important point?
To be honest I am very confused since answer_ptr and *answer_ptr seem to be the same...
Thank you guys for your help!
Cheers, Styx


text:
Q: Bug in F******** spatial relation? (I'm not cussing) I would expect ISpatialFilter.SpatialRelDescription to behave consistently with IRelationalOperator.Relation.  However, when I run the code below, I get:
    Total features : 44368
    Count1: 9 T********
    Count2: 9 T********
    Count1: 21 F********
    Count2: 44359 F********
    Count1: 1 ******F**
    Count2: 1 ******F**

Is this a bug in the F******** relation ?
private void TestSpatialFilter()
{
    IMxDocument mxdoc = ((IApplication)m_application).Document as IMxDocument;
    IFeatureLayer fLayer = mxdoc.FocusMap.get_Layer(0) as IFeatureLayer;
    IEnvelope env = ((IActiveView)mxdoc.FocusMap).Extent;
    env.Expand(0.5, 0.5, true);
    env.Project(((IGeoDataset)fLayer.FeatureClass).SpatialReference);
    Debug.Print("Total features : {0}", fLayer.FeatureClass.FeatureCount(null));
    IFeatureClass fc = fLayer.FeatureClass;
    string[] rels = { "T********", "F********", "******F**" };
    foreach (string rel in rels)
    {
        Debug.Print("Count1: {0} {1}", Count1(fc, env, rel), rel);
        Debug.Print("Count2: {0} {1}", Count2(fc, env, rel), rel);
    }
}

public static int Count1(IFeatureClass fc, IGeometry geom,  string relDescription)
{
    ISpatialFilter sf = new SpatialFilterClass();
    sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelRelation;
    sf.SpatialRelDescription = relDescription;
    sf.Geometry = geom;
    int i = fc.FeatureCount(sf);
    Marshal.FinalReleaseComObject(sf);
    return i;
}
public static int Count2(IFeatureClass fc, IGeometry geom, string relDescription)
{
    int i = 0;
    string relation = String.Format("RELATE(G1,G2,'{0}')", relDescription);
    IRelationalOperator relOp = geom as IRelationalOperator;

    IFeatureCursor fCur = fc.Search(null, false);
    IFeature feat;
    while ((feat = fCur.NextFeature()) != null)
    {
        if(relOp.Relation(feat.Shape,relation))
            i++;
    }
    Marshal.FinalReleaseComObject(fCur);
    return i;
}

A: That does seem a bit odd. Perhaps it was only tested with few specific operations, Ex: Intersects, Disjoint, etc? What does FF*FF**** (inverse of T********) do for you? I seem to remember Within not working a few versions back so it does not surprise me.


text:
Q: Checking if a string contains only digits ? (isDigitMethod required) The user should give a string, where we should check if all characters are numbers.
If all are digits, we will get one message that the password is with digits and move on with the program. If any of them (or all) is not a digit, then the user should enter password again.
(E.g. 465486 is acceptable. hell3429384 or sfdkjsfkj is not acceptable)
Apparently, my code is not working correctly, since whether I give a number or a letter to the password, I get the same result.
Am I looping something wrong, or am I using the isDigit method wrong?
import java.util.*;
public class Password {
    public static void main(String[] args) {
        Scanner passn = new Scanner(System.in);
        System.out.println("Give password: ");
        String pass = passn.nextLine(); /* user enters password*/
        int length = pass.length();
        boolean isadigit;
        for(int i = 0; i < length; i++) { /*looping each character one by    one*/
            char character= pass.charAt(i);
            if (Character.isDigit(i)) { /*checking if each character is digit*/
                isadigit = true; /* if it is, give the value to isadigit true*/
                System.out.println("PASSWORD is w digits");
            }
            else {
                System.out.println("PASSWORD w/out digits");
                passn.nextLine();
            }
        }
    }
}

A: If you can use java-8 there is one-liner:
pass.chars().allMatch(Character::isDigit)

A: You are not checking each character, but each index value.
Change
if(Character.isDigit(i))

to
if(Character.isDigit(character))

Also: you don't break out of the loop when you encounter a non-digit...

A: A side note if you are on Android:
You can use TextUtils.isDigitsOnly() directly, e.g.
TextUtils.isDigitsOnly(myString)

And just in case, an empty string is digit only because it doesn't contain any non-digit; also this method is not null-tolerant.

A: To be honest: You could write code like you did. But it would be better to use a regular expression on that. You want to know, if a certain String only contains digits. Here is the code:
String foo = "My_pwd_is_wrong_123!";
String bar = "123";
boolean foo_ok = foo.matches("^[0-9]*$") // Will be "false"
boolean bar_ok = bar.matches("^[0-9]*$") // Will be "true"

A: Ok, in that case: Your Problem is, that you continue your loop after identifiyng a non-digit in one Password. You need to BREAK your loop, as soon as you find a non-digit in the pwd:
public class TEST {

    public static void main(String[] args) {
        Scanner passn = new Scanner(System.in);
        System.out.println("Give password: ");
        String pass = passn.nextLine(); /* user enters password*/
        int length = pass.length();

        boolean isadigit = true;

        for(int i = 0; i<length; i++) { /*looping each character one by    one*/
            char character= pass.charAt(i);
            if (!Character.isDigit(character)) { /*checking if current character is digit*/
                isadigit = false; /* if it is not, give the value to isadigit false*/
                break;
            }
        }

        if(isadigit)
            System.out.println("PASSWORD is w digits");
        else
            System.out.println("PASSWORD w/out digits");
    }

}

A: Please see this sample implementation
    boolean isDigit = false;

    for (int i = 0; i < length; i++) {
        char character = pass.charAt(i);

        if (Character.isDigit(character)) {
            isDigit = true;
        } else {
            passn.nextLine();
        }
    }

    if (isDigit) {
        System.out.println("PASSWORD is w digits");
    } else {
        System.out.println("PASSWORD w/out digits");
    }

A: In Kotlin, you can use
text.all { it.isDigit() }

A: try to parse the string to Integer.
catch the exception
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
try
{
    Integer.parseInt(pass);
    System.out.println("Digital password!");
}
catch(NumberFormatException nfe){
    System.out.println("without digit password!");
}


text:
Q: Rails gem list for Code track and Query issue optimizer is there not my issue but for my knowledge improvement i also known which gem are use in rails for Track our rails app code and find issue in query.
please, help me.
Thanks!

A: I am not fully sure what exactly are you looking for, but:
Rubocop
https://github.com/bbatsov/rubocop -- is a best gem for tracking code quality and syntax style.
Bullet
https://github.com/flyerhzm/bullet -- verify your queries to find N+1 issues (https://www.sitepoint.com/silver-bullet-n1-problem/). But it's get fired only when you really trigger some action. At least I've never looked for or faced a way to run it through whole app.


text:
Q: Kafka consumer, which takes effect, max.poll.records or max.partition.fetch.bytes? I have trouble understand these two consumer settings, let's say I have a topic with 20 partitions, and all messages are 1KB size, and, to simplify this discussion, also suppose that I have only one consumer.
If I set max.partition.fetch.bytes=1024, then, since each partition will give me one message, I will get 20 messages in one go if I understanding it correctly.
But what if I set max.poll.records=10? Could anyone help to provide some explanation? Many thanks.

A: There is no direct relation between two configs. max.partition.fetch.bytes specifies max amount data per partition the server will return. On the other hand max.poll.records is specifies maximum number of records returned in a single poll().
So in your case if you have a topic with 20 partitions that each of them has one record  with 1KB size and there is only one consumer which subscribe this topic,
then you can get each of the messages beacuse message size doesn't exceed max.partition.fetch.bytes but you can also get at most 10 messages in one poll.
As a result;

*

*Your consumer will get 10 messages in the first call to poll().

*In your second poll() it will get other 10 records.


text:
Q: Question Edit Bug on App As per the website, any questions which has pending edits are not allowed to be edited, but edit button remains always active in app. It is critical and must be fixed.
Here is a screenshot: (Question which is still pending for an edit review, I clicked on edit, and got the edit window)

*

*App Version: 1.0.85

*Device Manufacturer: motorola

*Device Model: Moto G (4)

*

*OS Version: 6.0.1 (1)


text:
Q: Can sudo use my existing aliases? How can I let sudo use my existing aliases in my .bash_profile (or .bashrc, .profile …)?
For example I want to be able to use ll instead of ls -laGF as sudo.

A: alias sudo='sudo su -i ENV=/home/myuser/.profile'

A: No. Sudo draws from the root account and won't consult your user's ~/.bash_profile.
But you can workaround this problem by adding the following alias to your profile:
alias sudo='sudo '

*Note the space after the command. From then on, sudo will work normally and you'll be able to use your user's aliases without issue (both normally and with root privileges).

Explanation: http://www.gnu.org/software/bash/manual/bashref.html#Aliases says:

If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.


text:
Q: Since we cannot do i++, how to code looks neater I need to find the first '\t' symbol in an array. Since we do not have i++ or so in scala I ended up writing the following:
val data: Array[Byte] = //..
var i = 0
while(i < data.length && data{val j = i; i += 1; j} != '\t'){ }

Can we refactor it in a neater way?

A: If you want to do something until a condition is met, you would probably be better off splitting up the while and for loops. Declaring a for loop inside the declaration of a while loop is ugly and probably unpredictable when it gets more complicated.
Also, don't use var. It is best practice to keep everything as immutable as possible when using Scala.
Something like this technically does the job:
def iterateUntilByte(byte: Byte, array: Array[Byte]): Any = {
  for(i <- array.indices) {
    if(array(i) != byte) /* do something */ else return
  }
}

[ScalaFiddle]
Or a more condensed version:
def iterateUntilByte(byte: Byte, array: Array[Byte]): Any = {
  array.map(a => if(a != byte) /* do something */) // can be foreach if return type is Unit
}

[ScalaFiddle]
You can modify the above code to do whatever you want when you find \t, like if(a == byte) {...} else {...} (if you are only interested in the \t entry).

A: Don't use var (if at all possible within your time constraints; note that this is always possible).
Don't use return (ever ever ever! Read this).
You should also never write a loop. This seems hard when you first start using Scala coming from an imperative language but there is always a better way. Attempting to write a loop is not the "scala way", not functional programming.
You can use takeWhile and foreach to do something until some condition is met. You can use find to obtain the first item that matches some condition. You can use indexOf. You can use zipWithIndex. You can use filter. You can use foldLeft, collect, groupBy, or of course map. You can use convoluted combinations of these. You can use recursion to "return early". You do not ever need to "write a loop".
Your original question seems like an XY problem, but it appears val i = data.indexOf('\t') would do it, unless the data does not contain '\t', then it will be -1. More ideas;
val i = data.indexOf('\t') match {
  case -1 => data.length-1
  case n => n
}

val i = Some(data.indexOf('\t')).filterNot(_ == -1).getOrElse(data.length-1)

def i2(data: Array[Byte]): Array[Byte] = data.takeWhile(_ != '\t')

def printUpToTab(data: Array[Byte]): Unit = i2(data).foreach(println)

// Warning: obtaining the index of something is not usually necessary.
//  Step back and consider a cleaner solution.
def tabIndices(data: Array[Byte]): List[Int] = data.zipWithIndex.collect {
  case ('\t', n) =>
    println(s"Found a tab at $n")
    n
}.toList

// does a list contain less than N tab characters? Simple solution:
def containsLessThanNtabs(data: List[Byte], n: Int): Boolean =
  data.count(_ == '\t') < n

// This version will "return early" when N tabs are found,
//  not counting through the entire list.
// This could be more efficient for very long lists.
// You must have a `List` to use the `::` construct.
def recursiveVersion(data: List[Byte], n: Int): Boolean = {
  def recurse(bytes: List[Byte], count: Int): Boolean =
    if (count >= n) false
    else {
      bytes match {
        case Nil => true
        case '\t' :: tail => recurse(tail, count+1)
        case _ :: tail => recurse(tail, count)
      }
    }

  recurse(data, 0)
}

Hope this helps. Let me know if you want help extending these ideas to your actual problem.


text:
Q: How are smoke cells an example of Brownian motion? I don't get how smoke cells are an example of Brownian motion.

A: The smoke is a mixture of air and tiny 'dust' particles, which are much larger than the air molecules and undergo Brownian motion. Watching the dust particles under a microscope in a smoke cell (where the smoke is at rest), one can directly observe this Brownian motion.


text:
Q: Is there difference between using '~' and Unicode non-breaking space? Does (Lua)LaTeX treat these two character the same or is there some difference? I've got used to write Unicode NBSPs using Shift-Space shortcut and it is easier for me to use this instead of the tilde character. Should I change behavior of non-breaking space characters (U+00a0), or is it redundant?

A: In PDFLaTeX and the latex command on modern distributions, they are the same.  Both evaluate to \nobreakspace.  In LuaLaTeX and XeLaTeX, they are different by default, but you can change that.
The inputenc package parses the no-break space character (in each encoding that has it) as \nobreakspace.  In the Latin-1 encoding, for example, the definition is
\DeclareInputText{160}{\nobreakspace}

And for the default, UTF-8, it is
\DeclareUnicodeCharacter{00A0}{\nobreakspace}

The LaTeX kernel also makes ~ an active character, defined as
\def~{\nobreakspace{}}

In LuaLaTeX or XeLaTeX, ~ still evaluates to \nobreakspace, which is defined in the LaTeX kernel as
\DeclareRobustCommand{\nobreakspace}{%
   \leavevmode\nobreak\ }

However, the character U+00A0 is interpreted literally.  (Although it still searches and copies from the PDF as a space character.) You can clearly see the difference with the test file
\documentclass{article}

\begin{document}
foo~bar{^^a0}baz
\end{document}

In particular, U+00A0 is a fixed width set by the font, and \nobreakspace uses the same interword spacing as the rest of the line—so you might want the fixed-width non-breaking space for a monospace font.  The no-break space character, ^^a0, \symbol{"A0} and \char"A0 all give the same output.
However, you could redefine U+00A0 to evaluate to \nobreakspace:
\documentclass{article}
\usepackage{fontspec}
\usepackage{newunicodechar}

\newunicodechar{^^a0}{\nobreakspace}

\begin{document}
foo~bar{^^a0}baz
\end{document}

A: They're different in LuaLaTeX. Look at this example where the spaces preceding "here" are U+00A0.
In the first paragraph the active U+00A0 becomes the normal U+00A0 (of course one doesn't want to use \newunicodechar for this setting, but it was necessary for the test). In the second paragraph the active U+00A0 is \nobreakspace.
\documentclass{article}
\usepackage{newunicodechar}

\def\testchar{ }% U+00A0
\newunicodechar{ }{\test}% U+00A0

\begin{document}

\let\test\testchar

Some text with nonbreaking space up to here; now spaces are normal and we go to the next line

\let\test\nobreakspace

Some text with nonbreaking space up to here; now spaces are normal and we go to the next line

\end{document}

As you see, in the first paragraph the interword spaces are not uniform and the ones specified as U+00A0 are bigger.
If you do
\newunicodechar{ }{\nobreakspace}% U+00A0

in your preamble, you are effectively changing U+00A0 into \nobreakspace (that's essentially the same as ~).


text:
Q: Centre of an ellipse from the generic conic equation Find the centre of the ellipse $$14x^2-4xy+11y^2-44x-58y+71=0$$
My attempt : I know from the generic conic equation $ax^2+by^2+2hxy+2gx+2fy+c=0$ that the condition for an ellipse is $h^2<ab$. But I am unaware of the procedure to find the centre from the generic equation. Pls help.

A: Let $f(x,y)=14x^2-4xy+11y^2-44x-58y+71=0$ and solve the system
\begin{cases}
\dfrac{\partial f}{\partial x}=0,\\
\dfrac{\partial f}{\partial y}=0.
\end{cases}
then
\begin{cases}
28x-4y-44=0,\\
-4x+22y-58=0.
\end{cases}
so the center is $(2,3)$.


text:
Q: CRLF is not sent during serial communication using Python A win10 program running Python 3.7.9 trying to send via serial USB port to an ESP32 REPL running MicroPython.
The program is supposed to do the following:

*

*create a file "XXXX.py"

*write a string "AHFRTG" to the file followed by CRLF

*write a string "112121 " to the file followed by CRLF

*close the file

The file gets created, but there is only 1 line containing "AHFRTG112121". Ie. the CRLF is missing.
import serial
import time

try:
  portx = "COM6"
  bps = 115200
  timex = 5
  ser = serial.Serial(portx,bps,timeout=timex)

  result = ser.write("f = open('XXXX.py','a')\r\n".encode())
  time.sleep(1)

  result = ser.write("f.write('AHFRTG')\r\n".encode())
  time.sleep(1)

  result = ser.write("f.write('112121')\r\n".encode())
  time.sleep(1)

  result = ser.write("f.close()\r\n".encode())
  time.sleep(1)

  print('------------------------')
  ser.close() #Close serial port

except Exception as e:
  print("---abnormal---: ",e)'''

A: TLDR: You need to include CRLF for both the remote process and the file.

Right now there is only a CRLF passed to the remote process. The file content itself does not include a CRLF.
#       no CRLF is written to file vv
result = ser.write("f.write('AHFRTG')\r\n".encode())
#         CRLF is written to process ^^^^

You need to include the CRLF in the file content as well. As you are writing literal source code, the CRLF must appear as a literal of \ r \ n instead of an actual CRLF; this requires escaping each \.
#           CRLF is written to file vvvvvv but it is escaped in the source code
result = ser.write("f.write('AHFRTG\\r\\n')\r\n".encode())
#         CRLF is written to process ^^^^