text:
Q: How do I remove every file that has x in its title? I have a lot of directory where there are hundreds of files.
In every directory there are pairs of my_file-01.jpg and my_file-€01.jpg
I want to remove every file that contains € sign in its title: how to do that?

A: find does the job:
find . -iname "*€*" -delete gets rid of all files whose name matches "€", be careful, find goes into subdirectories as well, if you don't want that you have to tune the find params a little

A: Something along the lines of
find -name '*€*' -delete

You might want to try this first, to see if the correct files would be delete:
find -name '*€*' -ls

A: In each example, the first command lists files whose name contain a € and the second command deletes them.
Using GNU find (as found on Linux):
find -name '*€*' -ls
find -name '*€*' -delete

Add -type f after -name '*€*' if you only want to match regular files and not directories as well.
Using find, relying only on POSIX features:
find . -name '*€*' -print
find . -name '*€*' -exec rm {} +

Add -type f after -name '*€*' if you only want to match regular files and not directories as well.
Using bash 4 or zsh:
echo **/*€*
rm **/*€*

Under zsh only, **/*€*(.) restricts the matching to regular files, excluding directories.

If you only want to list files that have € in their names and such that an identical file without the € exists, here are standard find and zsh solutions.
find . -name '*€*' -type f -exec sh -c 'cmp -s -- "$0" "$(printf "%s" "$0" | tr -d "€")"' {} \; -print
find . -name '*€*' -type f -exec bash -c 'cmp -s -- "$0" "${0//€/}")"' {} \; -print
echo **/*€*(.e\''cmp -s -- $REPLY ${REPLY//€/}'\')


text:
Q: 1N5819 diode reading? I'm trying to find which diode in a charger is bad. I took the 1N5819 diode out of the electronics board and tested it with my multi-meter set to "diode".
What I got was 0000 in both directions. Shouldn't this diode (or any diode for that matter) only give a reading in one direction?
Does getting 0000 reading mean that this diode is bad?
What should the reading be?

A: Usually, the multimeter will give you a reading in only one direction:  the forward biased direction.  Some expensive meters can do reverse biased voltages, i.e. zener diodes, but most multimeters will only do one direction.    So, you'd have to connect the positive lead to the anode and the negative lead to the cathode.     Then the meter will give you the forward voltage drop of the diode.
If your meter is giving you '0000' both directions, it could mean one of two things:
-- The diode is definitely busted.
-- The meter is not functioning correctly.
Is it possible for you to test the diode function on your multimeter using a known, good diode?  That way you can verify at least the meter is working as expected.  You don't have to unsolder or take the diode out of the good test board to do this.

A: We can't know what your multimeter does when set to "diode".  Unless you explain exactly what the meter does on that mode, there is no way to know what 0000 means or what the reading should be for each direction.
However, you should certainly get some assymetry when measuring a diode.  On the Ohms scale, the resistance reading should be significantly higher in one direction than the other.  The reading itself won't be meaningful since the diode in effect adds a offset voltage, but you should certainly get different readings depending on orientation.
It sounds like maybe your diode is shorted.

A: What is show depends on your meter and your diode. For a silicon diode like 1N.... I would expect the meter to read about 0.300V (for Schottky) to 0.700V for a regular type in forward biased direction and OL (overload, infinity) in the reverse biased direction.
Sounds like the diode is bad, you should check the other ones too.

A: As noted - diode test ranges usually inject a small current.
 Readings are usually mV drop but no guarantee.
1N5819 is 1A Schottky.
 should read around 300 mV forwards and open circuit in revere direction.
If you have another diode see if it shows a differential reading when swapped.
If meter has a low Ohm range (200 Ohm max often) the you can usually see diode forward and back direction difference with that. Also try next 1 or 2 Ohm ranges up as well.
Most modern multimeters use 9V battery.
A few use 2 x AA batteries.
The latter may be less able to give good readings using low Ohms range.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with reversing line into file This code does reverse and put result in file, but not fully correct.
Like, some issues with detecting line breaker or sth. Here's an example:
Source:
This is a line.
This is another line.
Quick brown fox jumps over a lazy dog!

Result:
(blank line)
.enil a si sihT
.enil rehtona si sihT!god yzal a revo spmuj xof nworb kciuQ

#include <stdio.h>
#include <string.h>
char *reverse (char *str)
{
    char *begin, *end, c;
    if (!str || !(*str))
        return NULL;
    for (begin=str, end=str+strlen(str)-1; begin<end; begin++, end--)
    {
        c=*begin;
        *begin=*end;
        *end=c;
    }
    begin=str+strlen(str)+1; *begin='\0'; //??
    return str;
}
void main(void)
{
    char line[1000];
    FILE *fsrc, *frslt;
    fsrc=fopen("source.txt", "r");
    if (fsrc==NULL) return;
    frslt=fopen("result.txt", "w");
    while (!feof(fsrc))
    {
        fgets (line, 1000, fsrc);
        fputs (reverse(line), frslt);
    }
    fclose(fsrc);
    fclose(frslt);
}

A: A couple of comments/nitpicks, which may or may not solve your problem :)
if (!str || !(*str))
    return NULL;

Don't do that. Don't return NULL on empty strings, fputs() will barf. In my experience, it's better to a) assert that the str pointer is non-null, b) return the empty string.
begin=str+strlen(str)+1; *begin='\0'; //??

There should be no need to terminate the string, since it's already terminated.
void main(void)

Nah, main() returns an int.
while (!feof(fsrc))

This won't work. You need to do some IO before you can test for feof()/ferror(). IMHO it's better to simply loop on fgets().
while (fgets(line, sizeof line, fsrc) {
     ...
 }

It may be a good idea to drop the input and output files, and simply read from stdin and write to stdout, at least while testing. The functionality you're trying to implement is already available in a UNIX shell (man rev). Using stdin/stdout makes it easier to test and compare results with the results from rev.
Also, keep in mind that fgets() won't remove the \n from the string. input like "foo\n" becomes "\noof", which is probably not what you want.
Here's a snippet which illustrates my comments in code. It doesn't solve all problems, but should be sufficient to get you going.
#include <stdio.h>
#include <string.h>
#include <assert.h>

void reverse(char *str)
{
    char *begin, *end, c;
    size_t n;

    assert(str != NULL);

    n = strlen(str);
    if (n == 0)
        return;

    for (begin = str, end = str + n - 1; begin < end; begin++, end--) {
        c = *begin;
        *begin = *end;
        *end = c;
    }
}

int main(void)
{
    char line[1000];

    while (fgets(line, sizeof line, stdin)) {
        reverse(line);
        fputs(line, stdout);
    }
}

HTH


text:
Q: Concept of the slope Having difficulties understanding the concept of the slope:
Suppose we have $f(x)=x^2$, its derivative $f'(x)=2x$
At $x=10$, $f(x)=100$ and $f'(x)=20$. So the rate of change of the function at $(x,y)=(10,100)$ is $20$, but what does that mean? If we take $x+1=11$, we get: $f(11)=121$ and not $120$.
So what was the point of calculating the slope at (10,100)? What information did it provide us?

A: Well, it provided us with the slope at that exact point on the graph. Of course in this case the slope will change as soon as we move away from this point.
What can we do with the slope? We can for example see if that point on the graph is a possible local minima/maxima. If the slope is not equal to 0, there is no possibility for this to be the case, since we could move a bit up/down to find a higher/lower point. If we examine all cases where the slope is 0, we have a chance of finding our targets.
Another example would be the slope being acceleration of a particle in a physics model. Finding the acceleration at a point in time can allow us to derive other properties of the particle, such as force.

A: The line through the two points $(10,100)$ and $(11,121)$ on the graph is called a secant line, and it's slope is $21$.
If you pick a point closer to $(10,100)$ than the point $(11,121)$ you will find that the resulting secant line will have slope closer to $20$.
In a way, you are "sneaking up" on the slope of the tangent line by approaching it with a sequence of secant lines.
The slope of the tangent line is the limit of the slopes of the secant lines.


text:
Q: Objects not being interpretted correctly JavaScript Even though the console logs indicate that the value(s) inside the object has changed, the height of the div does not change correctly. What is this a result of? I'm expecting that it will change according to the number of 0's inside the object. For instance, if there's one 0, then it will decrease to 25px, and if there are zero 0's, it would decrease to 0px. However, it always decreases to 50px even if all inputs are filled. Why?
https://jsfiddle.net/r4gf716f/
$(document).ready(function() {

  var obj = {
    userLength: 0,
    passLength: 0,
  };

  $('#username').on('change', function() {
    if ($('#username').val().length < 6) {
      $('#para').html('too short - user');
      obj.userLength = 0;
      console.log('failed user');
    } else {
      $('#para').html('');
      obj.userLength = 1;
      console.log('WORKINGUSER');
    }
  })

  $('#password').on('change', function() {
    if ($('#password').val().length < 6) {
      $('#para').html('too short - pass');
      obj.passLength = 0;
      console.log('failed pass');
    } else {
      $('#para').html('');
      obj.passLength = 1;
      console.log('passed user');
    }
  })

  var errorCount = Object.keys(obj).filter(function(key) {
    return (obj[key] === 0);
  }).length;

  if (errorCount > 0) {

    $('.color').css("height", +errorCount * 25 + "px");
    console.log(errorCount);
  }

})

HTML

  <input type='text' id='username' placeholder='u'>
  <input type='text' id='password' placeholder='p'>

CSS
.color {
  background-color: black;
  height: 200px;
  width: 100px;
  transition: all ease-in-out 2s;
}

A: Like apsillers says it only runs once. I created a function for you to do the checking. you just call it at the start and when you want to check the errors.
    $(document).ready(function() {

  var obj = {
    userLength: 0,
    passLength: 0,
  };
checkErrors();
  $('#username').on('change', function() {
    if ($('#username').val().length < 6) {
      $('#para').html('too short - user');
      obj.userLength = 0;
      console.log('failed user');
    } else {
      $('#para').html('');
      obj.userLength = 1;
      console.log('WORKINGUSER');
    }
    checkErrors();
  })

  $('#password').on('change', function() {
    if ($('#password').val().length < 6) {
      $('#para').html('too short - pass');
      obj.passLength = 0;
      console.log('failed pass');
    } else {
      $('#para').html('');
      obj.passLength = 1;
      console.log('passed user');
    }
    checkErrors();
  })

function checkErrors(){
    var errorCount = Object.keys(obj).filter(function(key) {
      return (obj[key] === 0);
    }).length;

    if (errorCount > 0) {

      $('.color').css("height", errorCount * 25 + "px");
      console.log(errorCount);
    }
}
})

Edit:
If you want it the .color div to be 0px this would be the code:
    $(document).ready(function() {

  var obj = {
    userLength: 0,
    passLength: 0,
  };
checkErrors();
  $('#username').on('change', function() {
    if ($('#username').val().length < 6) {
      $('#para').html('too short - user');
      obj.userLength = 0;
      console.log('failed user');
    } else {
      $('#para').html('');
      obj.userLength = 1;
      console.log('WORKINGUSER');
    }
    checkErrors();
  })

  $('#password').on('change', function() {
    if ($('#password').val().length < 6) {
      $('#para').html('too short - pass');
      obj.passLength = 0;
      console.log('failed pass');
    } else {
      $('#para').html('');
      obj.passLength = 1;
      console.log('passed user');
    }
    checkErrors();
  })

function checkErrors(){
    var errorCount = Object.keys(obj).filter(function(key) {
      return (obj[key] === 0);
    }).length;

      $('.color').css("height", errorCount * 25 + "px");
      console.log(errorCount);
}
})


text:
Q: Total partition of a sequence From a sequence of size let say n consisting of numbers 1,2...n find the number of groups such that R and (R-1) will be in the same group if the sequence [1,2,3...N] is divided into group of "X" numbers sequentially i.e [1...N] is divided into groups [1...X],[(X+1)...2*X], [(2*X+1)...3*X] ... [ (X*floor((N-1)/X)+1)...N] , where 1<=X<=N and last group can have less than X numbers.
For eg: n=5 R=5
 For different values of "X" groups formed are as follow
For, X=1 ,
               [ {1},{2},{3},{4},{5} ]
     X=2
           [ {1,2} , {3,4} , {5} ]

     X=3
           [ {1,2,3} , {4,5} ]

     X=4
           [ {1,2,3,4} , {5} ]

     X=5
           [ {1,2,3,4,5} ]

We can clearly see that for X=3 and X=5, R and R-1 are in same groups.Hence answer=2.
Example 2:n=6 R=5
   X=1
           [ {1},{2},{3},{4},{5},{6} ]

     X=2

           [ {1,2} , {3,4} , {5,6} ]

     X=3

           [ {1,2,3} , {4,5,6} ]

     X=4

           [ {1,2,3,4} , {5,6} ]

     X=5

           [ {1,2,3,4,5}, {6} ]

     X=6

           [ {1,2,3,4,5,6} ]

here ans=3 for X=3,5 and 6.
Note:Can a formula be computed in general for this?

A: When X divides R-1 then R and R-1 will be in separate blocks.  Otherwise I do not understand what you are asking.


text:
Q: Homology of punctured projective space I am trying to calculate $H_k(X)$ where $X = \mathbb{R}P^n - \{ x_0 \}$
I started thinking about $k=2$. We can get the projective plane by taking the upper hemisphere with points along the equator identified according to the antipodal map. If we remove a point from the hemisphere, we can then enlarge this such that we are just left with a circle and thus for $k=2$ we just have the homology of the circle.
My geometric intuition starts to fail for $k=3$ and higher spaces. So my questions are:
1) Does the same construction work for higher $k$? (probably not, this seems too easy)
2) If not, what is the nice way to calculate the homology groups (say we know $H_k(\mathbb{R}P^n)$? I guess there is a way to use Mayer-Vietoris, but I just can't see it

A: We have a deformation retraction of $X$ to $\mathbb{RP}^{n-1}=\{x_0=0\}\subset X$ given by the homotopy : $$ ([0,1]\times X\to X:(t,[x_0:x_1:\dots:x_n])\mapsto [(1-t)x_0:x_1:\dots:x_n]                                                             $$
Since $X$ and $\mathbb{RP}^{n-1}$ are thus homotopically equivalent they have the same homology  so that $$ H_k(X)=H_k(\mathbb{RP}^{n-1}) \operatorname {for all} k\geq 0$$

A: Your idea should work similarly in general: Take the closed upper hemisphere of $S^n$. Then $\mathbb{R}P^n$ is obtained by identifying antipodal points on the equator, which is an $S^{n-1}$. So removing a point (preferably not on the equator!) would result in something homotopy equivalent to an $S^{n-1}$ with its antipodal points identified- and that's just $\mathbb{R}P^{n-1}$. So if you know the homology of that, you're in business!


text:
Q: Convert multiple rows in a single column in R I have a dataset that has multiple columns, each column represent a different value of the ID. I would like to convert these value rows into a single column.
Sample data
ID             Elevation_1       Elevation_2      Elevation_3     Elevation_4
 279557         2070.934         2457.829         2954.444            0.000
 280485         2070.934         2457.829         2966.311         3226.203

Desired output
ID      Elevation
279557  2070.934
279557  2457.829
279557  2954.444
279557  0.000
280485  2070.934
280485  2457.829
280485  2966.311
280485  3226.203

What I have tried so far
library(tidyverse)
library(dplyr)

df = df%>%
  gather(ID)

I also oooked into pivot_longer but couldn't quite understand how to use it in this case.
How can this be done using dplyr?


text:
Q: Efficient discharge of capacitor voltage to 2-10 ohm DUT I need to apply the voltage in a capacitor to a load (between 2 and 10 Ω) and need to have the most efficient and simple method to do so.
The goal is to apply power to a DUT (device under test), measure the energy applied to the DUT, and

*

*Have the highest possible amount of the energy stored in the capacitor reach the DUT.

*Drain the charge in the capacitor as quickly as possible.
It must never take longer than 10 ms (though I've found if it takes more than a few hundred µs it tends to be because the switching is too inefficient).
The capacitor is charged to specified voltage, disconnected from the power supply, and then a switch discharges the capacitor through a DUT (Device under Test).
Depending on specific test

*

*The capacitor can be charged from around 2 V to around 40 V,

*The capacitor can be from 0.68 µF to 100 µF

I am able to get 90-95% of the energy in the capacitor to the DUT using a IRLB8721PBF MOSFET.
Datasheet here - VDS - 30V, Ids - 62A, RDson - 9 mOhm, Qg - 8nC
The DUT (and a 0.05 Ω shunt) are in series between the capacitor and the drain of the MOSFET (low side switching). The source of the MOSFET is connected to 0 V. See schematic. Schematic is just the general concept - not the complete circuitry.
Questions:

*

*What principal parameters should I consider to determine how good a given transistor is for this application, or to determine the one that most closely meets my specifications ?

*Is a MOSFET the best solution. eg might a bipolar transistor be able to provide a better solution?

*If MOSFET is the way to go, does Vgs need to be at least Vth above Vds?
Mechanical switches aren't an option for the actual discharge switching.
I'm not too late to make small design changes around how the actual switching happens, I'm just paranoid that there is a better way to do this and that my tunnel vision on MOSFETs (specifically the one above) has blinded me from a better way.

A: The MOSFET
The \$R_{DS(ON)}\$ for this MOSFET is 9mΩ, already very good.
Importantly, it's much lower than the 50mΩ current sense resistor, making the sense resistor the most significant cause of energy loss during discharge (with a caveat described below).
To obtain this \$R_{DS(ON)}\$, though, you have to have to drive the gate way beyond the voltage \$V_{GS(TH)} = 1.8V \$ stated in the datasheet. In fact, on the first page of the datasheet, in the section entitled "Benefits", the phrase "Very Low RDS(on) at 4.5V VGS" is a pretty big hint.
On page 6 of the datasheet is this graph:

Here you can see that at room temperature, for this device to have an "on" resistance of less than 10mΩ, the required \$V_{GS}\$ is 5V, and it gets worse as temperature rises. To be certain, I would recommend a gate voltage of at least 10V.
So to answer your question "does Vgs need to be at least Vth above Vds", I have two things to say:

*

*No, you need at least 5V at the gate.

*The gate needs to be at least 5V higher in potential than the source, and \$V_{DS}\$ has nothing to do with it.

It's easy to apply a high voltage at the gate, but you also need to do it fast. The gate takes time to charge, and during that time the drain-to-source channel sits somewhere between high resistance (off) and 10mΩ (on), and is therefore dissipating power. Your goal is to keep the time spent in this middle ground as short as possible, which means charging the gate as quickly as possible.
The greatest impediment you face in this respect is any resistance that exists between the source of voltage that you intend to apply to the gate, and the gate itself. The gate is a capacitor, and together with the source resistance it forms a classic RC system, with an associated time constant R × C.
The datasheet tells us that the gate capacitance is around 1nF. So if your gate potential is derived from a source with 1kΩ of resistance, the time constant is:
$$ \tau = 1k\Omega \times 1nF = 1\mu s $$
This is the amount of time it takes to charge to only 63% of the target source's voltage. Whatever your target voltage at the gate, if the source of that potential has a resistance of 1kΩ (such as the output of a typical opamp), you can expect that for 1µs the MOSFET will be a significant contributor to energy loss.
I'll leave you to decide how acceptable that is. The moral is that you may need to be very careful about how you "drive" the gate.
The Shunt
With the shunt and the MOSFET there, totalling 60mΩ, and a DUT of 2Ω, the fraction of power delivered to the DUT (efficiency) will be (best case):
$$ \frac{2\Omega}{2\Omega + 60m\Omega} = 97\% $$
This doesn't even account wiring resistance or capacitor ESR, which could be an additional few tens of milliohms. You won't be able to achieve better with this design, but you can factor this loss into your calculations.
The Discharge
I think also that the extremely fast rise of current through the DUT will induce ringing, and will be easily coupled (both capacitively and inductively) into the gate drive circuitry, which could really mess things up. I advise that you keep that high-current loop well shielded (by using short, shielded cables) and keep loop area as small as as you can (don't use any long and/or widely separated traces/wires to close the loop).
Instead of a single large capacitor C, consider adding some smaller ceramics in parallel with it, say 1uF, 100nF and 10nF. This will improve its ability to respond to the sudden application of a heavy load, and may mitigate the ESR of C, another source of inefficiency. In fact, you can greatly improve the ESR of the capacitor by instead using multiple smaller capacitances in parallel.
Also, decouple your control circuitry with 100nF and 10nF capacitors - that sudden current spike will likely find its way to their otherwise clean voltage supply.
The Charge
To initially charge the capacitor, you seem to be connecting it directly across the power supply. This is going to be a huge load on the supply, and a big cause for concern for anything else using it.
I recommend limiting charging current with a small resistor, say 10Ω, to keep it down to something more reasonable than "all-the-amps", and to prolong the life of the capacitor.

A: The purpose I gather is to measure the charge discharge energy efficient in a low ESR capacitor with a fixed resistor. Then compare at different V and load R values to see how it changes.
You might want to consider a constant charge CC circuit and constant discharge CC circuit so you get similar curves as in battery tests.  Whatever load current you choose , select a FET with RdsOn < 1 % of your smallest load resistor using a a transistor or a switch with a cap across it to prevent bounce voltage on the gate.
You can simulate this in Falstad in short order by adding the 20 to 50mohm ESR if you choose your ps or any cap with ESR 100 to 200 uF caps.  T=~20 us =ESR*C low ESR types (ballpark)


text:
Q: SSDmobilenet pets config -> Faced error when tried to created tflite pb file from customize checkpoint created from transfer training Faced error when tried to created tflite pb file from customize checkpoint created from transfer training
System information :
ubuntu - 18.0
tf.VERSION = 1.14.1-dev20190517
tf.GIT_VERSION = v1.12.1-2154-g3df6d99f3f
tf.COMPILER_VERSION = v1.12.1-2154-g3df6d99f3f
env : LD_LIBRARY_PATH /usr/local/cuda-10.0/lib64:/usr/local/cuda-10.0/lib64

Tensorflow command:
python /object_detection/export_tflite_ssd_graph.py
    --pipeline_config_path models/ssd_mobilenet_v1_pets.config
    --trained_checkpoint_prefix model.ckpt-23595
    --output_directory /tflite/
    --add_postprocessing_op=true

Error log :

TypeError: export_tflite_graph() takes 6 positional arguments but 7 were given

Any help appreciated !

A: This is a bug with the script. We will fix it shortly.
Thanks for flagging!


text:
Q: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.events.Model.IMG here is my activity code:-
class event_images : AppCompatActivity() {

    private var recyclerView: RecyclerView? = null
    private var imageAdapter: Imageadapter? = null
    private var img1: MutableList<IMG>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_images)

        recyclerView = event_images
        recyclerView?.setHasFixedSize(true)
        recyclerView?.layoutManager = LinearLayoutManager(baseContext)

        img1 = ArrayList()
        imageAdapter = baseContext?.let { Imageadapter(it, img1 as ArrayList<IMG>, true) }
        recyclerView?.adapter = imageAdapter

        val wimagesRef = FirebaseDatabase.getInstance().getReference().child("events")
        e_imagesRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (snapshot in dataSnapshot.children){
                    val image = snapshot.getValue(IMG::class.java)
                    if (image != null){
                        event_images.visibility = View.VISIBLE
                        (img1 as ArrayList<IMG>)?.add(image)
                    }
                }
            }

            override fun onCancelled(error: DatabaseError) {

            }
        })

    }
}

here is adapter code:-
class Imageadapter (private var mContext: Context,
                    private var mimages: List<IMG>,
                    private var isActivity: Boolean = false) : RecyclerView.Adapter<Imageadapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Imageadapter.ViewHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.images_adapter, parent, false)
        return Imageadapter.ViewHolder(view)
    }

    override fun onBindViewHolder(holder: Imageadapter.ViewHolder, position: Int) {
        val imageid = mimages[position]

        Picasso.get().load(imageid.getImageUrl()).into(holder.ImageIv)
        holder.Datetv.text = imageid.getDate()
        holder.Venuetv.text = imageid.getVenue()

    }

    override fun getItemCount(): Int {
        return mimages.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var ImageIv: ImageView = itemView.image_ret
        var Datetv: TextView = itemView.date_ret
        var Venuetv: TextView = itemView.venue_ret

    }

here is my model code:-
class IMG {
    private var ImageUrl: ImageView = ""
    private var date: String = ""
    private var venue: String = ""

    constructor()

    constructor(ImageUrl: ImageView,
                date: String,
                venue: String){
        this.ImageUrl = ImageUrl
        this.date= date
        this.venue = venue
    }

    fun getDate(): String
    {
        return date
    }

    fun setDate(Date: String){
        this.date = Date
    }

    fun getImageUrl(): String {
        return ImageUrl
    }
    fun setImageUrl(ImageUrl: String){
        this.ImageUrl = ImageUrl
    }

    fun getVenue(): String
    {
        return venue
    }
    fun setVenue(Venue: String){
        this.venue = Venue
    }
}

The error my project is:-

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.events.Model.IMG at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436) at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232) at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80) at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203) at com.example.events.event_images$onCreate$2.onDataChange(event_images.kt:38) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75) at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63) at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:246) at android.app.ActivityThread.main(ActivityThread.java:8633) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

the snapshot of the db is:-

I don't know how solve this error.
Can someone help me solving this problem?

A: This means that the database encountered a single string property, where your code said it should expect an entire IMG object in your snapshot.getValue(IMG::class.java) call.
It's impossible for us to say for sure why this is, but check the events node in your database, because at least one child node/property under it is a string value, instead of an IMG object.

Update after you added the screenshot of your database:
Your events node contains the properties for a single event. So when you loop over dataSnapshot.children, the snapshot variable will first point to the date property, then to the imageurl property, then to the venue property. None of these properties is a valid IMG object on their own, which is why the SDK throws an exception.
The best solution is to change your database to have/allow multiple events under the events node:
events: {
  "-Mfdskheuheas...": {
    date: "...",
    imageurl: "..."
    venue: "..."
  },
  "-Mzsdfhkerqas...": {
    date: "...",
    imageurl: "..."
    venue: "..."
  },
}

You'd typically call push() in your code to generate that extra level in the database, which generates keys of the type -M... above. Also see the documentation on adding items to a list.
Alternative if you really only want to have the properties of a single event under /events, you can remove the loop from your onDataChange:
override fun onDataChange(dataSnapshot: DataSnapshot) {
    val image = dataSnapshot.getValue(IMG::class.java)
    if (image != null){
        event_images.visibility = View.VISIBLE
        (img1 as ArrayList<IMG>)?.add(image)
    }
}

A: You might need to change, If issue isn't resolved. Then please share your DB snapshot.
class IMG {
    private var ImageUrl: ImageView = ""

AND
constructor(ImageUrl: ImageView,
                date: String,
                venue: String){
        this.ImageUrl = ImageUrl
        this.date= date
        this.venue = venue
    }

to
class IMG {
    private var ImageUrl: String = ""

AND
constructor(ImageUrl: String,
            date: String,
            venue: String){
    this.ImageUrl = ImageUrl
    this.date= date
    this.venue = venue
}


text:
Q: VBA Validate that if one cell in a range has a value, all cells should have a value I have a spreadsheet where users will be entering data in columns A through D. I want to identify in a message box any rows (i) where the range (Ai:Di) is not either completely blank or completely populated. The total range that users can populate is A2:D501.
If no rows are identified, the macro should continue to the next piece of code that I've already written, which then proceeds to save the workbook.
One twist - column C is prepopulated with =IF(A2<>"",TODAY(),""). So, C will never truly be blank. The macro would need to consider the above formula as blank so that if a row only has that formula in column C it won't count it.
Thanks for your help, I'm new to this!

A: Something like this
Function Validate() as boolean
Dim WB as WorkBook
Dim WS as Worksheet
Dim CellA as Range
Dim CellB as Range
Dim CellC as Range
Dim CellD as Range
Dim RowNum as integer
Dim ErrorCnt as integer
Dim ErrorList as String
dim ValueCount as integer
set WB  = ThisWorkBook
Set WS = WB.Worksheets("SheetName")
ErrorCnt = 0
ErrorList = ""
For RowNum  = 2 to 501
    Set CellA = ws.Cells(RowNum, 1)
    Set CellB = ws.Cells(RowNum, 2)
    Set CellC = ws.Cells(RowNum, 3)
    Set CellD = ws.Cells(RowNum, 4)
    ValueCount  = 0
    If CellA.Value <> "" Then ValueCount = ValueCount +1
    If CellB.Value <> "" Then ValueCount = ValueCount +1
    If CellD.Value <> "" Then ValueCount = ValueCount +1
    If (ValueCount  >0 and ValueCount   <3) then
        ErrorCnt = ErrorCnt +1
        If ErrorCnt = 1 Then
           ErrorList = Cstr(RowNum)
        Else
           ErrorList = ErrorList  & ", " & Cstr(RowNum)
        End if
    End if
Next
If ErrorCnt = 0 Then
    Validate = True
ElseIf ErrorCnt = 1 Then
    MSgbox "1 Error on Row " & ErrorList
    Validate = False
Else
    MSgbox cstr(RowNum) & " Errors on Rows " & ErrorList
    Validate = False
End If
End Function

You could also use other functions to validate things further, for example if only numbers are valid for Column D then replace that line with
If isnumeric(CellD.Value) Then ValueCount = ValueCount +1


text:
Q: Get Facebook group members count in Node.js Is it possible to do that? I am playing with their explorer and I can't get the information of members..I just need to count members.
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=https%3A%2F%2Fwww.facebook.com%2Fgroups%2Ffree.code.camp.you.can.do.this%2F&version=v2.5
All groups are open/public. Is there any npm module that can do that?

A: First, you need to get the Group ID with the Search API: /search?type=group&q=free.code.camp.you.can.do.this
The Group ID is "1013157175381620", so that´s what you can use to access the members:
/1013157175381620/members

Now you have to use that API endpoit to get all members and count them. Most likely you will need to use Paging to get all of them: https://developers.facebook.com/docs/graph-api/using-graph-api#paging
Or even better: /1013157175381620/members?summary=true&limit=1
Result:
{
  "data": [
    {
      "name": "...",
      "administrator": false,
      "id": "..."
    }
  ],
  "paging": {
    "next": "..."
  },
  "summary": {
    "total_count": 529
  }
}


text:
Q: Dalvik memory allocation Is there any way, how to programatically (like allocating and filling some array) check, how much memory can Dalvik allocate before OutOfMemoryError appears? Is it possible to do it with Java?

A: Every Java application allocates memory when it runs. This is what we have done using
java -Xms<initial heap size> -Xmx<maximum heap size>.

Also, in Throwable block, you can do the following way:

*

*Total Memory (heap) - Runtime.getRuntime().totalMemory();

*System.out.println("Used Memory:"
        + (runtime.totalMemory() - Runtime.runtime.freeMemory()) / mb);

*System.out.println("Free Memory:"
        + Runtime.runtime.freeMemory() / mb);

*System.out.println("Total Memory:" + runtime.totalMemory() / mb);

Maybe this will solve the problem.


text:
Q: Удаление подстроки - пути на ФС Всем доброго дня. Имеется строка, содержащая такое:

/usr/lib/gcc/i686-pc-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ostream:581:69:
note: template<class _CharT, class
_Traits, class _Tp> std::basic_ostream<_CharT, _Traits>&
std::operator<<(std::basic_ostream<_CharT,
_Traits>&&, const _Tp&) /usr/lib/gcc/i686-pc-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ostream:528:77:
note: template<class _Traits>
std::basic_ostream<char, _Traits>&
std::operator<<(std::basic_ostream<char,
_Traits>&, const unsigned char*) /usr/lib/gcc/i686-pc-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ostream:523:75:
note: template<class _Traits>

Каким образом можно удалить весь путь к файлу, оставив лишь его имя? Спасибо.
A: Оператор замены (в perl, в php д.б. так же, в sed надо корректировать): s/^([^:]+)\///
. Удаляет с начала строки все не :, заканчивающиеся /


text:
Q: Save Email Attachment to Sharepoint I receive an automated report with a big .csv file. Flow is timing out for sending the email to sharepoint. Does anyone know if I can use VBA to save certain email attachments to sharepoint?
Thanks.


text:
Q: Is it possible to run a command within a login shell using sudo or su? I'm trying to run a non-interactive command within a login shell (using su - or sudo -i) but couldn't make it work so far.
Within ~/.bashrc I have sourced a script which sets all variables my application needs. When I do an interactive login su - username I can see all my variables there and if I run my application it works fine. However, when I try to execute my application by using su - username -c 'command' the necessary variables are not being set. In other words, it seems su - is incompatible with -c option. The same happens with sudo -i -u user command.
I have searched tons of questions but couldn't find an answer to this specific behavior.
According to bash man pages:
When bash is invoked as an interactive login shell, or as a non-interactive
shell with the `--login` option, it first reads and executes commands from the
file `/etc/profile`, if that file exists. After reading that file, it looks for
`~/.bash_profile`, `~/.bash_login`, and `~/.profile`, in that order, and reads and
executes commands from the first one that exists and is readable. The
`--noprofile` option may be used when the shell is started to inhibit this
behavior.

The above behavior is not working as ~/.profile executes ~/.bashrc and it in turn sources the script which sets all variables.
How can I execute a non-interactive login shell?
Thank you

A: You can source the variable file in your script. In your script, include the following line before referencing any of the variables:
source full_path_to_variable_file

This will read your variables into the script's session. You must use the full literal path (no aliases), starting with the root directory'/', so for example if your home directory's .bash_aliases defines your variables:
source /home/felima/.bash_aliases

On the command line '.' has the same effect
. ~/.bash_aliases

But in scripts using 'source' is more clear.


text:
Q: Cannot create a new Rails App after upgrading to Rails 6.1.4 I wanted to start a new rails project and decided to upgrade my Rails and Ruby versions.
I started by upgrading Rails to 6.1.4 and later upgraded Ruby to 3.0.2
Before creating my new app I decided to check once more the version of Rails running and I had this error:
$ rails -v
Traceback (most recent call last):
    2: from /Users/el/.rbenv/versions/2.6.5/bin/rails:23:in `<main>'
    1: from /Users/el/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems.rb:302:in `activate_bin_path'
/Users/el/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems.rb:283:in `find_spec_for_exe': can't find gem railties (>= 0.a) with executable rails (Gem::GemNotFoundException)

I tried the create new rails app command and had the same error as below;
$ rails new tracking-app-api --api --database=postgresql
Traceback (most recent call last):
    2: from /Users/el/.rbenv/versions/2.6.5/bin/rails:23:in `<main>'
    1: from /Users/el/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems.rb:302:in `activate_bin_path'
/Users/el/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems.rb:283:in `find_spec_for_exe': can't find gem railties (>= 0.a) with executable rails (Gem::GemNotFoundException)

I ran the command $ gem update --system  and currently have:
gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 3.2.3
  - RUBY VERSION: 3.0.2 (2021-07-07 patchlevel 107) [x86_64-darwin18]
  - INSTALLATION DIRECTORY: /Users/el/.rvm/gems/ruby-3.0.2
  - USER INSTALLATION DIRECTORY: /Users/el/.gem/ruby/3.0.0
  - RUBY EXECUTABLE: /Users/el/.rvm/rubies/ruby-3.0.2/bin/ruby
  - GIT EXECUTABLE: /usr/local/bin/git
  - EXECUTABLE DIRECTORY: /Users/el/.rvm/gems/ruby-3.0.2/bin
  - SPEC CACHE DIRECTORY: /Users/el/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Users/el/.rvm/rubies/ruby-3.0.2/etc
  - RUBYGEMS PLATFORMS:
     - ruby
     - x86_64-darwin-18
  - GEM PATHS:
     - /Users/el/.rvm/gems/ruby-3.0.2
     - /Users/el/.rvm/rubies/ruby-3.0.2/lib/ruby/gems/3.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/el/.rvm/gems/ruby-3.0.2/bin
     - /Users/el/.rvm/gems/ruby-3.0.2@global/bin
     - /Users/el/.rvm/rubies/ruby-3.0.2/bin
     - /Users/el/.rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /Users/el/.rvm/bin

But I keep having the same error. I am using macOS Mojave version 10.14.5
Thanks for your help.

A: I ran gem install rails and it fixed the issue. This is because I upgraded Rails before upgrading Ruby and as such my gem file did not have the rails gem. So I think it is advisable to always upgrade Ruby before upgrading Rails.

A: Try this:
bundle install --path vendor/bundle


text:
Q: how to cheack first character of text input is X if length is 6 using Jquery I wanted to validate a HTML text box using Jquery...in that text box i wanted to accept only numbers, if the length is 6-it must contain only numiricals and if legth is 7 it must conain alphabet X at the beginning.
<input type="text" class="stid" id="stn" name="stn"  maxlength="7" placeholder="Number should be 7 digits followed by letter X" required>

I tried the application using java script its working fine but how to implement using JQuery.
my javascript code
var textBox = document.getElementById("stn");
    var textLength = textBox.value.length;
    if((textLength < 7 || textLength > 7))
    {
    document.getElementById("name").innerHTML="Student Number should be 7 digits if it not follwed by x";
    return false;
    }
    else{
    if((textLength < 6 ))
    {
    //<!--to check the first letter is x in student number-->
    var firstChar = document.getElementById("stn").value.charAt(0);
    if( firstChar !== "x" && firstChar !== "X")
    {
                                                                                document.getElementById("name").innerHTML="error message,";
        return false;
    }
    }
    }

How to implement this with Jquery?

A: I think you're looking for something like this:
var length = $('#stn').val().length;
if( length != 7 ){
    $('#name').html('Student Number should be 7 digits if it not follwed by x');
}else if(length < 6){
    var firstChar = $('#stn').val().value.charAt(0);
    if(firstChar != 'x' && firstChar != 'X'){
         $('#name').html('error message');
    }
}

But like this the second conditional will never be true, I think you want this:
    var length = $('#stn').val().length;
    if(length < 6){
        var firstChar = $('#stn').val().value.charAt(0);
        if(firstChar != 'x' && firstChar != 'X'){
             $('#name').html('error message');
        }
    }else if( length != 7 ){
        $('#name').html('Student Number should be 7 digits if it not follwed by x');
    }

A: I'm going to post code to make a point.  Toni's answer is everything you need, and is much more efficiently coded.  I'm posting mine because it doesn't translate your logic and make it more concise, in an attempt to draw a distinction between "porting to jQuery" and "coding well."  Toni's answer does both.  Mine will show your exact logic, using jQuery:
var textBox = $("#stn");
var textLength = textBox.val().length;
if((textLength < 7 || textLength > 7))
{
    $("#name").html("Student Number should be 7 digits if it not follwed by x");
    return false;
}
else
{
    if((textLength < 6 ))
    {
        //<!--to check the first letter is x in student number-->
        var firstChar = $("#stn").val().charAt(0);
        if( firstChar !== "x" && firstChar !== "X")
        {
            $("#name").html("error message,");
            return false;
        }
    }
}

Even in my case, I neatened up your code by fixing spacing.  My point is that jQuery doesn't necessarily do much for you.
If you want to take advantage of JavaScript's regex utility, you can shorten this considerably:
var val = document.getElementById("stn").value;
if (!val.match(/[xX]?[0-9]{6}/)) {
    document.getElementById("name").innerHTML = "Student number should be 6 digits with an optional x or X in front";
    return false;
}

Rewriting this in jQuery shows very little difference:
var val = $("#stn").val();
if (!val.match(/[xX]?[0-9]{6}/)) {
    $("#name").html("Student number should be 6 digits with an optional x or X in front");
    return false;
}

}


text:
Q: Freestanding functions in C# Being a C++ programmer, every time I work with C# I wonder why it lacks support for freestanding functions; in other words: functions that are not part of any class. I really miss this feature, because standalone functions allow to add functionality to classes without requiring full private access, avoiding hard-to-maintain monolith classes. Furthermore, it allows extending third party libraries. I know you can use a static class, but the class name is totally irrelevant, making the client code unnecessarily verbose.
For example. I want to create a helper function to count the words in a string. How can I avoid having to write "StringHelperClass.CountWords();" in the client code? StringHelperClass acts as a namespace, only I cannot write "using StringHelperClass;". I am forced to repeat "StringHelperClass" with every usage, whereas it is obvious that it is a string helper function, as its only parameter is a string.
Is there a way to extend a class' functionality, while keeping the client code concise?

A: Edit: note that since the using static .... directive was added in C# 6, this can largely be considered an equivalent feature. Just use regular .NET static methods, then use a using static directive, and those methods are immediately available to you.

The better question would be:
"Why should it include it?"
Given that C# holds together pretty well without freestanding functions, what is the requirement to add them? In particular, static utility classes work fine for hosting such (either as regular or extension methods), and allow simple disambiguation when conflicts arise.
It also (as OregonGhost notes in the comments) helps modularize the code, preventing death-by-IntelliSense etc.
So: why add them? What is the problem (in C#) that isn't already solved?

A: I agree that it's a feature I find lacking in C#. The main reason is verbosity of using the functions. The class name acts as a namespace, but there's no way of simply 'using' that namespace at the start of a code file. So for example if you want to write OpenGL in C# you would have to type things like: OpenGL.glClearDepth(1.0f); OpenGL.glEnable(GL_DEPTH_TEST);, etc. I know it probably has something to do with the basic concept of making everything a class, but I don't really like languages that force you to do things a certain way. Of course that's maybe the reason I don't really use C# unless I have no other choice (like at work).


text:
Q: What is the limit of $ \lim_{x\to 0}( \sin(x)/x )^{1/(1-\cos x)} $ What is the limit of
$$ \lim\limits_{x\to 0}\left( \frac{\sin x}{x} \right)^{\frac{1}{1-\cos x}} $$
By applying L'Hôpital's rule many times, I find the limit is $ e^{-\frac{1}{3}} $. Are there other methods more straightforward than mine?

A: Let $$f(x) = \left(\frac{\sin(x)}{x}\right)^{1/(1-\cos(x))}$$
For $|x| < \pi$, $\sin(x)/x > 0$ and
$$\log(f(x)) = \frac{\log(\sin(x)/x)}{1 - \cos(x)}$$
Now use Maclaurin series: $$\frac{\sin(x)}{x} = 1 - \frac{x^2}{6} + \ldots $$
so $$ \log \left(\frac{\sin(x)}{x}\right) = - \frac{x^2}{6} + \ldots $$
while
$$1 - \cos(x) = \frac{x^2}{2} + \ldots $$
so
$$ \lim_{x \to 0} \log(f(x)) = -\frac{1}{3}$$
and thus
$$ \lim_{x \to 0} f(x) = \exp(-1/3)$$

A: We have
$$\left( \frac{\sin x}{x} \right)^{\frac{1}{1-\cos x}}
=\left[\left( 1-\left(1-\frac{\sin x}{x}\right) \right)^{\frac1{\left(1-\frac{\sin x}{x}\right)}}\right]^{\frac{1-\frac{\sin x}{x}}{1-\cos x}} \to (e^{-1})^\frac13=e^{-\frac13}$$
indeed
$$\frac{1-\frac{\sin x}{x}}{1-\cos x}=\frac{\frac16 x^2+o(x^2)}{\frac12x^2+o(x^2)}\to \frac13$$

A: The easiest way is to use Taylor expansion:
\begin{align}\left( \frac{\sin x}{x} \right)^{\frac{1}{1-\cos x}}&=\exp\left(\frac{1}{1-\cos x}\ln\left(\frac{\sin x}{x}\right)\right)\\&=\exp\left(\frac{1}{\frac{x^2}{2}+o(x^2)}\ln\left(1-\frac{x^2}{6}+o(x^2)\right)\right)\\&\sim \exp\left(\frac{-x^2/6}{x^2/2}\right)=e^{-1/3}\end{align}


text:
Q: ld.exe cannot find cannot find -lboost_system or -lboost_filesystem Doing this on Windows, using mingw g++ compiler version 8.1.0
I'm trying to write simple tester that uses boost/filesystem.hpp. I believe that  requires me to statically link libboost_filesystem.lib and libboost_system.lib, as the documentation states that the header files for these also rely on their separately compiled binaries. To create these binaries, I followed this link from the boost documentation: section 5.1 Simplified Build from Source
After this process finished, I know that in C:\boost_1_72_0\stage\lib has the following .lib files:
libboost_filesystem-vc142-mt-gd-x32-1_72.lib
libboost_filesystem-vc142-mt-gd-x64-1_72.lib
libboost_filesystem-vc142-mt-x32-1_72.lib
libboost_filesystem-vc142-mt-x64-1_72.lib
Now for the build attempt. I'm working in Visual Studio Code which shouldn't matter since I've built inside it using g++ before and other boost header only libraries. Here's the command + output
Output (command is first):
C:\mingw-w64\mingw32\bin\g++.exe -g C:\Users\pawlos.campbell\source\codepractice/c++/main.cpp -o C:\Users\pawlos.campbell\source\codepractice/c++/main.exe -Lc:/boost_1_72_0/stage/lib/ -lboost_filesystem-vc142-mt-x64-1_72 -lboost_system-vc142-mt-x64-1_72 -Ic:/boost_1_72_0/
C:/mingw-w64/mingw32/bin/../lib/gcc/i686-w64-mingw32/8.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -lboost_filesystem-vc142-mt-x64-1_72
C:/mingw-w64/mingw32/bin/../lib/gcc/i686-w64-mingw32/8.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -lboost_system-vc142-mt-x64-1_72
This tells me ld.exe can't see the libraries. I've tried shortening down to -lboost_filesystem, no dice.
Am I missing something obvious? Any suggestions are welcome...


text:
Q: mediaplayer error (1, -5001) What is the problem?
What does -5001 mean?
05-03 15:09:00.766 21171-21183/com.finnq.masil.dev V/MediaPlayer: message received msg=100, ext1=1, ext2=-5001
05-03 15:09:00.766 21171-21183/com.finnq.masil.dev E/MediaPlayer: error (1, -5001)
public Object instantiateItem(View pager, final int position) {
    View v = mInflater.inflate(R.layout.view_guide, null);
    v.setTag("video"+position);

    final VideoView video = (VideoView) v.findViewById(R.id.guide_item_video);
    LinearLayout text1 = (LinearLayout) v.findViewById(R.id.guide_item_text1);
    LinearLayout text2 = (LinearLayout) v.findViewById(R.id.guide_item_text2);
    LinearLayout text3 = (LinearLayout) v.findViewById(R.id.guide_item_text3);
    LinearLayout text4 = (LinearLayout) v.findViewById(R.id.guide_item_text4);

    int videoRawData = 0;
    if (position == 0) {
        videoRawData = R.raw.intro_01;
        text1.setVisibility(View.VISIBLE);
    } else if (position == 1) {
        videoRawData = R.raw.intro_02;
        text2.setVisibility(View.VISIBLE);
    } else if (position == 2) {
        videoRawData = R.raw.intro_03;
        text3.setVisibility(View.VISIBLE);
    } else if (position == 3) {
        videoRawData = R.raw.intro_04;
        text4.setVisibility(View.VISIBLE);
    }
    String uriPath = "android.resource://" + mCtx.getPackageName() + "/" + videoRawData;
    video.setVideoURI(Uri.parse(uriPath));
    video.setZOrderOnTop(true);
    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (viewpager.getCurrentItem() != position) {
                        video.pause();
                    }
                }
            }, 100);
        }
    });
    video.start();

    ((ViewPager) pager).addView(v, 0);
    return v;
}


text:
Q: Massively moving favorites from one folder to another in Google Chrome Version 73.0.3683.86 (64 bits) I want to massively move a bunch of favorites found with a search from one favorite folder to another, in Google Chrome Version 73.0.3683.86 (64 bits). Drag and drop isnt working and I tried to find the Google Chrome favorite folder in the root but it seems all the favorites are packed in one file. How can this be done?

A: The hand method
Open the Bookmarks Manager putting this in the address bar: chrome://bookmarks/
Select Menu -> Export Bookmarks.
Pick a place to put the file.
Open the file in TextWrangler, Notepad, or your favourite text editor that doesn't support HTTP. Make sure Word wrap is off for your sanity. You could also open this file in Chrome and use the Inspector to make this change I guess.
Hit Ctrl+F and look for the source folder name lets call it 'Source'. It should be on a line that looks a lot like this:

*Source*

<A HREF="chrome://bookmarks/" ADD_DATE="1554473476"

The last line shown is the opening words of a bookmark. The first line is of a folder. You can simply move around this data by cutting and pasting them under other folder lines.
Delete the folders you have in your Bookmark manager, or simply erase the bookmarks file
at %USER%\AppData\Local\Google\Chrome\User Data\Default
Go back to the bookmark manager and re-import your bookmarks.
The app method
If it's going to be easier with drag and drop support, just download this extension.
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=2ahUKEwjMu-_Dk7nhAhW1WxUIHQU7DlYQFjAAegQIAhAB&url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Fbookmark-manager%2Fidakfiahffeejfhghndaboolmmhbnepn&usg=AOvVaw00unx2IXb3Qx4wfvWi9GwC


text:
Q: Advice for a physics undergrad student I am currently a first year student studying Theoretical Physics. This summer I had a mind to try and become well versed on the topics of multivariable/single variable calculus and linear algebra, as I consider them to be a necessary foundation on the road to building an advanced mathematical knowledge.
Currently I have taken a full year of linear algebra and a module in single variable and advanced calculus. I was recommended the books Advanced Calculus (Loomis and Sternberg) and Steven Romans Linear Algebra, however I feel the latter may be a bit out of my reach at the moment.
I would greatly appreciate some advice from someone more experienced who also once stood where I am currently. Thank you in advance!


text:
Q: Increase SQL Query Performance Sql:
select distinct DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as Date,
(select count(*) from Raw_Mats A where DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0)) as Total,
(select count(*) from Raw_Mats B where DateAdd(Day, DateDiff(Day, 0, B.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) and B.status='Solved') as Delivered,
(select count(*) from Raw_Mats C where DateAdd(Day, DateDiff(Day, 0, C.Receive_date), 0)=DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) and C.status='Pending') as UnDelivered
from Raw_Mats m where m.Receive_date between '2011-07-01' and '2011-07-21'

How to increase the performance of the above query. It is taking 44 secs . wanna make it less than 10 secs
Thanks

A: Do you have an index on both Receive_date and status? (not an index on each, combined)
Also:

*

*You have have 4 touches in the table which means the query will scale at least O(4n).
By using COUNT(CASE) you can remove Delivered and UnDelivered subqueries

*The simple count subquery isn't needed either

*You need GROUP BY. YOur DISTINCT is a work around for that

*BETWEEN is >= and <= which isn't the usually correct for dates with times

I've used a subquery here for clarity but it doesn't matter:
select
   DateOnly as Date,
   COUNT(*) AS Total,
   COUNT(CASE WHEN status='Solved' THEN 1 END) AS Delivered,
   COUNT(CASE WHEN status='Pending' THEN 1 END) AS UnDelivered
from
   (
   SELECT
       DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as DateOnly,
       status
   FROM
      Raw_Mats
   WHERE
      Receive_date >= '2011-07-01' AND Receive_date < '2011-07-21'
   ) T
 GROUP BY
   DateOnly

Edit, without subquery.
I started with a subquery because I thought it's be more complex than expected and didn't bother taking it out...
select
   DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0) as Date,
   COUNT(*) AS Total,
   COUNT(CASE WHEN status='Solved' THEN 1 END) AS Delivered,
   COUNT(CASE WHEN status='Pending' THEN 1 END) AS UnDelivered
from
   Raw_Mats
WHERE
   Receive_date >= '2011-07-01' AND Receive_date < '2011-07-21'
GROUP BY
   DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0)

A: Divide and conquer: Just try each part of your sql as a separate statement and you'll find out which part is slow. If you have sub-selects and functions there is a good chance, that the server need temp-tables to perform the select, if you haven't got enough memory (or a large dataset or configured your sql server to do so), this temp-objects are swapped to disk, which makes it slow too.

A: Too many sub queries man! Get rid of some of them and it will help. Also you should not use functions on both sides in your sqls.
For example:
where DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0)=
              DateAdd(Day, DateDiff(Day, 0, m.Receive_date), 0)

In this specific case the db engine will have to go through all the rows to evaluate DateDiff(Day, 0, A.Receive_date) and DateAdd(Day, DateDiff(Day, 0, A.Receive_date), 0) then compare it with the right hand side which also is a function! This simply is a disaster.
Also, do you have indexes on Receive_date? If not add it.


text:
Q: How to set custom email settings automatically Im trying to change how email clients auto add my mail server settings. How would i change the default settings for my mail server to custom values that i set?
Thunderbird and other mail clients retrieve the mail servers settings whether its SSL, TLS, Server name, so on. How would i make it so when someone uses my email server, it automatically uses SSL and sets the incoming an outgoing setting to my preference.

A: What to do to make Thunderbird use automatic settings is described on this page:

*

*https://developer.mozilla.org/en/Thunderbird/Autoconfiguration


text:
Q: How to process geonames city data in Node.JS So I understand that this isn't the traditional way to share code but seeing how there isn't anything on the stack about how to accomplish such a task - I figured I'd share.
To further explain, I looked everywhere for an easy to use Node.JS module to process geonames data into a mongo database. The select few projects I found turned out to be a bust. Perhaps people aren't sharing because it really is such a simple task. With that said, I still think it could be valuable to share what I have.
The following answer will show how to process geonames data from http://geonames.org into a usable object that can then be saved into a database or just used out right.

A: var lineReader = require('line-reader');

lineReader.eachLine('./geonames-data/US/US.txt', function(line, last) {

  var city = line.split('\t').structure();

  if (city.is) { // if this is a city.

    // Delete un-needed object properties so we don't add useless info to DB.
    delete city.is;
    delete city.type;

    // Do something with the city object.
    console.log(JSON.stringify(city, true, 3) + '\n');
  }

});

Array.prototype.structure = function() {
    // from geonames readme: - P.PPL    populated place a city, town, village, or other agglomeration of buildings where people live and work
    return {
        _id: Number(this[0]),
        name: this[1],
        state: this[10],
        country: this[8],
        coordinates: [this[4], this[5]],
        timezone: this[17],
        is: ((this[6] == "P") ? true : false), // if object type is city.
        type: ((this[6] == "P") ? "city" : "other") // todo: add a parse function to parse other geonames db types
    }
}

A: To further extend the above answer. I have included an example that uses the geonames Node.JS module from Github. ( https://github.com/bugs181/geonames )
Disclaimer: I am the author of the aforementioned github repo.
This example can also be found on the Github repo.
var geonames = require('./geonames.js');

// Intialize geonames module.
geonames.init();

// 34.0500, -118.2500 - Los Angeles, California - More specifically Bunker Hill, California
// 34.057°N 118.238°W - San Francisco, California - More specifically Opera Plaza, California

geonames.city(34.0500, -118.2500, function(err, result) {
        if (err) {
                console.log("There was an error resolving coordinates.");
                console.log(err);
                return;
        }

        console.log("Result: " + JSON.stringify(result, true, 3));
});

Output:
[geonames] Resolve city from coordinates. [34.05, -118.25]
Result: {
   "city": "Bunker Hill",
   "state": "CA"
}

You may use strings for the latitude and longitude as well but you must convert them for the Mongo database. Use the Number() method to do this.
For example:
var lat = "34.0500";
var lon = "-118.2500";

geonames.city(Number( lat ), Number( lon ), function(err, result) {


text:
Q: display Youtube video content I have this script in my website: video feed
As you can see there is no additional info. However I managed to show the video title with:
html.push('
',
                  '  ',title,'
');

My question is: How can I show more than the title of the video, like stats:
number of views, video link, additional uploader content etc.
I don't need everything of course but it would be nice to show a bit more than just the video title. I have read the api documents(find here) but could not find anything, however I'm no expert so I could have overlooked something.
Thanks

A: you need this:
http://code.google.com/intl/nl-NL/apis/youtube/2.0/developers_guide_protocol.html#Retrieve_video_entry
http://gdata.youtube.com/feeds/api/videos/videoid?v=2
use on this an xml parser (xml2array) and read the data or do it with json?

A: If you look at the JSON response, you're already getting most of the information. Take a look at the reference documentation that lists out all the data and tags that are returned. You'll want to look for the equivalent JSON elements yourself since they don't seem to be documented.
For example, the description is available as the <media:description> tag in XML which shows up as the media$description element in JSON. The <yt:rating> tag has the number of likes and dislikes. However, note that the deprecated gd$rating is still used in the JSON.

A: First of all thank you guys for taking the time and effort to help me out. Because my programming skills are that of a newbie( I actualy just learned html,css) it could be that you guys have provided me with a good answer but because I'm new at this I didn't understand. So that said...
I have been looking around on the internet and I found this script
It was not what I was looking for, I could not merge it with my current script. But than I looked at the js and there it was. So I just copied and paste and it works fine now. This is what I was looking for:
var title = entry.title.$t.substr(0, 40);
var viewcount = entry.yt$statistics.viewCount;
var comments = entry.content.$t;

Again, thank you all very much.


text:
Q: javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes I have an ArrayList which contains some objects. Object is a container for login/pass.
I try to decode them because i have to serialize them into local file for recreation after another launch.
Problem is during encryption I recieve
javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1039)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:983)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)

And I completely don't understand why. In my opinion Base64 should deal with this. But maybe I don't understand properly its meaning.
I use to encrypt/deccode
public class Move
{
    private static Move instance;

    String key = "pT5IkWNR90gJo5YM";
    String initVector = "RandomInitVector";
    Cipher cipher;

    private Move()
    {
//      try
//      {
//          cipher = Cipher.getInstance("AES/CBC/NoPadding");
//      }
//      catch (NoSuchAlgorithmException | NoSuchPaddingException e)
//      {
//          e.printStackTrace();
//      }
    }

    public void saveData(ArrayList<Account> dataToSave)
    {
        try
        {
            FileOutputStream fileOut = new FileOutputStream(Config.SERIAL_FILE);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(encrypt(dataToSave));
            out.close();
            fileOut.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public ArrayList<Account> loadData()
    {
        ArrayList<Account> loadedData = new ArrayList<Account>();
        File f = new File(Config.SERIAL_FILE);
        if (f.exists())
        {
            try
            {
                FileInputStream fileIn = new FileInputStream(Config.SERIAL_FILE);
                ObjectInputStream in = new ObjectInputStream(fileIn);
                loadedData = (ArrayList<Account>) in.readObject();
                in.close();
                fileIn.close();
            }
            catch (IOException | ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            loadedData = decrypt(loadedData);
        }
        else
        {
            loadedData = new ArrayList<Account>();
        }
        return loadedData;
    }

    private ArrayList<Account> encrypt(List<Account> decrypted)
    {
        ArrayList<Account> encrypted = new ArrayList<Account>();

        try
        {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            for (int i = 0; i < decrypted.size(); i++)
            {
                try
                {
                    byte[] login = cipher.doFinal(Base64.getDecoder().decode(decrypted.get(i).getLogin().getBytes()));
                    encrypted.add(new Account(login.toString(), "pass"));
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }
        catch (InvalidKeyException | InvalidAlgorithmParameterException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException e)
        {
            e.printStackTrace();
        }
        return encrypted;
    }

    private ArrayList<Account> decrypt(List<Account> encrypted)
    {
        ArrayList<Account> decrypted = new ArrayList<Account>();

        try
        {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            for (int i = 0; i < encrypted.size(); i++)
            {
                byte[] login = cipher.doFinal(Base64.getDecoder().decode(encrypted.get(i).getLogin()));
                decrypted.add(new Account(new String(login), "pass"));
            }
        }
        catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException e)
        {
            e.printStackTrace();
        }
        return decrypted;
    }

    public static Move getMove()
    {
        if (instance == null)
        {
            instance = new Move();
        }
        return instance;
    }
}

A: AES block size is always 128bit, it must receive input in multiples of this number.
Smaller input must be padded to 16 bytes, and the type of padding specified to the algorithm.
Using "AES/CBC/PKCS5Padding" will do the trick.
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

If you use NoPadding, then you must implement your own padding for encryption, and make sure  to remove it from the resulting string in decryption.


text:
Q: The getter 'placeName' was called on null I created a class Address with the following strings
class Address{
  String placeName='';
  double latitude;
  double longitude;
  String placeId= '';
  String placeFormattedAddress= '';
  Address(
      {
        this.placeId,
        this.latitude,
        this.longitude,
        this.placeName,
        this.placeFormattedAddress,
      });

}

and I tried to get the address from google maps and then pass the value using Provider Package
class HelperMethods{
  static Future<String> findCordinateAddress(Position position, context) async {

    String placeAddress = '';

    var connectivityResult = await Connectivity().checkConnectivity();
    if(connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi){
      return placeAddress;
    }

    String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$mapKey';

    var response = await RequestHelper.getRequest(url);

    if(response != 'failed'){
      placeAddress = response['results'][0]['formatted_address'];

      Address pickupAddress = new Address();
      pickupAddress.longitude = position.longitude;
      pickupAddress.latitude = position.latitude;
      pickupAddress.placeName = placeAddress;

      Provider.of<AppData>(context, listen: false).updatePickupAddress(pickupAddress);

    }

    return placeAddress;

  }

}

but the thing is that it takes some time
so, when I try to open the page where the address will be displayed it shows the error
and it disappeared after the address is ready, so is there anyway to prevent this from happening ?
pass a different value until the address is ready ???
The getter 'placeName' was called on null.
Receiver: null
Tried calling: placeName
    String address = Provider.of<AppData>(context).pickupAddress.placeName ?? '';

and then I print or display the content of the address

A: UPDATE :
it was so easy but I couldn't see it before
just add question mark (?) after .pickupaddress

String address = Provider.of<AppData>(context).pickupAddress?.placeName ?? '';

A: You might want to use conditions in your UI code. Something like :
if(placeName != null)
  Text(placeName)

// null-aware operator
Text(placeName ?? "name is null")

// ternary operator
placeName != null ? Text(placeName) : CircularProgressIndicator()


text:
Q: On touching uppermost div selects contents of div under it - z-index property I have a strange problem though, when i click the content with z-index 20, the thing with z-index 1 gets selected in my phone.
The image has both the screen shot - the part on the right side of the image is only for illustrating my problem, as such the white gray div is behind my content div.
Can someone please rescue.
Related CSS files:
#content {
background: #000000;
background: url(../img/WireFrame_test.png) center center no-repeat;
box-shadow: 0 0 15px 15px #222222;
overflow-x: hidden;
z-index: 20;
}

.snapjs-right .snap-drawer-right {
    display: block;
    z-index: 10;
}

.snapjs-right .snap-drawer-left {
    display: block;
    right: 0;
    left: auto;
    z-index: 1;

}

As requested related HTML scripts:

...

Questions

Java

What is Java?

Uses of Inheritence?

...

my content goes here

A: Surely because "Uses of inheritance" is the only link element (other than "What is java"), it will be selected - there's nothing else to select!
Try setting the display of that element to "none" when it is hidden.

A: You could try to hook into the event when clicking / dragging on the content panel and do an event.stopPropagation(); or an event.preventDefault(); when the panel is closed.
As far as i know, you can see that coz Snap.js add's corresponding classes like (class="snapjs-right" or class="snapjs-left") to the body in order to indicate if a panel is open or not.
So first you've got to check that.
With jQuery it would look something like this:
$(document).ready(function() {
    $("#UsesofInheritence_Anchor_ID").bind("click", function() {
        if (!($('body').hasClass("snapjs-right"))){
            event.stopPropagation();
            event.preventDefault();
        }
    });
});


text:
Q: Position of 'for' preposition in sentence Which one is correct and why?

*

*Reports are important for her to know for which categories money are
spent and how to optimise it.

*Reports are important for her to know what categories money are
spent for and how to optimise it.

A: Let me copy answer from chat here for future readers with same question:
You spend money/time/etc on something, not for something.
(for is possible for another meaning that you don't need to be concerned with now.)
Therefore, neither choice below is the optimal wording.

for which categories money are spent
what categories money are spent for

Change for for on, and both are correct, with the former being more formal.

on which categories money is spent
what categories money is spent on

Also, money is spent, not are.


text:
Q: Valgrind error setting a null byte in C int length = strlen(input_str);
output_s = malloc((sizeof(char*) * totalSentences) + 1);
for (int i = 0; i < totalSentences; i++) {
  output_s[i] = malloc((sizeof(char) * sentences[i]) + 1);
}

free(sentences);

currentSentence = 0;
int currentCharacter = 0;
int firstChar = 1;
for (int i = 0; i < length; i++) {

  if (isalpha(*input_str) && (firstChar == 1)) {
    output_s[currentSentence][currentCharacter] = (char)toupper(*input_str);
    currentCharacter++;
    firstChar = 0;
  } else if (isalpha(*input_str)) {
    output_s[currentSentence][currentCharacter] = (char)tolower(*input_str);
    currentCharacter++;
  } else if (!isspace(*input_str) && !ispunct(*input_str)) {
    output_s[currentSentence][currentCharacter] = *input_str;
    currentCharacter++;
  }

  if (isspace(*input_str)) {
    firstChar = 1;
  }

  if (ispunct(*input_str)) {
    firstChar = 1;
    currentCharacter = 0;
    currentSentence++;
    input_str++;
    if (currentSentence == totalSentences) {
      break;
    }
    continue;
  }

  input_str++;
}

output_s[totalSentences] = NULL;

So I am creating an array of strings in c, and using a for loop and printf I know the strings are being created valid and it prints (null) at the end so I am assuming I am correctly setting the NULL byte at the end with output_s[totalSentences] = NULL; however when running this through valgrind it shows
==18908== Invalid write of size 8
==18908==    at 0x400BB1: camel_caser (camelCaser.c:99)
==18908==    by 0x400D45: test_camelCaser (camelCaser_tests.c:34)
==18908==    by 0x400E17: main (camelCaser_main.c:13)
==18908==  Address 0x5204538 is 24 bytes inside a block of size 25 alloc'd
==18908==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18908==    by 0x40090C: camel_caser (camelCaser.c:57)
==18908==    by 0x400D45: test_camelCaser (camelCaser_tests.c:34)
==18908==    by 0x400E17: main (camelCaser_main.c:13)

with line 57 being the line where I malloc the malloc(sizeof(char*) * totalSentences + 1) and line 99 being the line where I actually set the last byte in the array to be NULL, so I don't know if this is somehow messing up the memory earlier in the array that has caused the null to be written in a bad spot or am I not allocating enough memory to fit NULL in?

A: You definitely need that to be output_s = malloc(sizeof(char*) * (totalSentences + 1)); instead of output_s = malloc((sizeof(char*) * totalSentences) + 1);.
The code - as you have it - allocates space for totalSentences char *s, plus 1 byte. Your code wants space for totalSentences + 1 char *s. That's why valgrind gives the error that you're writing 8 bytes to a space 24 bytes into 25 bytes allocated.


text:
Q: Otsu Threshold in general I want to know if I could use the Otsu Code for a Histogram which contains other data than greyValues? I have a set of mm which multiplied by 1000 to get int values and now I want to cut off the left part of the histogram with Otsu.

A: Sure, why not? The algorithm doesn't know what the values mean, it just separates the values into two classes. You just have to make sure that the code you're using iterates over the full range of your int values.


text:
Q: How to use tf-hub models locally I,ve been trying to use a BERT model from tf-hub https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2.
import tensorflow_hub as hub
bert_layer = hub.keras_layer('./bert_en_uncased_L-12_H-768_A-12_2', trainable=True)

But problem is that it is downloading data after every run.
So i downloaded the .tar file from tf-hub  https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2
Now i'm trying to use this downloaded tar file(after untar)
I've followed this tutorial https://medium.com/@xianbao.qian/how-to-run-tf-hub-locally-without-internet-connection-4506b850a915
But it didn't work out well and there is no further infromation or script is provided in this blog post
if someone can provide complete script to use the dowloaded model locally(without internet) or can improve the above blog post(Medium).
I've also tried
untarredFilePath = './bert_en_uncased_L-12_H-768_A-12_2'
bert_lyr = hub.load(untarredFilePath)
print(bert_lyr)

Output
<tensorflow.python.saved_model.load.Loader._recreate_base_user_object.<locals>._UserObject object at 0x7f05c46e6a10>

Doesn't seems to work.
or is there any other method to do so..??

A: Hmm I cannot reproduce your problem. What worked for me:
script.sh
# download the model file using the 'wget' program
wget "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2?tf-hub-format=compressed"

# rename the downloaded file name to 'tar_file.tar.gz'
mv 2\?tf-hub-format\=compressed tar_file.tar.gz

# extract tar_file.tar.gz to the local directory
tar -zxvf tar_file.tar.gz

# turn off internet

# run a test script
python3 test.py

# running the last command prints some tensorflow warnings, and then '<tensorflow_hub.keras_layer.KerasLayer object at 0x7fd702a7d8d0>'

test.py
import tensorflow_hub as hub
print(hub.KerasLayer('.'))

A: I wrote this script using this medium article(https://medium.com/@xianbao.qian/how-to-run-tf-hub-locally-without-internet-connection-4506b850a915) as reference. I am creating a cache directory within my project and the tensorflow model is cached locally in this cached directory and I am able to load the model locally. Hope this helps you.
import os
os.environ["TFHUB_CACHE_DIR"] = r'C:\Users\USERX\PycharmProjects\PROJECTX\tf_hub'

import tensorflow as tf
import tensorflow_hub as hub
import hashlib

handle = "https://tfhub.dev/google/universal-sentence-encoder/4"
hashlib.sha1(handle.encode("utf8")).hexdigest()

embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
def get_sentence_embeddings(paragraph_array):
    embeddings=embed(paragraph_array)
    return embeddings

A: After getting information from tf-hub team they provide this solution.
Let's say you have downloaded the .tar.gz file from official tf-hub model page from download button.
You have extracted it. You got a folder which contain assets, variable and model.
You put it in your working directory.
In script just add path to that folder:
import tensroflow-hub as hub

model_path ='./bert_en_uncased_L-12_H-768_A-12_2' # in my case
# one thing the path you have to provide is for folder which contain assets, variable and model
# not of the model.pb itself

lyr = hub.KerasLayer(model_path, trainable=True)

Hope it should work for you as well. Give it a try

A: The tensorflow_hub library caches downloaded and uncompressed models on disk to avoid repeated uploads. The documentation at tensorflow.org/hub/caching has been expanded to discuss this and other cases.


text: Q: OpenVz VDS/VPS  настройки сервера для хостинrа сайтов Так и не нашел метки на hashcode.ru о настройках VDS/VPS для хостинга сайтов.Дайте пожалуйста хороший свежий мануал на установку (apache2,mysql,php,phpmyadmin)


text:
Q: Asp Net Core How to render razor components using ajax? In my razor page i can render a view component using ajax pretty easily. However razor components are much easier to work with since you can have everything in one file and less confusing when working with a self contained component. How can i do this for a razor component? Also my project is just razor pages and MVC controllers and currently using one razor component as a sidebar
public ViewComponentResult OnGetUserAsync(int id)
{
    FormInput = new FormModel(id);
    return ViewComponent("EditUser", FormInput);
}


text:
Q: What happens when I enable associated domains for my iOS app ID? I am trying to enable universal links for my existing app. It seems I have to enable associated domains to do that. The dialog sounds pretty scary as I am still not very versed in these iOS certificate/provisioning profile concepts (even though I've been working on iOS apps for a quite a while I never get used to these).
One thing I'm concerned about is, if I press OK here, would it affect the existing app that's already being used by people? For example, I have push notification feature, I am not sure what would happen once I press OK here. I don't want push notification to stop functioning on my production app.

A: App ID changes
A provisioning profile attaining Invalid status due to App ID changes does not affect any currently deployed apps that were signed with that profile. It's just an indication that the profile must be regenerated/updated to reflect changes in services and entitlements made to its associated App ID before it can again be used for code signing.
Certificate expiration or revocation
For standard developer program teams (those whose distribution method is the iOS App Store), expiration or revocation of a code signing certificate does not affect any apps that were signed with that certificate (this includes development builds, beta test builds, and live App Store apps). Its just an indication that the profile must be regenerated/updated to be associated with a new, valid certificate.
https://developer.apple.com/library/content/qa/qa1878/_index.html


text:
Q: Is "grounds" ever used for things other than coffee? I've never seen the word grounds (meaning sediment/dregs; definition 12 only) used to describe anything other than coffee; are there any other usages of grounds of that meaning, or has it become a coffee-word?

12.  grounds, dregs or sediment: coffee grounds.

A: A Concise Etymological Dictionary of the English Language (Walter W. Skeat, 1910) says grounds comes not from having being ground, but from being left over at the bottom.

grounds, dregs. (E.) So called from being at the bottom. Cf. Gael. grunndas, lees, from grunnd, bottom., ground; Irish gruntas, dregs, from grunnt, the bottom.

An 1825 patent talks of:

an improved apparatus for the purpose of beneficially separating the infusion of tea or coffee from the grounds or dregs.

A French and English dictionary (Randle Cotgrave, 1673) translates:

Fondrilles: The grounds, lees; or dregs of liquor.

There are definitions of sediment and faeces that give grounds as a synonym.
The justice of the peace, and parish officer, Volume 2 (Richard Burn, 1814):

Penalty on brewer receiving stale beer grounds, or mixing with any liquor except malt and hops, 100l.

Beer and ale grounds were not uncommon in recipes, laws for unscrupulous landlords, instructions for making files, as an ingredient for sloughing ulcer treatments, medical comparisons with vomit.
But nowadays, it is chiefly applied to coffee:

A: Nay, it is not a coffee word only; behold: Chicory Grounds!
In my opinion, chicory is a coffee substitute, so "grounds" remains a "coffee word" still.


text:
Q: Concatenate string and number in batch file How to concatenate number and string in for loop?
I've tried like this but it doesn't work:
SET PATH=C:\file
FOR /L %%x IN (1,1,5) DO (
    SET "NUM=0%%x"
    SET VAR=%PATH%%NUM%
    ECHO %VAR%
)

A: Modify your code like this:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET PATH=C:\file
FOR /L %%x IN (1,1,5) DO (
    SET "NUM=0%%x"
    SET VAR=%PATH%!NUM!
    ECHO !VAR!
)

You always have to use SETLOCAL ENABLEDELAYEDEXPANSION and !...! instead of %...% when working with variables which are modified inside a loop.

A: You'll need delayed expansion to accomplish that:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET FILEPATH=C:\file
FOR /L %%x IN (1,1,5) DO (
    SET "VAR=%FILEPATH%0%%x"
    ECHO !VAR!
)
ENDLOCAL & SET VAR=%VAR%

You do not need the interim variable NUM, you can concatenate the string portions immediately.
You should never change variable PATH as this is used by the system. Hence I changed it to FILEPATH.
Since SETLOCAL creates a new localised environment block, all variables defined or changed in there cannot be seen outside of that block. However, the last line in the above code demonstrates how the last concatenated value can be passed beyond ENDLOCAL.


text:
Q: ALL Prime Numbers Within 2 Columns of Number Pyramid - Proof? I was arranging numbers putting them in different orders when I happened to build a pyramid and noticed that two columns of the pyramid seemed to contain all of the prime numbers. Not just some of them, but all of the first hundred primes at least.
Considering how rare I thought that might be, I'm bringing it here for consideration.
I began with the numbers 5, 6, 7 at top. Then going diagonal to the left for 5, I did 5*2, then 5*3, etc as the left side of the triangle. On the right I did 7*1, then 7*2, etc going down the right side of the triangle.
This means the top row is 5, 6, 7. The next row is 10, 11, 12, 13, 14. The next is 15, 16, 17, 18, 19, 20, 21... and so on.

If you look at the columns under 5 and 7 they contain ALL of the prime numbers. I'm geeking out a bit.. has this been discovered yet?
Is there a way to create a proof that all prime numbers do NOT exist in these two columns?

A: The column under $5$ consists of all numbers of the form $6n-1$, and the column under $7$ consists of all numbers of the form $6n+1$.  All primes $> 3$ are of one of these forms.


text:
Q: Keep getting annoying warning "bind failed: EADDRINUSE (Address already in use)" I'm connecting a mobile with a java aplication but I keep getting this warning:

01-05 13:19:30.759: W/System.err(3371): java.net.BindException: bind
  failed: EADDRINUSE (Address already in use)
01-05 13:19:30.759: W/System.err(3371):   at
  libcore.io.IoBridge.bind(IoBridge.java:89)
01-05 13:19:30.759: W/System.err(3371):   at
  java.net.PlainSocketImpl.bind(PlainSocketImpl.java:150)
01-05 13:19:30.759: W/System.err(3371):   at
  java.net.ServerSocket.bind(ServerSocket.java:318)
01-05 13:19:30.759: W/System.err(3371):   at
  java.net.ServerSocket.bind(ServerSocket.java:281)
01-05 13:19:30.759: W/System.err(3371):   at
  com.example.informativoapp.ConnectThread.run(ConnectThread.java:32)
01-05 13:19:30.759: W/System.err(3371): Caused by:
  libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in
  use)
01-05 13:19:30.759: W/System.err(3371):   at
  libcore.io.Posix.bind(Native Method)
01-05 13:19:30.759: W/System.err(3371):   at
  libcore.io.ForwardingOs.bind(ForwardingOs.java:39)
01-05 13:19:30.759: W/System.err(3371):   at
  libcore.io.IoBridge.bind(IoBridge.java:87)
01-05 13:19:30.759: W/System.err(3371):   ... 4 more

I'm using this code :
Mobile code :
private ConnectedThread con;
private ConnectThread connect;

...

protected void onCreate(Bundle savedInstanceState) {
...
 connect = new ConnectThread(mHandler);

         connect.start();
}

 public void onBackPressed() {
            if(connect != null)
                connect.interrupt();
            if(con != null)
                con.interrupt();

            finish();
        }

public class ConnectThread extends Thread {

    Handler mHandler;
    private ConnectedThread con;

    public ConnectThread(Handler mHandler)
    {

        this.mHandler = mHandler;

    }

    @Override
    public void run()
    {
        while(true){
            Socket socket=null;
            try {
                ServerSocket serverSocket = new ServerSocket();
                serverSocket.setReuseAddress(true);
                serverSocket.bind(new InetSocketAddress(4200));
                socket = serverSocket.accept();

                Log.i("conex", "Conectou");

                mHandler.obtainMessage(3,socket).sendToTarget();

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

}

handler execute it :
                    con = new ConnectedThread((Socket)msg.obj, mHandler);
                    con.start();

A: EDITED (thanks Titus)
Probably, Your code creates socket every time.
Please try this.
    Socket socket=null;
    try {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(4200));
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    while(true){
        try {
            Log.i("conex", "Conectou");

            socket = serverSocket.accept();
            mHandler.obtainMessage(3,socket).sendToTarget();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


text:
Q: PHP: Extract value from JSON array I have an API that takes parameters from a post through JSON and I want to extract one of the values in an array for a key value pair.  However, despite many attempts, I can't get it to work.
Here is my code:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$parameters = $request["result"]["parameters"];

When I log $parameters to a text file, it log as
 {"numberofhits":"5"}

However, my efforts to capture the value 5 are not working:
$numhits = $json['numberofhits']; logs as empty.

So does:
$numhits = $parameters->numberofhits;

How can I capture the value 5 in a variable?

A: From your code above $json is a string and not a json object, your should use $request to access numberofhits
$request['numberofhits']

A: If your $parameters just shows {"numberofhits":"5"}, this means your post request just returned a json of a json. Try json decoding $parameters again like json_decode($parameters, true); and log that result. It should log the desired array.


text:
Q: Get chart name with VBA I am setting up a macro to generate a chart. I have recorded a macro while I was generating the sample chart, but now I need to have the macro working independently from the name of the chart (Chart 9 in this case)
Sheets("statistics").Select
Sheets("statistics").Range("A101:C106").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnStacked
ActiveChart.SetSourceData Source:=Range("statistics!$A$101:$C$106")
ActiveChart.ChartArea.Select
ActiveSheet.Shapes("Chart 9").Name = "waterfall"
ActiveChart.Location Where:=xlLocationAsObject, Name:="summary"
ActiveSheet.ChartObjects("waterfall").Activate
ActiveSheet.Shapes("waterfall").IncrementLeft 80
ActiveSheet.Shapes("waterfall").IncrementTop -2200
ActiveSheet.ChartObjects("waterfall").Activate
ActiveSheet.Shapes("waterfall").ScaleWidth 1.6025463692, msoFalse, msoScaleFromTopLeft
ActiveSheet.Shapes("waterfall").ScaleHeight 1.6084106153, msoFalse, msoScaleFromTopLeft
ActiveSheet.ChartObjects("waterfall").Activate
ActiveChart.Legend.Select
Selection.Delete
ActiveSheet.ChartObjects("waterfall").Activate
ActiveChart.SeriesCollection(1).Select
Selection.Format.Fill.Visible = msoFalse
ActiveChart.SeriesCollection(2).Select
ActiveChart.SeriesCollection(2).Points(6).Select
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent3
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Solid
End With
ActiveChart.SeriesCollection(2).Points(1).Select
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent3
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Solid
End With
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent1
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Transparency = 0
    .Solid
End With
ActiveChart.SeriesCollection(2).Points(5).Select
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent1
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Solid
End With
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.RGB = RGB(255, 0, 0)
    .Transparency = 0
    .Solid
End With
ActiveChart.SetElement (msoElementDataLabelCenter)
ActiveChart.SeriesCollection(2).Points(1).Select
ActiveChart.ChartArea.Select
ActiveChart.ChartArea.Select
ActiveChart.SeriesCollection(2).Points(1).Select
ActiveChart.PlotArea.Select
ActiveChart.SeriesCollection(2).Select
ActiveChart.SetElement (msoElementDataLabelCenter)
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleHorizontal)
Selection.Caption = "hrs"
ActiveChart.Axes(xlValue).AxisTitle.Select
Selection.Left = 7
Selection.Top = 13.028

I have tried
Sheets("statistics").Range("A101:C106").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnStacked
ActiveChart.SetSourceData Source:=Range("statistics!$A$101:$C$106")
ActiveChart.ChartArea.Select
Set ThisChart = ActiveChart
ActiveSheet.Shapes(ThisChart).Name = "waterfall"

but it is not working

A: Try the code below, it will loop through all existing ChartObjects in "statistics" worksheet, and if it finds a chartobject with a name of "Chart 9" it will rename it to "waterfall".
Note: you could use a similar approach to create the chart, without the need to use Select, ActiveSheet and ActiveChart.
Code
Option Explicit

Sub RenameExistingChart()

Dim ChtObj As ChartObject

For Each ChtObj In Worksheets("statistics").ChartObjects
    If ChtObj.Name = "Chart 9" Then
        ChtObj.Name = "waterfall"
    End If
Next ChtObj

End Sub

Edit 1: create the chart with ChtObj:
Set ChtObj = Worksheets("statistics").ChartObjects.Add(Left:=100, Top:=100, _
                                    Width:=100, Height:=100) ' <-- just default settings , modify later
With ChtObj
    .Chart.ChartType = xlColumnStacked
    .Chart.SetSourceData Source:=range("statistics!$A$101:$C$106")
    .Name = "waterfall"

    With .Chart.SeriesCollection(2).Format.Fill ' modify fill for series (2)
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent3
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = 0
        .Solid
    End With

    .Chart.SeriesCollection(1).ApplyDataLabels ' add data lables to series (1)

End With

A: You could use something like this:
Sub ChartStuff()
Dim cht As Shape
Range("A101:A106").Select
ActiveSheet.Shapes.AddChart.Select
Set cht = ActiveSheet.Shapes(1)
cht.Name = "waterfall"
End Sub

Hope this helps!

A: Dealing with charts in VBA is a little complicated.
When you use Addchart, Selection will be a ChartArea
A ChartArea is part of a Chart which is part of a ChartObject
The name of a chart you see is in fact the name of the ChartObject
You can do something like this:
Range("A101:A106").Select
ActiveSheet.Shapes.AddChart.Select

Dim ca As ChartArea, ch As Chart, co As ChartObject
Set ca = Selection
Set ch = ca.Parent
ch.ChartType = xl3DColumn
Set co = ch.Parent
co.Name = "waterfall"
Debug.Print ca.Name, ch.Name, co.Name

A: Create a function that you call from within the sub, that sends the name of the active chart, for example:
Function actchart(ActiveChart As String) As String
  actchart = ActiveChart
End Function

And then from within your sub, you can replace, as an example, where you have:
ActiveSheet.Shapes("Chart 9").Name = "waterfall"

with
ActiveSheet.Shapes(actchart(ActiveChart.Parent.Name)).Name = "waterfall"

This worked for me with the same issue! Hope it helps.


text:
Q: How to parse parameter pack as template parameter everyone.Recently I want to write a function to count time consumption in most common cases.
template<typename ReturnType, typename... ArgList>
int64_t TimeCount(function<ReturnType(ArgList...)> f, ArgList... args) {
    auto t0 = chrono::high_resolution_clock::now();
    f(std::forward<ArgList>(args)...);
    auto t1 = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(t1 - t0).count();
    cout << "cost " << duration << "ms " << endl;
    return duration;
}

But with the code above, only somthing likecandidate template ignored: could not match 'function<type-parameter-0-0 (type-parameter-0-1...)>' against 'void (*)(int (*)(std::vector<long> &, int, int), std::vector<long> &, int, int)' can I get, Is there any way to make the code work correctly?
Thanks for reading.

A: Issues with
template <typename ReturnType, typename... ArgList>
int64_t TimeCount(std::function<ReturnType(ArgList...)> f, ArgList... args)

are

*

*that ArgList should be deduced from 2 places and should be identical.

*lambda/function pointers are NOT std::function, and disallow deduction.

You might use instead:
template <typename F, typename... ArgList>
int64_t TimeCount(F f, ArgList&&... args)