text:
Q: Android Architecture Components: bind to ViewModel I'm a bit confused about how data binding should work when using the new Architecture Components.
let's say I have a simple Activity with a list, a ProgressBar and a TextView. the Activity should be responsible for controlling the state of all the views, but the ViewModel should hold the data and the logic.
For example, my Activity now looks like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);

    binding.setViewModel(listViewModel);

    list = findViewById(R.id.games_list);

    listViewModel.getList().observeForever(new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });

    listViewModel.loadGames();
}

private void setUpList(List<Game> items){
    list.setLayoutManager(new LinearLayoutManager(this));
    GameAdapter adapter = new GameAdapter();
    adapter.setList(items);
    list.setAdapter(adapter);
}

and the ViewModel it's only responsible for loading the data and notify the Activity when the list is ready so it can prepare the Adapter and show the data:
public int progressVisibility = View.VISIBLE;

private MutableLiveData<List<Game>> list;

public void loadGames(){

    Retrofit retrofit = GamesAPI.create();

    GameService service = retrofit.create(GameService.class);

    Call<GamesResponse> call = service.fetchGames();

    call.enqueue(this);
}

@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        setList(response.body().data);

    }
}

@Override
public void onFailure(Call<GamesResponse> call, Throwable t) {

}

public MutableLiveData<List<Game>> getList() {
    if(list == null)
        list = new MutableLiveData<>();
    if(list.getValue() == null)
        list.setValue(new ArrayList<Game>());
    return list;
}

public void setList(List<Game> list) {
    this.list.postValue(list);
}

My question is: which is the correct way to show/hide the list, progressbar and error text?
should I add an Integer for each View in the ViewModel making it control the views and using it like:
<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibility}" />

or should the ViewModel instantiate a LiveData object for each property:
private MutableLiveData<Integer> progressVisibility = new MutableLiveData<>();
private MutableLiveData<Integer> listVisibility = new MutableLiveData<>();
    private MutableLiveData<Integer> errorVisibility = new MutableLiveData<>();

update their value when needed and make the Activity observe their value?
viewModel.getProgressVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        progress.setVisibility(visibility);
    }
});

viewModel.getListVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        list.setVisibility(visibility);
    }
});

viewModel.getErrorVisibility().observeForever(new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer visibility) {
        error.setVisibility(visibility);
    }
});

I'm really struggling to understand that. If someone can clarify that, it would be great.
Thanks

A: Here are simple steps:
public class MainViewModel extends ViewModel {

    MutableLiveData<ArrayList<Game>> gamesLiveData = new MutableLiveData<>();
    // ObservableBoolean or ObservableField are classes from
    // databinding library (android.databinding.ObservableBoolean)

    public ObservableBoolean progressVisibile = new ObservableBoolean();
    public ObservableBoolean listVisibile = new ObservableBoolean();
    public ObservableBoolean errorVisibile = new ObservableBoolean();
    public ObservableField<String> error = new ObservableField<String>();

    // ...

    // For example we want to change list and progress visibility
    // We should just change ObservableBoolean property
    // databinding knows how to bind view to changed of field

    public void loadGames(){
        GamesAPI.create().create(GameService.class)
            .fetchGames().enqueue(this);

        listVisibile.set(false);
        progressVisibile.set(true);
    }

    @Override
    public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
        if(response.body().response.equals("success")){
            gamesLiveData.setValue(response.body().data);

            listVisibile.set(true);
            progressVisibile.set(false);
        }
    }

}

And then
<data>
    <import type="android.view.View"/>

    <variable
        name="viewModel"
        type="MainViewModel"/>
</data>

...

<ProgressBar
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.progressVisibile ? View.VISIBLE : View.GONE}"/>

<ListView
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:visibility="@{viewModel.listVisibile ? View.VISIBLE : View.GONE}"/>

<TextView
    android:id="@+id/main_list_error"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{viewModel.error}"
    android:visibility="@{viewModel.errorVisibile ? View.VISIBLE : View.GONE}"/>

Also notice that it's your choice to make view observe
ObservableBoolean : false / true
    // or
ObservableInt : View.VISIBLE / View.INVISIBLE / View.GONE

but ObservableBoolean is better for ViewModel testing.
Also you should observe LiveData considering lifecycle:
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    listViewModel.getList().observe((LifecycleOwner) this, new Observer<List<Game>>() {
        @Override
        public void onChanged(@Nullable List<Game> items) {
            setUpList(items);
        }
    });
}

A: Here are simple steps to achieve your point.
First, have your ViewModel expose a LiveData object, and you can start the LiveData with an empty value.
private MutableLiveData<List<Game>> list = new MutableLiveData<>();

public MutableLiveData<List<Game>> getList() {
    return list;
}

Second, have your view (activity/fragment) observe that LiveData and change UI accordingly.
listViewModel = ViewModelProviders.of(this).get(ListViewModel.class);
listViewModel.data.observe(this, new Observer<List<Game>>() {
    @Override
    public void onChanged(@Nullable final List<Game> games) {
        setUpList(games);
    }
});

Here it is important that you use the observe(LifecycleOwner, Observer) variant so that your observer do NOT receive events after that LifecycleOwner is no longer active, basically, that means that when your activity of fragment is no longer active, you won't leak that listener.
Third, as a result of data becoming available you need to update your LiveData object.
@Override
public void onResponse(Call<GamesResponse> call, Response<GamesResponse> response) {
    if(response.body().response.equals("success")){
        List<Game> newGames = response.body().data; // Assuming this is a list
        list.setValue(newGames); // Update your LiveData object by calling setValue
    }
}

By calling setValue() on your LiveData, this will cause onChanged on your view's listener to be called and your UI should be updated automatically.


text:
Q: Oracle APEX - numeric value error in a filter I have an Oracle APEX application. It has a numeric column, and the default filter setup will allow the user to enter any text in the filter value. This results in a server-side error, which is not very user friendly.
Is there any way to restrict the values entered in the filter to numeric only values?

A: Did you set item's type to "Number field"? Help says

Displays a number field. This item type automatically validates that the value is a number.

Or, you could use "Text field" as its type and create a validation. For example, a function body that returns error text:
if not regexp_like (:P1_THAT_ITEM, '^\d+$') then
   return 'Enter a number';
end if;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows isn't generating Python Compiled Files I'm currently on a Windows 7 environment developing a Pyramid web application.  I had been developing this app on my Mac, but that's recently died, so I've had to move to my Windows machine.
I've set up everything I need; Python 2.7, Pyramid, pyramid_beaker, MongoDB, mongoengine, etc.
It seemed to be working while I was editing the templates.  However, when I tried editing a view to add a new page to the app, it would not seem to be able to find it.  I added the following routes:
config.add_route('info_about','/info/about')
config.add_route('info_contact','/info/contact')
config.add_route('info_copyright','/info/copyright')
config.add_route('info_privacy','/info/privacy')
config.add_route('info_terms','/info/terms')

...which are handled by a view_config decorator like so:
@view_config(route_name='info_about', renderer="myproject:templates/info/about.mako", permission='all')
def info_about(request):
    <code goes here>

This is in an info.py file in the view subfolder (which does contain an __init__.py file).  This method has worked when I was on my Mac, but now that I've tried on Windows, it doesn't seem to work (it throws a 404 Not Found page up when trying to access it).
After a little investigating, I found that the .pyc version of info.py (the compiled version) does not exist.  info.py is new and was added on the Windows machine.  As a test, I tried editing a file created on the Mac and restarting the test server.  It hasn't modified the .pyc counterpart either, so I'm led to assume that Windows is not producing the .pyc version of the python files.
Is this a common problem, and more importantly, is there a solution? (I have to assume there is...)

A: Sorry, your question is not clear enough. It seems you have some kind of read/write permission problems, and generating *.pyc has nothing to do with it.
*.pyc contains Python bytecode, in fact it is there just to load the original *.py files faster. Every time Python successfully reads a *.py file and is able to write(!) into the same directory, it creates a corresponding *.pyc file.
For more information see compiled python files.


text:
Q: React JS display clicked table row I am currently trying to learn react by building a simple app that works with a JSON array by calling a certain API. I would then like to show the results of the array in a table and have the ability to click one of the rows and get the data from that row to update another part of the page.
I have successfully called the API and am showing the correct data in the table but I am struggling to figure out how to show the data after the click in another part of the page. I created a click handler event and can log information to the console but cant figure out how I would show this data on the page for the relevant row that is clicked.
So I currently have this in my page:

Below this script is another container that I would like to show the results when the table row is clicked.
So to summarize, I want to display the data from the API call in a table, upon clicking on one of the table rows I want to take the table row data and format it in another container on the page.

A: I'd move both the table-component and the display area-component into a parent component that has the responsibility of managing state. The parent component will pass a callback for handling row clicks down to the table, something along the lines of the below edits to your code example. (Heads-up: haven't slept in the past 40+ hours when writing this, due to travel..)


text:
Q: merge sound file audio and record in Widows 8 Metro Windows Store application I have two sound files that I need to merge. One is an audio file and the other is a recording file.
I am using c# to build a Metro Style App. Is there any libraries or any functionality in .net I can use to complete this?

A: Take a look to NAudio, I don't know if they have a version for Windows store apps.
An option could be to write .net web service that uses NAudio to do the job of merging the audio files and send it back to your app.


text:
Q: Oracle Function related query Why do i come across compilation errors for the code below?? Have i gone wrong in the nesting ? I get the error as encountered DECLARE when expecting BEGIN..
DECLARE
BEGIN
   DECLARE
      FUNCTION fn_Add1 (p_n1 NUMBER, p_n2 NUMBER)
      RETURN NUMBER
      AS
      BEGIN
        RETURN fn_Add2(p_n1,p_n2,40);
      END;

   DECLARE
     FUNCTION fn_Add2 (p_n1 NUMBER, p_n2 NUMBER,p_n3 NUMBER)
     RETURN NUMBER
     AS
     BEGIN
       RETURN (p_n1+p_n2+p_n3);
     END;
END;
BEGIN
   DBMS_OUTPUT.PUT_LINE (fn_Add1(20,30));
END;
/

A: Remove the nested BEGIN and DECLARE - this way it should work:
DECLARE
  FUNCTION fn_Add2 (p_n1 NUMBER, p_n2 NUMBER,p_n3 NUMBER)
  RETURN NUMBER IS
  BEGIN
      RETURN (p_n1+p_n2+p_n3);
  END;

  FUNCTION fn_Add1 (p_n1 NUMBER, p_n2 NUMBER)
  RETURN NUMBER IS
  BEGIN
     RETURN fn_Add2(p_n1,p_n2,40);
  END;

BEGIN
  DBMS_OUTPUT.PUT_LINE (fn_Add1(20,30));
END;
/

p.s.: I think it should be IS and not AS as well. Good luck!


text:
Q: Pass down component with props as prop in React Typescript I'm learning React with Typescript and hit an obstacle. I'm trying to pass a child component that has props to another child component like so:
const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
      skillsComponent={<Skills skills={skills} columns={columns}/>}
    >
    </Card>
  );
};

and use the Skills component like so:
const Card: FC<CardProps>  = ({ title, text, skillsComponent }): JSX.Element => {

  return (

{title}

            {text}

      {skillsComponent}

  )
}

{skillsComponent} gives the error Type 'Element' is not assignable to type 'FC<SkillsProps>'. Not sure what's the best solution here.

A: You don't need to bother with FC<CardProps>, or defining the return  type since that will be inferred. Typically when you build a card component you can just use a children Prop as below.
const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
    ><Skills skills={skills} columns={columns}/>
    </Card>
  );
};

interface CardProps {title:string, text:string, children:React.Node}

const Card  = ({ title, text,children }:CardProps) => {
  return (

{title}

            {children}

  )
}


text:
Q: How can I get array values from key in json file with python? Here is my JSON file:
{"name": "Nghia", "name2": ["Bao", "Tam"]}
My Python code:
file = open(jsonfile, 'r')
data = json.load(file)
key = list(data.keys())
value = list(data.values())
print(key[value.index('Nghia')])

Output: name
But the issue is I can't use key[value.index('Bao')] or key[value.index('Tam')] to get name2

A: In simple terms, the index() method finds the given element in a list and returns its position.
So here,
key = list(data.keys()) // ['name', 'name2']
value = list(data.values()) // ['Nghia', ['Bao', 'Tam']]

Now this code
print(key[value.index('Nghia')])

finds the element from this list ['Nghia', ['Bao', 'Tam']] and returns the index of that element and print it.
So above you can see in the second element of the list ['Nghia', ['Bao', 'Tam']], we have an array as element ['Bao', 'Tam']
So in order to find the the index of that element in the value list, you have to use this
print(key[value.index(['Bao', 'Tam'])])

here is the function which returns the index of an element if the element in the list is an array or string
Function takes two arguments value and item,
value is a List
item is the element of list which index needs to be find
Function returns -1 if its not found any item in the list
def findIndex(value,item):
    for elementIndex in range(0, len(value)):
        if type(value[elementIndex]) is list:
            for itemElemIndex in range(0 ,len(value[elementIndex])):
                if value[elementIndex][itemElemIndex] == item:
                    return elementIndex
        else:
            if value[elementIndex] == item:
                return elementIndex
    return -1

print(key[findIndex(value,"Tam")])

A: The issue is that you're trying to match a string to a list, which will of course not match. If you must keep the structure of your data, you need to explicitly check for both strings matching or the list containing the string. For example:
data = {"name": "Nghia", "name2": ["Bao", "Tam"]}

search_term = "Bao"

for k, v in data.items():
  if v == search_term or search_term in v:
    print("Found in " + k)
  else :
    print("Not found in " + k)

which will output
Not found in name
Found in name2


text:
Q: Make something happen every X seconds on Arduino So, I want to make a hand sanitizer. I have an ultra-sonic sensor.
Right now it works like this: when distance is lower than 5cm, it pours liquid.
What I want to do is: when distance < 5 cm, pour for 2 seconds. After the 2 second have passed, wait another 3 seconds before measuring again.
Ex: I put my hand in front on sensor, it pours liquid for 2 seconds. After that it waits for 3 seconds then it's ready to pour again if distance < 5 cm.
Thank you, it would be of much help. I really don't know how to implement a timer like this.

A: #define DISTANCE_IN_MM          50u
#define DISPENSE_DURATION_IN_MS 2000u
#define DISPENSE_TIMOUT_IN_MS   3000u

// Function declarations.
//
uint16_t ultrasonic_sensor_get_distance();
void     turn_dispenser_on();
void     turn_dispenser_off();

void loop()
{
    // Poll sensor distance. If under threshold, pour.
    //
    if (DISTANCE_IN_MM >= ultrasonic_sensor_get_distance())
    {
        turn_dispenser_on();
        delay(DISPENSE_DURATION_IN_MS);
        turn_dispenser_off();
        delay(DISPENSE_TIMOUT_IN_MS);
    }
}


text:
Q: Find the expected number of $0$'s and $1$'s before the sequence $01$ I have the following problem:

Let $X_1,X_2,...X_N$ be a sequence of independent Bernoulli random variables. Let $p\in (0,1)$ and $P(X_i=1)=p, P(X_i=0)=1-p.$ What is the expected value $T_{01}$, the number of $0$'s and $1$'s, before (and including) the sequence "$01$".

This is what I have tried to come up with so far:
Basically there are three possible "events" that I have to consider:

*

*The event that the first slot is a $1$, the next $k-1$ slots are $0$'s and the $k$-th
slot is a $1$. For example, the event could look like this:

$$\color{green}{1}\color{blue}{0000000}\color{red}{1}000$$

*The event that the first $k-1$ slots are $0$'s and the $k$-th slot is a $1$:
$$\color{blue}{0000000}\color{red}{1}001$$

*The event that the first $k-2$ slots are $1$'s the $k-1$ slot is a $0$ and the $k$-th slot is a $1$
$$\color{green}{111111111} \color{blue}{0}\color{red}{1}011$$
I know from this MIT OCW Lecture (Link) that the proabability mass function (PMF) for such an experiment is given by:
$$p_{Y_k}(t)=\begin{pmatrix}t-1 \\ k-1\end{pmatrix}p^k (1-p)^{t-k}$$
This gives the probability of $k$ events in $t$ time.
My question:
My problem comes from the fact that I don't want to find the arrival time of $k$ events. I am looking the expected value of a very specific event. The event $01$. Do I just find the probabilities of the three cases I listed above and multiply them together? Figuring out the possible cases seems like a very tedious and time consuming way to do it. How can I approach problems like this? Is there some "recipe" that I can follow that extends to similar problems such as finding $T_{101}$ (the expected numbers of $0's$ and $1's $ until the sequence $101$?
I want to add another example that I tried to solve based on the answers and the comments:
Question: Find the expected number of $0$'s and $1$'s before the sequence $11$. In other words find $E[T_{11}]$:
$$\begin{align}E[T_{11}]&=p\left(E[T_{11}] \space \lvert \space X_1=1 \right)+(1-p)\left( E[T_{11} \space \lvert \space X_1=0] \right) \\  \end{align}$$
For the first term: $$\begin{align} E[T_{11} \space \lvert \space X_1=1]&=p\left(E[T_{11} \space \lvert \space X_1=1, X_2=1] \right)+(1-p)\left(E[T_{11} \space \lvert \space X_1=1, X_2=0] \right) \\ &=\underbrace{2p}_{\text{Achieved $11$ in two trials}}+\underbrace{(1-p) (2+E[T_{11}])}_{\text{cycled back to starting state wasting two trials}} \end{align} $$
For the second term:
$$E[T_{11} \space \vert \space X_1=0]=\underbrace{1+E[T_{11} ]}_{\text{Cycled back to starting state but having wasted one trial}}$$
Combining the terms and solving for $E[T_{11} ]$:
$$\begin{align} &E[T_{11}]=p(2p+(1-p)(2+E[T_{11}]))+(1-p)(E[T_{11}]+1) \\[10pt] &\iff E[T_{11}]= 2p+p(1-p)E[T_{11}])+(1-p)E[T_11]+(1-p) \\[10pt] & \iff E[T_{11}]-p(1-p)E[T_{11}]-(1-p)E[T_{11}]=p+1 \\[10pt] &\iff E[T_{11}](1-p+p^2-1+p)=p+1 \\[10pt] & \iff E[T_{11}]=\boxed{\frac{p+1}{p^2}}\end{align}$$
Assuming the probability $p=\frac{1}{2}$
$$\implies E[T_{11}]=6$$

A: You could try the following, based on finding a recurrence relation. You can write
$$\begin{align*}
\mathbb{E}[T_{01}]
&= \mathbb{E}[T_{01}\mid X_1=1]\Pr[X_1=1]
+ \mathbb{E}[T_{01}\mid X_1=0]\Pr[X_1=0]\\
&= \frac{1}{2}\left(\mathbb{E}[T_{01}\mid X_1=1]
+ \mathbb{E}[T_{01}\mid X_1=0]\right)
\end{align*}$$
Now, you can show/check that $\mathbb{E}[T_{01}\mid X_1=1] = 1+\mathbb{E}[T_{01}]$. (Can you see why?) The other one is a bit more annoying, but similarly
$$\begin{align*}
\mathbb{E}[T_{01}\mid X_1=0] &=
\frac{1}{2}\mathbb{E}[T_{01}\mid X_1=0,X_2=0]
+ \frac{1}{2}\mathbb{E}[T_{01}\mid X_1=0,X_2=1] \\
&=  \frac{1}{2}(1+\mathbb{E}[T_{01}\mid X_1=0])
+ \frac{1}{2}\cdot 2\\
&=  \frac{1}{2}\mathbb{E}[T_{01}\mid X_1=0])
+ \frac{3}{2}
\end{align*}$$
from which $\mathbb{E}[T_{01}\mid X_1=0]=3$. Putting the two together,
$$\begin{align*}
\mathbb{E}[T_{01}]
&= \frac{1}{2}\left(1+\mathbb{E}[T_{01}] +3\right) = 2+\frac{1}{2}\mathbb{E}[T_{01}]
\end{align*}$$
from which $\mathbb{E}[T_{01}]=4$.

A: From start (state a), one toss either takes you to $0$, or you are effectively back to start, waiting for a $0$
From $0$ (state b), one toss either takes you again to $0$, or you end having obtained $01$
$\displaylines{Thus\quad a = 1 + \frac12 b + \frac12 a,\;\\ b = 1 + \frac12 b}$
Solving, we get $a = 4$

PS
If probabilities of getting $0$ is p and that of getting $1$ is $(1-p)$, exactly the same process yields
$a = \dfrac{1}{p-p^2}, \;or\; \dfrac{1}{p(1-p)}$

PPS
Regarding "recipe" for, say, first $101$, you can follow the same process extended. Taking $p = \frac12$ to illustrate, and get a concrete answer.

*

*At start (state a), we are waiting for a $1$

*Having got $1$ (state b),we are waiting for a $0$

*Having got $10$ (state c), we are waiting for a $1$
We flit between the states until we reach the destination

*

*With one toss from a  we can either go to b or remain at a

*With one toss from b we can either go to c or remain at b

*With one toss from c we can end or go back to b
$\displaylines a = 1+\frac12 a + \frac12 b\\ b =1+ \frac12 c + \frac12 b\\c =1+ \frac12 b$
which yields $a = 8$


text:
Q: data from jsonp ¿How i do (with Jquery) to obtain a specific value from this json result? for example for email
 [
 {
   address: "",
   province: "",
   firstName: "Anna",
   email: "anna@example.org",
   postalCode: "",
   key: "135",
   type: "technical",
   description: "",
   isPrimaryContact: true,
   phone: "",
   country: "",
   city: "",
   salutation: "",
   position: " Projects Leader, Academic Systems",
   lastName: ""
 }
]

I use $.ajax() , from a json in a different server.

A: If you have a JSON object, you would simply use:
var email = data.email;

Here is a full, shortened example:
 var data = {
   address: "",
   province: "",
   firstName: "Anna",
   email: "anna@example.org"
 };

alert(data.email);

If your data is really an array, you would need to use:
alert(data[0].email);

Similar shortened example:
 var data = [{
   address: "",
   province: "",
   firstName: "Anna",
   email: "anna@example.org"
 }];

alert(data[0].email);


text:
Q: Flutter xcode build failed resource fork, Finder information, or similar detritus not allowed.. Every time Every day, when I try to run my flutter project on my ios simulator, I get this error

If I run these two commands, it runs just fine
xattr -lr -Path To Project-
xattr -cr -Path To Project-
But needing to do this over and over is

*

*annoying

*hints at a larger problem.

Is there something I can do that will make it so I don't need to continually run these commands?


text:
Q: WSO2 Identity Server 5.11: Password expiry option not available as per documention I need to add password expiry feature in my application using wso2 identity server version 5.11. Referred to following documentation:https://is.docs.wso2.com/en/latest/learn/password-expiry/
As per the aforementioned document we need to download password policy authenticator which is not supported by latest IS 5.11. Also, I did not get Password Expiry option under Password Policies in resident section of identity providers.
Kindly suggest how can I add password expiry feature in wso2 IS 5.11 which will redirect my application to change password window after user password gets expire.
Thanks in Advance!

A: To do this,
Prerequsists

*

*Stop the server if it is already running.

*Download the Password Reset Enforcer code from here and build it using  mvn clean install -DskipTest

*Add the following lines to <IS_HOME>/repository/conf/deployment.toml file

    [[event_handler]]
    name= "passwordExpiry"
    subscriptions =["POST_UPDATE_CREDENTIAL", "POST_UPDATE_CREDENTIAL_BY_ADMIN", "POST_ADD_USER"]
    [event_handler.properties]
    passwordExpiryInDays= "30"
    enableDataPublishing= false
    priorReminderTimeInDays= "0"

*Check the build files and copy the authentication page (<PASSWORD_RESET_ENFORCER_ARTIFACTS>/is/pwd-reset.jsp) to the <IS_HOME>/repository/deployment/server/webapps/authenticationendpoint/ directory.

*Copy the connector (org.wso2.carbon.extension.identity.authenticator.passwordpolicy.connector-<version>.jar) to the <IS_HOME>/repository/components/dropins/ directory.

Configuring the Expiration Policy

*

*Start the Identity Server and log in.

*In the Identity section under the Main tab, click Resident under Identity Providers.

*Go to Password Expiry under Password Policies.

*Change Password Expiry In Days according to your requirements.
(By default, the Password Reset Enforcer will expire passwords in 30 days.)

*Click Update to save the changes.

Configurations

*

*Go to claims in the admin console and find http://wso2.org/claims/identity/lastPasswordUpdateTime URI or last password update claim and make it as supported by default.

*Create a new user then go to the management console and go to user-profile of the user and update the Last Password Update value to a lower value.

*Go to the Local and Outbound Authentication Configuration section in the Service Providers page of your service.

*Select the Advanced Configuration radio button option.
Add the basic authentication as the first step and Password Reset Enforcer authentication as the second step.
Select User subject identifier from this step under basic authentication.
Select Use attributes from this step under Password Reset Enforcer.

*Now try to login into the app again, you will be requested the password.

More info: https://github.com/wso2-extensions/identity-outbound-auth-passwordPolicy/blob/master/docs/config.md


text:
Q: Does async/await execution have a higher priority than setTimeout callbacks? I was writing some code where a user would click a button and the time of the next locally-visible solar eclipse would be computed.
This can be a very time-consuming calculation. So I wrote the calculation code with a couple of nested async functions, breaking all of the computations into bite-size pieces, allowing execution to yield frequently so that the user's web browser wouldn't lock up during the calculation.
Here's a grossly simplified test case of the timing issues involved, without the astronomical complexity (available on CodePen):
window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 15000;

async function workWorkWork(msg) {
  return new Promise(async (resolve) => {
    const start = performance.now();

    while (performance.now() < start + 5000) {
      await new Promise((innerResolve) => {
        let t = 0;

        for (let i = 0; i < 1e7; ++i) t += Math.sin(Math.random());

        console.log(msg || t);
        // innerResolve(); // What I thought should have been sufficient
        setTimeout(innerResolve); // What I had to do instead
      });
    }

    resolve();
  });
}

let busy = false;

function doStart() {
  if (busy)
    return;

  const button = document.getElementById('my-button');

  button.innerText = 'Started';
  button.style.background = 'red';
  busy = true;

  (async () => {
    setTimeout(() => (button.innerText = 'Busy'), 1000);
    workWorkWork('other work');
    await workWorkWork();
    busy = false;
    button.innerText = 'Start';
    button.style.background = 'unset';
  })();
}

After the user clicked the button, I wanted to wait for one second to go by before showing a busy indicator. The busy indicator was activated using a setTimeout called just before await-ing the calculation.
To my surprise, my the UI responded almost as if the async/await was blocking code. The whole calculation finished after several seconds, and then the busy indicator appeared, way too late.
Console output demonstrates that if I start up two calls of workWorkWork simultaneously, their output is interleaved in the web console, so each execution instance is properly yielding time to the other.
But the async function code doesn't yield any time to the setTimeout that was queued up before the function was called. It doesn't even let the DOM update with changes made before the async call and before the setTimeout.
The only way to get the setTimeout callback to run in a timely manner appears to be using other setTimeout calls within my async functions.
My first encounter with this problem was inside Angular code, and I figured I might be seeing an Angular-specific problem with the Angular Zone.js craziness, but I've now replicated the same problem in plain-ol' JavaScript.
Is this the behavior I should have expected? Is this documented anywhere?
Googling various combinations an permutations of async, await, setTimeout, Promise, etc., yields a lot of material which unfortunately has nothing to do with what I've run into here.
Correct behavior after clicking Start:

Button turns red, text changes to "Started".
About one second later, text changes to "Busy"
About four more seconds later, red background disappears and text changes back to "Start".

Bad behavior after clicking Start, without extra setTimeout:

Button makes no immediate change of text or color
About five seconds later, text changes to "Busy", and gets stuck that way.

A: Fulfilled promises are served via a microtask queue which gets handled BEFORE timer events.  await works off promises so it also goes before timer events.
So, if both a timer event and a promise fulfillment are both waiting to run their handlers, then the promise will get served first.
Here's some more info on the microtask queue or more specifically the PromiseJobs queue.


text:
Q: Pygame on Android: how can I double-tap to close the app without moving the rectangle The code below draws a rectangle which can be moved by touching the screen. Double-tapping the screen closes the toy app. I wonder how to improve the code so that when you double-tap to quit the app, the rectangle remains unmoved.
import pygame

def main():
    pygame.init()
    DISPLAY = pygame.display.set_mode((1000,500),0,32)
    WHITE = (255,255,255)
    blue = (0,0,255)
    DISPLAY.fill(WHITE)
    pygame.mouse.set_visible(False)
    pygame.draw.rect(DISPLAY, blue,(480,200,50,250))
    pygame.display.update()
    pygame.mouse.set_pos((480, 200))
    run = True
    clock = pygame.time.Clock()
    timer = 0
    dt = 0
    pos = 0

    while run:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if timer == 0:
                    timer = 0.001
                    # Click again before 0.5 seconds to double click.
                elif timer < 0.5:
                    # Double click happened
                    run = False
            else:
                pos = pygame.mouse.get_pos()
                DISPLAY.fill(WHITE)
                pygame.draw.rect(DISPLAY, blue, (pos[0],pos[1], 50, 250))
                pygame.display.update()

        # Increase timer after mouse was pressed the first time.
        if timer != 0:
            timer += dt
            # Reset after 0.5 seconds.
            if timer >= 0.5:
                 timer = 0

        # dt == time in seconds since last tick.
        # / 1000 to convert milliseconds to seconds.
        dt = clock.tick(30) / 1000

main()

A:
What I would like to do is to avoid that the rectangle is visually moved right before the app is closed.

Immediately before the application is closed, the state of run is set False. Don't change the position of the rectangle if run is False, respectively only change it if run:.
To handle the double-tap you have to add the addtional condition timer == 0:
def main():
    # [...]

    while run:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                # [...]

            else:
                if run and timer == 0:
                    pos = pygame.mouse.get_pos()
                DISPLAY.fill(WHITE)
                pygame.draw.rect(DISPLAY, blue, (pos[0],pos[1], 50, 250))
                pygame.display.update()

Or even better, do not draw anything if run is False:
def main():
    # [...]

    while run:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                # [...]

            elif run and timer == 0:
                pos = pygame.mouse.get_pos()
                DISPLAY.fill(WHITE)
                pygame.draw.rect(DISPLAY, blue, (pos[0],pos[1], 50, 250))
                pygame.display.update()


text:
Q: How to add H264 streaming module to Apache? I want to add the H264 streaming module to Apache. I'm on Windows using the stack WAMPserver 2.2 with Apache 2.2.22, and I have put the module (mod_h264_streaming.so) in the module directory. I've added the LoadModule code into httpd.conf but, alas, the server doesn't work (the icon shows orange). This is what I entered in httpd.conf
LoadModule h264_streaming_module modules/mod_h264_streaming.so

I have no idea what or where the problem is, and it's causing many headaches. This particular module is essential to my project. I realize this is probably vague troubleshooting, but I would greatly appreciate any advice.
Thanks in advance.

A: Step by Step
1- At first Download Visual Studio 2008 x64 SP1, be sure to install the Visual C++ 2008 x64 SP1 Redistributable Package
it can be downloaded from;
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=BA9257CA-337F-4B40-8C14-157CFDFFEE4E  (Setup this)
2- Download Apache module mod_h264_streaming from ; https://www.apachehaus.net/modules/mod_h264_streaming/ in the below.Before download Please careful about your apache version.consider it.
3- Extrach files , copy "mod_h264_streaming.so"
3- If you are using Wamp server go the C:\wamp\bin\apache\Apache2.4.4\modules and drop(add,copy what ever you say) mod_h264_streaming file to the path. If you are not using wamp go to C:/Apache24/modules/ and add mod_h264_streaming.
4- Then Go to httpd.conf (in the C:\wamp\bin\apache\Apache2.4.4\conf path) , open with notepad++ find load modules line
just like ;
LoadModule auth_basic_module modules/mod_auth_basic.so    // opened module
#LoadModule auth_digest_module modules/mod_auth_digest.so // closed module
#LoadModule authn_anon_module modules/mod_authn_anon.so

When you find the lines add this ;
 LoadModule h264_streaming_module modules/mod_h264_streaming.so

save and quit. Finally restart the apache server. Module is ready to serve you.


text:
Q: How to stop administrator password prompt on application install (OSX) How to turn off administrator password prompt on application install or other actions on mac?
I tried to put line in /etc/sudoers file:
zur4ik ALL=(ALL) NOPASSWD: ALL
where zur4ik is my username.
unfortunately it's not working: applications are asking for administrators password anyway.


text:
Q: What is the use of range() method in KeyValueStore Kafka? I want to understand the use of range method in KeyValueStore state store.
In which scenario we need to use this range method.
In Docs only one line is written.
KeyValueIterator<K,V> range(K from,K to)
Get an iterator over a given range of keys. This iterator MUST be closed after use.

How far i understand we use state store for some lookup if some record is already present we need to update it or delete it or add it depend on the requirement.
but i didn't understand the use of range method in state store.
how it's helpful in any situation (any example where this method is helpful)?


text:
Q: Word2Vec: Is it possible to train with respect to weight in NLP? I used Gensim's Word2Vec for training most similar words.
My dataset is all posts from my college community site.
Each dataset consists of like this:
(title) + (contents) + (all comments)  // String

For example,
data[0] => "This is title. Contents is funny. What so funny?. Not funny for me"

So, I have around 400,000 datas like above and make them as a vector and try to train these data via Word2Vec.
I wonder that whether it is possible to make Word2Vec consider WEIGHT, which means, if I give an weight to certain data vector, Word2Vec train this data in a way that each word in this data vector has more strong relationship(similarity).
For example, If I gave a weight 5 to dataset, I like Pizza, Chicken, the word Pizza and Chicken (or like and Pizza etc) has strong relations than other data vector's words.
Would that be possible?
Sorry for poor explanation but I'm not native english speaker. If need more detailed info, please post comment.

A: There's no such configurable weighting in the definition of the word2vec algorithm, or the gensim implementation.
You could try repeating those text examples that you want to have more influence. (Ideally, such repetitions wouldn't be back-to-back, but shuffled among the entire dataset.)
As a result, those examples will affect the underlying model's training more often, for a greater proportion of the total training time – shifting the relative positioning of the involved words, compared to less-repeated examples. That might have the end result you're seeking.


text:
Q: Visual Studio Online - Live ID vs Work Accounts We're completely upgrading our production and development environment from co-located boxes to an Azure implementation and we'll be developing using Visual Studio Online.  Up until this point our dev has occurred on a Remote Desktop environment where developers were logging into Windows server and developing on that RDP box.
We want to set this up and we have some confusion about the Account types/set up types.
It appears there are two ways to set up our Azure and two ways to set up our developers.  We are a MS partner w/ some MSDN licenses and Azure credits.
So for Azure we can use our existing MS accounts and just set up an Azure Pay As You Go (PAYG) subscription.  This was suggested to us initially but it seems weird to have the entire companies Azure environment going through an individuals live ID.  Then we saw we can sign up as an Organization now and it uses Azure AD.  We have not been using Active Directory and we're not sure how much complexity this is going to add to our administration.  Is there a discernible difference/benefit to going one way or the other?
Then, when we sign up our developers we can either have everyone sign up with their live ID's (we have MSDN w/ VS Premium credits for all developers) or we can set them up using Active Directory with Work Accounts.  Having our credits allotted in work accounts sounds like a good way to control things at first reading, but it also seems a bit more complex.  I'm wondering if there is much difference between MSDN accounts signed up w/ live IDs or AD Work Accounts.  I can't find a real comparison article or pro/con type of discussion anywhere.

A: It sounds like you have already figured out the main differences.  As an organization, I would suggest signing up for Azure as an organization.  You can do that here.  This is going to give you the management capabilities for resources typically needed by an organization.
Your developers can continue to use the MSDN subscriptions. As Dylan commented, these are not to be used for production environments.  You should consider using these for Dev/Test environments and activating your MSDN benefits.  This will save you some money.  More on that here.
Visual Studio Online will work with your Work Accounts and again give you more control over managing your online resources.  This link describes the sign-up process for both Microsoft Accounts and Work Accounts.  And if you scroll down a bit you will find your original question specifically addressed.

Finally, you can also add your Work Account(s) to your existing MSDN subscriptions if you like. This way you (and your developers) can use the same account credentials when accessing Azure Subscriptions.  Information on how to do that is available in this link.
Your Work Account subscription should be limited to personnel responsible for managing your "production" environment.
After signing up for Azure as an Organization, you can add users to the directory as described here.  You can also add "external" users using their existing Microsoft Accounts.  It's just a few dialogs to add a user.


text:
Q: How to make Listview Expandable in Xamarin Form i am new to Xamarin Form.
I was given a task to make Listview expendable. I am trying for a week but I couldn't do it.
Please if anyone has an idea that how to do it then let me know.
Thanks


text:
Q: Where to validate String parameter I have a Student class that has to have a property of a String ID, which has to be validated. I'm not sure whether to validate it inside the student class or the class that I'm implementing the Student class in. Does that make sense?

A: Assuming ID is final and immutable, then one approach is to have Student constructor throw an exception, probably new IllegalArgumentException("Invalid student ID");
You may additionally provide static method in Student class, which verifies if string is valid, in case you need to check it without creating Student object.
But the logic of determining if ID is valid or not should be in the Student class, I think.
If there are (or can be in future) different kind of student IDs, you could also consider abstract factory pattern, but sounds like that is bit of an overkill.

A: If Student already has any business inside use validate inside else use second one
Class Student
{
 public boolean  validate ()
  {
   //some logic to validation
  }
}

Inside of Model or controller or Action
 public boolean  validate ()
  {
   //some logic to validation
  }

A: One of the approach is to use validation object. For instance see the Validation approach uses in the Spring Framework. You create an object which implements the interface Validator with two methods: one to detect if the Validator can validate the instance to validate, and another one which validate it.
public class StudentValidator implements Validator<Student> {

  public boolean supports(Student student) {
   // ...
  }

  public void validate(Object target, Errors errors) {
   // ...
  }
}

This approach leads to separation of the code of the object and the way to validate it, offering more flexibility when combining validator:

*

*you can combine several Validator even if the class hierarchy is not respected (POJO principle).

*when you need to validate field with data from other system (for instance a database), this approach avoid to mix database / persistence code in the POJO domain class.

Please see the documentation of Spring about Validation.


text:
Q: Why can't array elements use push methods in JavaScript?

var strArr = []
strArr[0].push("someThing Text")
console.log(strArr)

Error: Cannot read properties of undefined (reading 'push')

var strArr = []
strArr[0] = "someThing Text"
console.log(strArr)

Array ["someThing Text"]
What's the difference between the two? Why can't array elements use push methods?

A: You are trying to push into an array at index 0 inside another array.
var strArr = []
strArr.push("someThing Text")
console.log(strArr)

If you wanted your code to work, you would need to do this.
var strArr = [ [] ] // an array in an array
strArr[0].push("someThing Text")
console.log(strArr)

A: Simply put, push is an array method. that means it only applies to an array (I look forward to a correction as I am a learner too).
Therefore, push will only apply/operate on an array element if the element is an array as well. Another way to grasp this is to note that elements in an array may be of different data types. Each data type has a different (predefined) set of operations/methods that can be applied to them. push is a predefined method that can be applied only to an array or array element(s) that is/are of the type array.
See the snipped below:

const myArr = ['Hello', 'World', ['Javascript', 'Python', 'PHP'], 100, 'function'];

console.log('Orginal array --> ' + myArr); // Orginal array: Hello,World,Javascript,Python,PHP,100,function
myArr.push(['Vue', 'Angular', 'React']);
console.log('Updated array --> ' + myArr); // Updated array --> Hello,World,Javascript,Python,PHP,100,function,Vue,Angular,React
myArr[2].push('Java');
console.log('Update myArr[2] ' + myArr); // Update myArr[2] Hello,World,Javascript,Python,PHP,Java,100,function,Vue,Angular,React

A: When you call an array function, you need to call it on the array itself, i.e. strArr.push("someThing Text"). strArr[0] is an array element, and could be a number, string, boolean, or other data type.
You can however add an array element at a specific point in an array, which is sort of what it looks like you were trying to do, with Array.splice(). The parameters are:

*

*index where array element should be inserted

*number of items (starting at index) you want to delete

*the actual elements you want to insert

var strArr = ["foo", "bar"]
strArr.splice(1, 0, "someThing Text")
console.log(strArr)

A: You are using the push method on an array element, not the array.
You should use strArr.push()

A: You are trying to add the element in a specific position using push() method. But the push() method is used to add one or multiple elements to the end of an array. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
array.push(objectName)

var strArr = []
strArr.push("someThing Text")
console.log(strArr)


text:
Q: How can I scroll efficiently horizontally Microsoft Paint? (Autohotkey maybe) I just want to use Paint for a whiteboard style sketching on math problems etc. And I really need a way to navigate efficiently on the page.
Maybe even like: hold space + move mouse, to grab the page like in Photoshop.
So is there some config file or hidden shortcut to scroll the page to the left/right? Or maybe there is an easy way in Autohotkey?
Thanks y'all!

A: #IfWinActive ahk_class MSPaintApp

+WheelUp::              ; Shift + Wheel Up for horizontal scrolling left
MouseGetPos,,,id, fcontrol,1
; Loop 1 ; <-- Increase for faster scrolling
SendMessage, 0x114, 0, 0, %fcontrol%, ahk_id %id% ; 0x114 is WM_HSCROLL and the 0 after it is SB_LINERIGHT.
return

+WheelDown::            ; Shift + Wheel Down for horizontal scrolling right
MouseGetPos,,,id, fcontrol,1
; Loop 8 ; <-- Increase for faster scrolling
SendMessage, 0x114, 1, 0, %fcontrol%, ahk_id %id% ;  0x114 is WM_HSCROLL and the 1 after it is SB_LINELEFT.
return

#IfWinActive

Source: Horizontal scrolling shortcut in Windows


text:
Q: Software defined radio, rtl-sdr, no output from rtl_fm I am trying out an rtl-sdr dongle (RTL2832U/R820T) on Ubuntu.
Following this guide I run the test command successfully.
$ rtl_test -t
Found 1 device(s):
  0:  Generic RTL2832U OEM

Using device 0: Generic RTL2832U OEM
Found Rafael Micro R820T tuner
Supported gain values (29): 0.0 0.9 1.4 2.7 3.7 7.7 8.7 12.5 14.4 15.7 16.6 19.7 20.7 22.9 25.4 28.0 29.7 32.8 33.8 36.4 37.2 38.6 40.2 42.1 43.4 43.9 44.5 48.0 49.6
No E4000 tuner found, aborting.

But I cannot get any real output. Running rtl_fm (as in here or in this video-guide):
$ rtl_fm -M wbfm -f 89.1M
Found 1 device(s):
  0:  Realtek, RTL2838UHIDIR, SN: 00000001

Using device 0: Generic RTL2832U OEM
Found Rafael Micro R820T tuner
Oversampling input by: 42x.
Oversampling output by: 1x.
Buffer size: 8.13ms
Tuned to 89352000 Hz.
Sampling at 1008000 Hz.
Output at 24000 Hz.
Exact sample rate is: 1008000.009613 Hz
Tuner gain set to automatic.
^X^CSignal caught, exiting!

User cancel, exiting...

gives no output.
Also, running rtl_sdr capture.bin -s 1.8e6 -f 392e6 did produce 23Mb file, but I don't know how to open/use it.
Could someone suggest what I could do now to at least be sure the dongle really works?
Also info: I run Ubuntu 14.04, rtl-sdr was installed from Ubuntu repositories, the version is 0.5.2.7.3ab6-1. Also I use the simple antena which came with the dongle. It is the same as in the video-guide. I guess it should be ok for fm frequencies.

A: Your rtl-sdr dongle and driver seems to be working. You should be getting binary output while running
$ rtl_fm -M wbfm -f 89.1M

Try running command from your link to play FM

*

*Install sox to play audio sudo apt install sox -y

*Now play the FM

rtl_fm -M wbfm -f 89.1M | play -r 32k -t raw -e s -b 16 -c 1 -V1 -


text:
Q: Better to use "and" or "in" when chaining "let" statements? I realize this is probably a silly question, but...
If I'm chaining a bunch of let statements which do not need to know each other's values, is it better to use and or in?
For example, which of these is preferable, if any:
let a = "foo"
and b = "bar"
and c = "baz"
in
  (* etc. *)

or
let a = "foo" in
let b = "bar" in
let c = "baz"
in
  (* etc. *)

My intuition tells me the former ought to be "better" (by a very petty definition of "better") because it creates the minimum number of scopes necessary, whereas the latter is a scope-within-a-scope-within-a-scope which the compiler/interpreter takes care to note but is ultimately unimportant and needlessly deep.

A: My opinion is that in is better. The use of and implies that the definitions are mutually dependent on each other. I think it is better to be clear that this is not the case. On the other hand, some OCaml programmers do prefer and for very short definitions, where the slightly more compact notation can appear cleaner. This is especially true when you can fit the definitions on a single line:
let a = "foo" and b = "bar" in

A: The answer to the question "which is better?" only really makes sense when the interpretations do not differ.  The ML family of languages (at least SML and OCaml) have both a parallel initialization form (and) and a sequential, essentially nested-scope form (in) because they are both useful in certain situations.
In your case the semantics are the same, so you are left to answer the question "what reads best to you?" and maybe (if this is not premature) "which might be executed more efficiently?"  In your case the alternatives are:

*

*For the and case: evaluate a bunch of strings and do a parallel binding to three identifiers.

*For the in case: bind foo to a, then bind bar to b, then bind baz to c.
Which reads better?  It is a toss up in this case because the outcome does not matter.  You can poll some English speakers but I doubt there will be much preference.  Perhaps a majority will like and as it separates bindings leaving the sole in before the expression.
As to what executes more efficiently, I think a good compiler will likely produce the same code because it can detect the order of binding will not matter. But perhaps you have a compiler that generates code for a multicore processor that does better with and.  Or maybe a naive compiler which writes all the RHSs into temporary storage and then binds them, making the and case slower.
These are likely to be non-essential optimization concerns, especially since they involve bindings and are probably not in tight loops.
Bottom line: it's a true toss-up in this case; just make sure to use parallel vs. sequencial correctly when the outcome does matter.

A: I would say in is better because it reduces scope and better expresses intent.  If I see all these defintions chained together in a shared scope manner I would be under the impression that it was done for a reason and would be looking for how they effect each other.

A: It's the same as the difference between let and let* in Lisp, I believe.
let* (similar in functionality to the in..in.. structure - the second structure in your question) is sometimes used to hide imperative programming since it guarantees sequential execution of expressions (see what Paul Graham had to say about let* in On Lisp).
So, I'd say the former construct is better. But the truth is, I think the latter is more common in the Ocaml programs I have seen. Probably just easier to use in letting one build on previously named expressions.


text:
Q: Create-react-app 'Failed to compile.' due to css import Appearing out of nowhere, this error has me stomped. It appears any time I try to import a css file, whether in full or as a module.
E.g.
import "./index.css"

or
import styles from "./button.module.css"

It MAY have been due to the latest macOS beta at least it seems to have coincided with its release. I tried rolling back from it, but that didn't work.
Failed to compile
./src/index.css (./node_modules/css-loader/dist/cjs.js?modules=true!./node_modules/style-loader/dist/cjs.js!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
CssSyntax error: Unknown word (1:1)

> 1 | var api = require("!../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
    | ^
  2 |             var content = require("!!../node_modules/css-loader/dist/cjs.js??ref--6-oneOf-4-1!../node_modules/postcss-loader/src/index.js??postcss!./index.css");
  3 |
This error occurred during the build time and cannot be dismissed.

I've tried manually adding web pack, checked everything for syntax errors, re-installed the whole repo, went back several commits and so on. Nothing seems to do anything. Happy to supply more context.
(I found one other person mentioning the same problem on SO 15 hours ago, but he hadn't supplied debugging information so the ticket was closed).
Note: The same codebase runs perfectly well on my MacBook, no problems!

A: It's seems like your npm project setup is broken. This type of problem famously called Failed to compile generally occurs when we are moving one branch to another branch more often and we sometimes forgot to do npm install and continue to work on another branch which has new packages without doing npm install and many more cases which is very hard to tell that in which cases your npm setup is broken.
There are couple of ways of solving this issue.
First way

*

*Delete the node_modules directory and package-lock.json file.

*Close the editor and open it again and in new terminal do npm i. Then check whether it is compiled or not.

If that didn't work then follow the second way.
Second way
Clear the npm cache forcefully of your project setup.
npm cache clear -f

Then restart the system for closing all the node service for this session. After restart do npm i and check again.
If that didn't work then follow the third  way which I think that fail compilation issue will be easily solved.
Third way
Just clone your project again in another directory and do npm install.

A: The code is right. There may not be a problem with code.
The steps mentioned below might help:

*

*Delete node_modules folder.

*run npm install

*run npm cache clean -f (try without -f first)

*first 2 steps worked for me.

A: Can you try this?
 Delete these folders: node_modules and package-lock.json.
(You can also delete a cache folder if there is)
 Run this Commands:
With yarn: yarn
With npm: npm install
 You can also try to change your import method:
import * as styles from ...
This might help hopefully!


text:
Q: How to filter an array of objects and order them based on how many times they show up in array I have an array of user objects, some of which appear multiple times. I am trying to count how many times each unique user object shows up in the array and reorder them to make the user that appears most often be first in the array, and the user that appears least in the array show up last in the array.
const users =
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "jisoo@gmail.com", createdAt: 1592452421714},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232}
]

I have tried using the method countBy with lodash
const bestMatched = countBy(users, "handle");

which returns
{lisa: 3, jisoo: 1, unnieJennie: 3, kawikaLovesKpop: 2}

I would still need access to the users array with all of the objects keys and values.

A: You can use bitwise NOT to do this because ~undefined = -1 and we need an object to store our result:
const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})

Try it:

const users =
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "jisoo@gmail.com", createdAt: 1592452421714},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232}
]

const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})

console.log({result})

Since object is not ordered so if you want to have a collection in order, you need to use array.
const result = users.reduce((m,{handle})=>({...m, [handle]:-~m[handle]}), {})
Object.keys(result).sort((a,b)=>result[a]-result[b]).map(key=>({[key]:result[key]}))

A: Try this:

let counterObj = {}

for (user of users){
    counterObj[user.handle] = 1 + (counterObj[user.handle] || 0)
}

console.log(counterObj)

A:

const users =
[
   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "bbfc927c-f3d4-4cdd-b872-9cb233a194aa", handle: "jisoo", email: "jisoo@gmail.com", createdAt: 1592452421714},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232},

   {id: "0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8", handle: "lisa", email: "lisa@gmail.com", createdAt: 1593894321997},

   {id: "1d1e31cd-eff2-47de-b46d-4d45bb2dd97f", handle: "kawikaLovesKpop", email: "kawika@gmail.com", createdAt: 1593894550566},

   {id: "be942039-6a59-46a4-9f92-1f7808b20c2f", handle: "unnieJennie", email: "jennie@gmail.com", createdAt: 1593894227232}
]

ob={lisa: 3, jisoo: 1, unnieJennie: 3, kawikaLovesKpop: 2}
map=new Map()
users.map(x=>map.set(x.handle,x))
res=Object.entries(ob).sort((a,b)=>b[1]-a[1])
.flatMap(o=>Array(o[1]).fill(map.get(o[0])))

console.log(res)

A: I believe this may be what you're looking for. There were some errors in the JSON as well, but it should be good now.
const users = [
  {
    id: '0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8',
    handle: 'lisa',
    email: 'lisa@gmail.com',
    createdAt: 1593894321997,
  },
  {
    id: 'bbfc927c-f3d4-4cdd-b872-9cb233a194aa',
    handle: 'jisoo',
    email: 'jisoo@gmail.com',
    createdAt: 1592452421714,
  },
  {
    id: 'be942039-6a59-46a4-9f92-1f7808b20c2f',
    handle: 'unnieJennie',
    email: 'jennie@gmail.com',
    createdAt: 1593894227232,
  },
  {
    id: '0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8',
    handle: 'lisa',
    email: 'lisa@gmail.com',
    createdAt: 1593894321997,
  },
  {
    id: '1d1e31cd-eff2-47de-b46d-4d45bb2dd97f',
    handle: 'kawikaLovesKpop',
    email: 'kawika@gmail.com',
    createdAt: 1593894550566,
  },
  {
    id: 'be942039-6a59-46a4-9f92-1f7808b20c2f',
    handle: 'unnieJennie',
    email: 'jennie@gmail.com',
    createdAt: 1593894227232,
  },
  {
    id: '0f933bbd-d1fb-4ad5-80f0-661c3c0aa2f8',
    handle: 'lisa',
    email: 'lisa@gmail.com',
    createdAt: 1593894321997,
  },
  {
    id: '1d1e31cd-eff2-47de-b46d-4d45bb2dd97f',
    handle: 'kawikaLovesKpop',
    email: 'kawika@gmail.com',
    createdAt: 1593894550566,
  },
  {
    id: 'be942039-6a59-46a4-9f92-1f7808b20c2f',
    handle: 'unnieJennie',
    email: 'jennie@gmail.com',
    createdAt: 1593894227232,
  },
];

function sort(jsonArray) {
  var containerArray = [];
  jsonArray.map((item, index) => {
    if (item === 'null') {
    } else {
      var newArray = [];
      var itemHandle = item.handle;
      jsonArray.map((i, index) => {
        if (itemHandle === i.handle && itemHandle !== 'null') {
          newArray.push(i);
          jsonArray.splice(index, 1, 'null');
        }
      });
      jsonArray.splice(index, 1, 'null');
      containerArray.push(newArray);
    }
  });
  return containerArray;
}

var finalArray = sort(users);

//Sorts the finalArray by highest occurrence to lowest
finalArray.sort(function(a,b){
  return b.length - a.length
})

console.log(finalArray)

Keeps objects together so that you can still access their properties via dot notation.


text:
Q: Router sending DHCP NAK to PC, but only when switching operating systems Here's the situation:
I have a PC with a single ethernet interface, with a single MAC address.
On my router (a Linksys E4200 with stock software), I have a DHCP reservation set to the MAC address of this interface, instructing it to always give a particular IP.
Normally, this works fine.
However, this computer is running both Linux (Ubuntu 18.04) and Windows 10.
After booting into Windows, everything works as expected and I have the correct IP.
However, upon booting back into Linux, the network "spins" forever and fails to connect. Running journalctl -xe shows many copies of:
Apr 17 23:38:41 <snip> dhclient[2030]: DHCPDISCOVER on enp3s0 to 255.255.255.255 port 67 interval 20 (xid=0x40fd6476)

And in particular, this exchange:
Apr 17 23:40:29 chase-lx dhclient[3456]: DHCPREQUEST of 192.168.1.105 on enp3s0 to 255.255.255.255 port 67 (xid=0x242aef01)
Apr 17 23:40:29 chase-lx dhclient[3456]: DHCPNAK from 192.168.1.1 (xid=0x1ef2a24)

Sure enough, to confirm, viewing logs on the router admin interface yields:
Wed, 17 Apr 2019 23:40:28 sending NAK to <the mac address>

So, the router is explicitly denying the DHCP request and effectively refusing to honor the DHCP reservation.
Why would the router be doing this - how can it even distinguish that a "different machine" is making the DHCP request if it comes from the same interface.
More importantly, is there a way I can configure my router to not do this?
Right now, one way to fix it is to use another computer to go to the admin interface, and delete from the DHCP client table the entry corresponding to the IP/MAC address.
After deletion, the machine in limbo succeeds in connecting.


text:
Q: Does creating a unique constraint on a column automatically create index? Consider this unique constraint:
ALTER TABLE Posts
ADD CONSTRAINT UQ_Posts_Name
UNIQUE (Name);

Does it automatically create index on Name column?

A: Yes, just to add.. creating primary key automatically creates clustered index.
EDIT:
I was wrong... after Lieven's comment:

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.

A: yes it does. See this

A: You can create a separate index on it as well. this article http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx describes the differences very well.

A: Yes, absolutely. A unique constraint creates a unique index.


text:
Q: Pass values from a freestyle job downstream pipeline job in jenkins On Jenkins, I have a freestyle job which takes user input (release branch and environment to deploy). I want to use these values in pipeline job. I tried to export the user input to a file, read the file, set the values as environment variables, tried to print in the pipeline job. This doesn't seem to work for me. Any inputs are appreciated?

A: There is an issue in later versions of Jenkins JENKINS-SECURITY-170
that prevents passing environment variables (or more precisely any arbitrary build parameters) between consecutive jobs in pipeline. The workaround is to start Jenkins instance with system property hudson.model.ParametersAction.keepUndefinedParameters set to true


text:
Q: Why this VBA code to copy range fails intermittently? I wrote below procedure to copy range of cells from an input sheet to output sheet. Output sheet is part of master template. After the copy, I call SaveAs function on master workbook to save the master workbook on file system with another name.
Private Sub copyRange(inputRange As Range, outputRange As Range)

inputRange.NumberFormat = "0.00000000"
inputRange.Copy
outputRange.PasteSpecial xlPasteValuesAndNumberFormats

End Sub

I'm calling this function multiple times from another procedure for each range that i want to copy. Calling code looks like this:
Dim InputSheet As Worksheet
Dim OutputSheet As Worksheet

Set InputSheet = Application.Workbooks.Open("C:/inputFile.xlsx", False, vbReadOnly).Worksheets("Sheet1")
Set OutputSheet = OutputSheet 'this is a sheet of master template

copyRange InputSheet.Range("E15:G28"), OutputSheet.Range("B12:D25")
copyRange InputSheet.Range("E33:G37"), OutputSheet.Range("B30:D34")

copyRange InputSheet.Range("I15:K28"), OutputSheet.Range("E12:G25")
copyRange InputSheet.Range("I33:K37"), OutputSheet.Range("E30:G34")

copyRange InputSheet.Range("M15:O28"), OutputSheet.Range("H12:J24")
copyRange InputSheet.Range("M33:O37"), OutputSheet.Range("H30:J34")

Above code keeps failing around 1 out of 5 times with error "paste special method of range class failed". Most of the time it runs fine and  output file is getting produced as expected. Is there any way to prevent this error?

A: After trying many things, finally I've removed call to pastespecial method.
Private Sub copyRange(inputRange As Range, outputRange As Range)

inputRange.NumberFormat = "0.00000000"
inputRange.value2 = outputRange.value2

End Sub

This approach have resolve intermittent issues while copying the range.


text:
Q: zcat to read gzip files and then concatenate them in Perl I need to write a perl script to read gzipped files from a text file list of their paths and then concatenate them together and output to a new gzipped file. ( I need to do this in perl as it will be implemented in a pipeline)
I am not sure how to accomplish the zcat and concatenation part, as the file sizes would be in Gbs, I need to take care of the storage and run time as well.
So far I can think of it as -
use strict;
use warnings;
use IO::Compress::Gzip qw(gzip $GzipError) ;

#-------check the input file specified-------------#

$num_args = $#ARGV + 1;
if ($num_args != 1) {
    print "\nUsage: name.pl Filelist.txt \n";
exit;

$file_list = $ARGV[0];

#-------------Read the file into arrray-------------#

my @fastqc_files;   #Array that contains gzipped files
use File::Slurp;
my @fastqc_files = $file_list;

#-------use the zcat over the array contents
my $outputfile = "combined.txt"
open(my $combined_file, '>', $outputfile) or die "Could not open file '$outputfile' $!";

for my $fastqc_file (@fastqc_files) {

    open(IN, sprintf("zcat %s |", $fastqc_file))
      or die("Can't open pipe from command 'zcat $fastqc_file' : $!\n");
    while (<IN>) {
        while ( my $line = IN ) {
          print $outputfile $line ;
        }
    }
    close(IN);

my $Final_combied_zip = new IO::Compress::Gzip($combined_file);
  or die "gzip failed: $GzipError\n";

Somehow I am not able to get it to run. Also if anyone can guide on the correct way to output this zipped file.
Thanks!

A: You don't need perl for this. You don't even need zcat/gzip as gzipped files are catable:
cat $(cat pathfile) >resultfile

But if you really really need to try to get the extra compression by combining:
zcat $(cat pathfile)|gzip >resultfile

Adding: Also note the very first "related" link on the right, which seems to already answer this very question: How to concat two or more gzip files/streams

A: Thanks for the replies - the script runs well now -
#!/usr/bin/perl
use strict;
use warnings;
use File::Slurp;
use IO::Compress::Gzip qw(gzip $GzipError);

my @data = read_file('./File_list.txt');
my $out = "./test.txt";

foreach my $data_file (@data)

{
    chomp($data_file);
    system("zcat $data_file >> $out");
}
my $outzip = "./test.gz";
gzip $out => $outzip;


text:
Q: SQL Query to achieve the sequence in the below format I am trying to find solution to achieve the result in the below format using sql.
I have two columns:
col1  col2
 1     e
 1     e
 1     e
 2     e2
 2     e2
 2     e2
 3     e3
 3     e3
 4     e4
 4     e4
 4     e4
 4     e4
 4     e4
 4     e4
 6     e6
 6     e6
 6     e6

where col1 has the sequence number and col2 has the events where the col1 has the numbers starting from 1 to 10 ...and so on for each batch of events i.e first batch has the sequence 1, next 2 assigned and so on.
I am trying to renumber the sequence col1 in the format below using sql
col1  col2
 1     e
 2     e
 3     e
 1     e2
 2     e2
 3     e2
 1     e3
 2     e3
 1     e4
 2     e4
 3     e4
 4     e4
 5     e4
 6     e4
 1     e6
 2     e6
 3     e6

A: Maybe you want this:
SELECT
    ROW_NUMBER() OVER (PARTITION BY col2 ORDER BY col2) col1,
    col2
FROM
    table_name
ORDER BY
    col2;

A: Try this:
SELECT col1, col2 FROM YourTable ORDER BY col2, col1

ORDER BY clause helps to get the result in order.

A: Check Col2 in your procedure use logic Like:
IF col2='e' Then
Begin
 RESET SEQUENCE
 SEQUENCE
end
else IF col2='p' Then
Begin
 RESET SEQUENCE
 SEQUENCE
end


text:
Q: Fundamental group of the Grothendieck ring scheme Let $K_0(V_k)$ be the Grothendieck ring of $k$-varieties with $k$ a field. Let S$_k$ be its affine scheme. Is this a connected scheme for any field ? (I understand that this could be a very naive question, but I have not found an immediate answer yet.)
Is it known what the topological fundamental group $\pi_1($S$_k)$ is of (the connected components of) S$_k$ ?


text:
Q: Python Selenium Webdriver: Unable to load all reviews on the browser I am trying to extract all google reviews of a restaurant. There are just over 900 reviews of the restaurant. However, my script was only able to extract 50 reviews. I am not sure where am I making the mistake. Any help to fix the issue would be highly appreciated. Here is my code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import time

driver = webdriver.Chrome()
base_url = 'https://www.google.com/search?tbs=lf:1,lf_ui:9&tbm=lcl&sxsrf=AOaemvJFjYToqQmQGGnZUovsXC1CObNK1g:1633336974491&q=10+famous+restaurants+in+Dunedin&rflfq=1&num=10&sa=X&ved=2ahUKEwiTsqaxrrDzAhXe4zgGHZPODcoQjGp6BAgKEGo&biw=1280&bih=557&dpr=2#lrd=0xa82eac0dc8bdbb4b:0x4fc9070ad0f2ac70,1,,,&rlfi=hd:;si:5749134142351780976,l,CiAxMCBmYW1vdXMgcmVzdGF1cmFudHMgaW4gRHVuZWRpbiJDUjEvZ2VvL3R5cGUvZXN0YWJsaXNobWVudF9wb2kvcG9wdWxhcl93aXRoX3RvdXJpc3Rz2gENCgcI5Q8QChgFEgIIFkiDlJ7y7YCAgAhaMhAAEAEQAhgCGAQiIDEwIGZhbW91cyByZXN0YXVyYW50cyBpbiBkdW5lZGluKgQIAxACkgESaXRhbGlhbl9yZXN0YXVyYW50mgEkQ2hkRFNVaE5NRzluUzBWSlEwRm5TVU56ZW5WaFVsOUJSUkFCqgEMEAEqCCIEZm9vZCgA,y,2qOYUvKQ1C8;mv:[[-45.8349553,170.6616387],[-45.9156414,170.4803685]]'
driver.get(base_url)
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[./span[text()='Newest']]"))).click()

title = driver.find_element_by_xpath("//div[@class='P5Bobd']").text
address = driver.find_element_by_xpath("//div[@class='T6pBCe']").text
overall_rating = driver.find_element_by_xpath("//div[@class='review-score-container']//span[@class='Aq14fc']").text
total_reviews_text =driver.find_element_by_xpath("//div[@class='review-score-container']//div//div//span//span[@class='z5jxId']").text

num_reviews = int (total_reviews_text.split()[0])
all_reviews = WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div.gws-localreviews__google-review')))
total_reviews = len(all_reviews)

while total_reviews < num_reviews:
        driver.execute_script('arguments[0].scrollIntoView(true);', all_reviews[-1])
        WebDriverWait(driver, 5, 0.25).until_not(EC.presence_of_element_located((By.CSS_SELECTOR, 'div[class$="activityIndicator"]')))
        #all_reviews = driver.find_elements_by_css_selector('div.gws-localreviews__google-review')
        all_reviews = WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div.gws-localreviews__google-review')))
        print(total_reviews)
        total_reviews +=1

A: Selenium expected condition presence_of_all_elements_located doesn't really wait for presence of ALL the elements matching the passed to that method locator.
It actually waits for at least 1 element matching the passed locator.
So instead of
num_reviews = int (total_reviews_text.split()[0])
all_reviews = WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div.gws-localreviews__google-review')))
total_reviews = len(all_reviews)

Please try this:
num_reviews = int (total_reviews_text.split()[0])
WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div.gws-localreviews__google-review')))
time.sleep(2)
all_reviews = driver.find_elements_by_css_selector('div.gws-localreviews__google-review')
total_reviews = len(all_reviews)

Possibly you will have the same issue with the second use of presence_of_all_elements_located as well.
Generally, never trust presence_of_all_elements_located, it will give you the first caught matches only.

A: If you notice the reviews are lazy-loaded as you scroll. You may need to add some code to scroll down and wait for all the reviews to appear.

A: Try like below:
Was able to extract more than 50 of the reviewer names.
i = 0
try:
    while True:
        time.sleep(.5)
        reviews = driver.find_elements_by_xpath("//div[@id='reviewSort']//div[contains(@class,'google-review')]")
        driver.execute_script("arguments[0].scrollIntoView(true);",reviews[i])
        print(f"{i+1}:{reviews[i].find_element_by_xpath('./div/div/div/a').text}")
        i+=1
except Exception as e:
    print(e)
    pass


text:
Q: jQuery DataTables button trigger after load results in an infinite loop I have a dataTable that can have columns filtered based on what the user checks.
I want the user to be able to export what they currently see on the dataTable. So I have a data-column attribute on each checkbox which lets me know which column should be shown or hidden based on whether or not it is checked.
I have initialized my table like this:
var table = $('.my-table').DataTable({
        pageLength:25,
        fixedHeader: true,
        sScrollX: true,
        dom: '<"html5buttons"B>lTfgitp',
        buttons: [
            {extend: 'copy'},
            {extend: 'csv',
                title: 'Testing',
                exportOptions: {
                    columns: get_columns_to_export(),
                    rows: { selected: true }
                },
                'customize': function(doc){
                    console.log("==CSV DOC==");
                    console.log(doc);
                }
            },
            {extend: 'excel',
                title: 'Testing',
                exportOptions: {
                    columns: get_columns_to_export(),
                    rows: { selected: true }
                },
                'customize': function(doc){
                    console.log("==EXCEL DOC==");
                    var sheet = doc.xl.worksheets['sheet1.xml'];
                    console.log(sheet);
                }
            },
            {extend: 'print',
                customize: function (win){
                    $(win.document.body).addClass('white-bg');
                    $(win.document.body).css('font-size', '10px');

                    $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
                }
            }
        ]
});

The function get_columns_to_export just returns the numbered list of columns that are visible, and this actually works, but only on page load.
If I unhide some columns (so that get_columns_to_export() returns a different array containing an extra number), the exported file will only contain the original columns that it found on table load.
I looked up how to trigger the button again, but am now running into issues where DataTables has an infinite loop before JS runs out of stack size.
From the DataTables documentation, I'm using button.trigger() found here with the following:
$('.buttons-excel').on('click',function(){
    table.button('.buttons-excel').trigger();
});

This causes the infinite loop to occur. I've also tried adding a return statement after the trigger action, but for some reason it ignores this and goes directly into the original customize function that I declared in the original declaration of table.
What can I do to update DataTables with the correct column numbers while not ending up in an infinite loop?

A: Change the exportOptions sections to be
exportOptions: {
                    columns: get_columns_to_export.bind(this),
                    rows: { selected: true }
                },

Datatables column selectors can take various options, among them a string or a function.
In your original example, you are calling the function get_columns_to_export() once at compile time, and this function returns the initial state of the columns which is what is being assigned to the column selector.
Because your columns are dynamic, you want to use the function form of the column selector, which will be called every time the button action is executed.
The infinite loop is being triggered by the fact that you are triggering the button in the click function which is called by the trigger function.  Get rid of this to stop the looping.


text:
Q: Jensen's inequality; what's the need for the probability measure? Jensen's inequality states that if $\mu$ is a probability measure on $\Omega$, $f$ is integrable function (on $\Omega$) and $\phi$ is convex on the range of f then:
$$\phi\left(\int_\Omega g(x)\,\mathrm d\mu\right)\leq\int_\Omega\phi\left[g(x)\right]\,\mathrm d\mu.$$
I wonder why $\mu \left( \Omega \right)$ has to be finite and equal to one? Why can't one let $\Omega$ = $\mathbb{R}$ for example?

A: If you consider $\mu$ to be an arbitrary finite measure and consider normalizing it to $\nu$, then applying the ordinary Jensen inequality to $\nu$, you get another version:
$$\phi \left ( \frac{1}{\mu(\Omega)} \int_\Omega g d \mu \right ) \leq \frac{1}{\mu(\Omega)} \int \phi \circ g d \mu.$$
In either case, it says applying a convex function to the average gives a smaller result than averaging the convex function itself.
The proof itself completely breaks down when $\mu(\Omega)=+\infty$, though.

A: You just have to consider $\mu$ be a finite measure, i.e. $\mu(\Omega)<\infty$, because if not you can´t apply the convexity of $\phi$. First let observe that without loss of generality we can consider $\mu(\Omega)=1$, because if $\mu(\Omega)<\infty$ then tou can take another measure that is normalized i.e. $d\nu(x)=\frac{d\mu(x)}{\mu(\Omega)}$. Also if $\phi$ is a convex function you have $\phi(y)\geq ay+b$ for $a,b$ constants, and if you fix $y_{0}$ you also have that $\phi(y_{0})=ay_{0}+b$, then
$$\phi\left(\int_{\Omega}f(x)d\mu(x)\right)=a\int_{\Omega}f(x)d\mu(x)+b,$$
now using that $\mu(\Omega)=1$ you have
$$a\int_{\Omega}f(x)d\mu(x)+b=\int_{\Omega}(af(x)+b)d\mu(x)\leq \int_{\Omega}\phi(f(x))d\mu(x).$$
So as you see if you don´t consider a finite measure, you can´t do this trick because you need to have that the integral of a constant is finite.

A: A quick collection of counterexamples why the Jensen equality in it's usual form fails in other cases:
General counterexample for finite measures $\mu(X) = c \in [0,\infty) \setminus\{1\}$:
Every affine linear function $\phi(x) = ax+b$ is convex. Suppose Jensen's equality holds, then
$$
a \mu(X) + b = a\left(\int_X 1\ d\mu \right) + b \leq \int_X a+b\ d\mu = (a+b)\mu(X).
$$
Thus
$$
b(1- \mu(X)) \leq 0
$$
for all $b\in\Bbb R$, as $\phi$ can be an arbitrary affine linear map. But clearly we can choose some $b\in\Bbb R$ such that this fails.
Specific example for infinite measure: Take $f(x)=x^{-1}, \phi(x)=x^2$ on $[1,\infty[$ with the Lebesgue measure. Then
$$
\phi\left(\int_{[1,\infty[} x^{-1}\ d\lambda(x)\right) = \infty \not\leq \int_{[1,\infty[} x^{-2}\ d\lambda(x) < \infty.
$$


text:
Q: I enter multiple objects in an arraylist but it only prints one JAVA
I'm trying to make a script where I can enter students with their last name and grade, teachers, print the students with their grades, and print the teachers.
I created an object "Estudiante" and I was entering it in an arraylist but at the time of printing the arraylist only prints one element

import java.util.*;

public class tarea1 {
public static void main(String[] args) {

ArrayList<Estudiante> Estudiantes = new ArrayList();
ArrayList<Profesor> Profesores = new ArrayList();
Scanner sc = new Scanner(System.in);

System.out.println("1.Ingresar estudiantes \n2.Ingresar Maestros \n3.Ver alumnos con sus notas \n4.Ver maestros \n5.Salir");

while(true){
    System.out.println("Elija el número de la opción deseada");

    try {
        int opcion = sc.nextInt();
        switch(opcion) {
        case 1:
            while(true) {
                Estudiante aux = new Estudiante();
                aux.ingresar_estudiante();
                Estudiantes.add(aux);

                sc.nextLine();
                System.out.println("Si desea seguir ingreseando resultados escriba Y, sino escriba cualquier otra letra");

                String continuar = sc.nextLine();

                if(continuar.equalsIgnoreCase("Y")) {
                    continue;
                }
                else {
                    break;
                }
            }
continue;

in this way I print them

    case 3:
            for(Estudiante e:Estudiantes) {
                System.out.println(e.ver_estudiantes());
                break;
            }

And this is the class

import java.util.*;

public  class Estudiante {

     private String nombre;
     private String apellido;
     private double nota;

    public Estudiante() {
    }

     public void ingresar_estudiante() {

        System.out.println("Ingresar estudiantes");

            Scanner sc = new Scanner(System.in);

            System.out.println("Ingresa el nomnre del estudiante: ");
            nombre = sc.nextLine();

            System.out.println("Ingresa el apellido del estudiante: ");
            apellido = sc.nextLine();

            System.out.println("Ingresa la nota separada de un punto: ");
            nota = sc.nextDouble();

            sc.nextLine();

        }

    public String ver_estudiantes() {
        return "El nombre del estudiante es " + nombre +" " + apellido + " y su nota es de " + nota;
    }
}

A: There is a "break" in case 3 in switch-case. It breaks the "for loop" after the first iteration.
 case 3:
        for(Estudiante e:Estudiantes) {
            System.out.println(e.ver_estudiantes());

        }


text:
Q: Is there another way of obtaining /usr/bin/mysql_config --plugindir on Redhat? On my debian boxes I can easily get this value from /usr/bin/mysql_config --plugindir when building a MySQL UDF library. However on Redhat this option does not appear to be a flag on the mysql_config binary so it just errors.
MySQL on Redhat is at 5.0.77 and on Debian it is at 5.1.37 so perhaps this could also be the cause?
I am unsure and it is the last problem halting a completed build. Any ideas of how I can obtain this value or get Redhats mysql_config to return the right thing?

A: The answer is no. MySQL did not support plugins until 5.1.


text:
Q: Is it possible to add a timestamp for the target folder with httrack? I am using httrack to backup my websites via command line:
httrack https://www.example.com  -O "websites/example.com"  -%v

Is it possible to add a timestamp to the target folder to get a target folder like this:
websites/example.com-2019-07-18

A: Use the following command:
httrack https://www.example.com  -O "websites/example.com-$(date '+%F')"  -%v

For more examples look at man date.


text:
Q: Physical reality of inner event horizon and inner ergosurface in a rotating black hole in D. Wiltshire et al. "The Kerr spacetime" In chapter 1/The Kerr spacetime-a brief introduction by Matt Visser of D. Wiltshire, M. Visser, S.M. Scott "The Kerr spacetime - Rotating black holes in general relativity" the author presents a schematic description of the relevant surfaces. In Boyer-Lindquist coordinates $(t, r, \theta, \phi)$:
Outer ergosurface $r_E^+ = m + \sqrt{m^2 - a^2 \cos^2 \theta}$
Outer event horizion $r_+ = m + \sqrt{m^2 - a^2}$
Inner event horizon $r_- = m - \sqrt{m^2 - a^2}$
Inner ergosurface $r_E^- = m - \sqrt{m^2 - a^2 \cos^2 \theta}$
where:
$m$ black hole mass
$a = J/m$ angular momentum per unit mass
$J$ angular momentum
Each surface embedded in the previous one, that is:
$r_E^+ \ge r_+ \gt r_- \ge r_E^-$
The equal sign holds on the polar axis
Then the author states that the inner horizon and the inner ergosurface are not physical as there are reasons to suspect they are grossly unstable. Moreover causal pathologies (closed timelike curves), even if originating in the maximally extended $r \lt 0$ region, can reach out to the inner horizon.
My question is:
1. Which reasons argue that the inner horizon and inner ergosurface are unstable?
2. As for the maximally extended $r \lt 0$ region which is the consensus in the theoretical physicists community about its physical meaning?


text:
Q: PowerShell SqlDataAdapter issue I am trying to pull data in to a dataadapter but I am getting the following error, Exception calling "Fill" with "1" argument(s): "Fill: SelectCommand.Connection property has not been initialized."
From reading the info on the error message is says I am not assigning the dataconnector correctly but I think i am as the same code works to pull the data in to a table.
Here is the code, can someone tell me what I am getting wrong please?
$serverName = 'server\SQLEXPRESS';
$databaseName = 'db';
$tableName = 'table';
$UserName = 'sa'
$Password = 'Password'
$ServerConnection = "Data Source=$serverName; user id=$UserName; password=$Password;Initial Catalog=$databaseName;"
#
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString=$ServerConnection
$connection.Open()
$SqlQuery = 'Select *  FROM table WHERE table.mailed = 0 ORDER by SessionID'
$command = $connection.CreateCommand()
$command.CommandText = $SqlQuery

$dt = New-Object System.Data.DataTable
$da = New-Object System.Data.SqlClient.SqlDataAdapter $SqlQuery
$da.fill($dt)

$connection.Close()


text:
Q: Can't get Flutter app on real device to make http request on Node.j server running locally I have my Node server running locally on 127.0.0.1:3000 and with my Flutter app running on Chrome localhost:5000 I can send http requests to url localhost:3000 and they all respond.
I'm now trying running it on a real Android device connected via usb and with the same url I get error: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 45614 error.
Now, why port 45614 (from the error) gets used if the url localhost port is 3000?
I got my ip4 address and used that in my Flutter app url as was suggested in various posts here on SO, tried with and without port as static String dbUrl = '192.168.43.105'; or static String dbUrl = '192.168.43.105:3000'; but requests are not hitting the server.
I tried setting adb to the  Node.js server port 3000 with adb tcpip 3000and that restarted the ads server listening on port 3000 but still requests won't hit my Node.js server..
Running adb devices command gets me 5203e95d43cd93a7 device which is the connected Android tablet, and with adb forward --list I get 5203e95d43cd93a7 tcp:56393 tcp:41547 but I can't find out which port is which and how to use it..
Sorry for the probably messy question but as you can see I'm quite lost here and after reading various posts here on the subject I only got me more confused..
Any help would be very much appreciated.
Many thanks.

A: first try adding http://, so it will be something like this
http://192.168.43.105:3000

if that didn't work try allowing firewall on port 3000.
note: the following solution worked for .netcore server so it might not work with nodejs
try changing your server url to the following:
http://0.0.0.0:5000

A: Firstly you need to get your pc ip address, for example your ip address is 192.168.1.1 then add port which u are using in your backend like 8000 or 8080. so now your url will be like http://192.169.1.1:8000/. and make sure your server/backend is running and your device and laptop is connected with same network.
It will work!


text:
Q: How to display a autocomplete selection only when selected? I have a JavaScript code which will give autocomplete prediction.
This code will display the word even if I keep my mouse over that prediction.
Actually I need to display it only when I select a predicition from the list.
See demo here : JSFIDDLE
$(function () {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    $("#tags").autocomplete({
        source: availableTags
    });
});
$(window).load(function(){
    $('#tags').each(function(i, el) {
        var that = $(el);
        that.autocomplete({
            select: function( event , ui ) {
                alert( "You searched for: " + ui.item.label );//alerting the selection to the user
            }
        });
    });
});

What is the meaning of these line? Can some one explain me ?
$(window).load(function(){
    $('#tags').each(function(i, el) {
        var that = $(el);
        that.autocomplete({
            select: function( event , ui ) {
                alert( "You searched for: " + ui.item.label );//alerting the selection to the user
            }
        });
    });
});

A: I think you may be making it harder than it really is.
$("#tags").autocomplete({
    source: availableTags,
    focus : function(event) { event.preventDefault(); },
    select: function(event, ui) {
        alert( "You searched for: " + ui.item.label); //alerting the selection to the user
    }
});

should be about enough. Preventing the default event from triggering on the focus event will prevent the element over which the mouse is hovering from being displayed in the #tags input.


text:
Q: unable to set innodb_directories in mysql5.7.28 I m unable to set innodb_directories in mysql5.7.28. Below the error
enter code here
cat /etc/my.cnf
innodb_directories="/u01/tablespaces/"

cat /varlog/mysql.log
2019-11-03T06:14:54.567062Z 0 [ERROR] unknown variable 'innodb_directories=/u01/tablespaces/'
2019-11-03T06:14:54.567104Z 0 [ERROR] Aborting


text:
Q: Iframe mostra sistema em localhost - PHP Bom dia
Vou tentar explicar a minha situação e ver se há solução.
Eu tenho um servidor que roda uma aplicação web em java que eu quero que funcione apenas em localhost.
Ainda, nesse servidor, eu tenho um sistema em PHP que está liberado para acesso pela internet, e que acessa essa aplicação java (localhost) e retorna o resultado. O porquê de estar utilizando outro sistema web, sendo que o java também é web, são por razões específicas.
Então, aqui vai o problema:
Eu quero acessar o sistema PHP, e dentro dele ter um iframe (exemplo) que me permite ter acesso ao sistema java que funciona só localhost. Deu pra entender?
Eu pensei em algo com cURL ou file_get_contend, mas talvez tenha outra forma ou uma biblioteca que ajude.
Agradeço desde já
Obrigado


text:
Q: Function displaying output prematurely The following function gets a random number:
def random_ticket():
    ticket = randint(100, 999)
    print(ticket)

The following function is a contact form which uses the random number function:
def contact_form():
    print("We weren't able to find a solution to the problem you are having. Please fill out this short contact form and our personal technicion will contact you as soon as possible!\n")
    name = raw_input('Name: ')
    email = raw_input('Email: ')
    problem_description = raw_input('Describe your problem: ')
    print("\nThank you for filling out this contact form. You will soon be contacted through Email. Here is your ticket number: {}\n".format(random_ticket()))

However, the console displays the ticket number before the actual "Thanks for filling text". It's supposed to go after that text. How would I fix this?

A: Change this:
def random_ticket():
    ticket = randint(100, 999)
    print(ticket)

To this:
def random_ticket():
    ticket = randint(100, 999)
    return ticket

In the calling line:
print("\n... {}\n".format(random_ticket()))

You called the random_ticket function which already printed out ticket and returning None, so in addition to the already printed ticket you printed None in this line.

A: you should return the value from random_ticket function
def random_ticket():
    ticket = random.randint(100, 999)
    return (ticket)

It will work as you expected


text:
Q: Adding a new field to an existing content-type in Drupal 7 I'm new to Drupal and I'm looking for a way to add a new field to an already installed content-type in Drupal 7. Please note that some content is already present in the database. Also, I need to do this programmatically and not via a GUI.
Googling, I have already found the following documents, which seem to be related:
https://api.drupal.org/api/drupal/modules!field!field.module/group/field/7
https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_update_N/7
Still, my ideas are a bit confused and a basic example would clarify things.

A: This snippet should get you started. It was found on the Drupal Stackexchange. I suggest you check there first in the future.
https://drupal.stackexchange.com/questions/8284/programmatically-create-fields-in-drupal-7
$myField_name = "my_new_field_name";
if(!field_info_field($myField_name)) // check if the field already exists.
{
    $field = array(
        'field_name'    => $myField_name,
        'type'          => 'image',
    );
    field_create_field($field);

    $field_instance = array(
        'field_name'    => $myField_name,
        'entity_type'   => 'node',
        'bundle'        => 'CONTENT_TYPE_NAME',
        'label'         => t('Select an image'),
        'description'   => t(''),
        'widget'        => array(
            'type'      => 'image_image',
            'weight'    => 10,
        ),
        'formatter'     => array(
            'label'     => t('label'),
            'format'    => 'image'
        ),
        'settings'      => array(
            'file_directory'        => 'photos', // save inside "public://photos"
            'max_filesize'          => '4M',
            'preview_image_style'   => 'thumbnail',
            'title_field'           => TRUE,
            'alt_field'             => FALSE,
        )
    );
    field_create_instance($field_instance);
    drupal_set_message("Field created successfully!");
}

You can execute this code countless ways. I am not privy to the requirements of your project so its hard for me to make a recommendation. You could hook this into the update/install functions, or you could build it into a page hook in a module, or you could just bootstrap any new php file in the root directory with this:
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);