text:
Q: How to convert PictureDrawable into ScaleDrawble? I am trying to scale a picture drwable which I get from svg-android-library. I can create the drawable but do not get how to scale it.
Here is the code I tried:
Drawable drawable = svg.createPictureDrawable();
    int size = 108;
        Bitmap img = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(img);
        //resize drawable here according to screen width
        drawable = new ScaleDrawable(drawable, 0, size*2, size*2).getDrawable();
        drawable.setBounds(0, 0, size*2, size*2);
        drawable.draw(canvas);

Any suggestions?

A: I used
Picture picture = svg.getPicture();

and then draw it with a new Rect which will stretch it to fit the new Rect
canvas.drawPicture(picture, newRect);


text:
Q: Discrete-time stochastic process - waiting time Suppose you are given a discrete-time stochastic process which startes in state $C$ and can attain two further states $A$ and $B$.
In state $C$ you take two independent exponential times $T_1 \sim E(2)$ and $T_2 \sim E(4)$, where $E(\lambda)$ denotes the exponential distribution with parameter $\lambda$. If $T_1$ is the smaller you go to position $A$ after time $T_1$, and if $T_2$ is the smaller you go to $B$ after time $T_2$.
Now my questions refers to the following statement:

The time spent in state $C$ is exponential of parameter $6$.

How can I show that the distribution of this random variable is $E(6)$?

A: What you are asking about is really not anything specifically to do with stochastic processes. You just want to prove that if $X$ is Exp(2) (where the parameter here is rate; sometimes the parameter of the exponential distribution is in fact the mean time), $Y$ is Exp(4), and the two are independent, then $Z:=\min \{ X,Y \}$ is Exp(6). One way to do this would be to prove that $P(Z>z)=e^{-6z}$ for $z \geq 0$ and $1$ otherwise. But $\{ Z>z \}=\{ X>z \} \cap \{ Y>z \}$, so this probability is easy to do using the independence and the known formulas for $P(X>z)$ and $P(Y>z)$.

A: First, you generate $T_1\sim E(2)$ and $T_2 \sim E(4)$ independently. Then, you leave the state C after $T_1$ or $T_2$ time has passed — whichever is sooner.
By the definition of the exponential distribution (with parameter $\lambda$), we have that
$$\Pr\left[X \geq t\right] = \exp{(-\lambda t)}.$$
Let $T \equiv \min(E(2), E(4))$ be the amount of time before you leave the state C. We have that for any $t$:
$$\begin{align*}
\Pr[T \geq t] &= \Pr[E(2) \geq t \text{ and }E(4) \geq t]& \text{defn of }T\\
&=\Pr[E(2) \geq t] \cdot \Pr[E(4)\geq t]&\text{independence}\\
&= \exp{(-2t)} \cdot \exp{(-4t)}&\text{exponential distribution}\\
&= \exp{(-6t)}&\text{arithmetic}\\
\end{align*}$$
which shows, according to our first equation above, that $T$ is distributed as an exponential variable E(6) with parameter $\lambda = 6$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL / BQ - Update app names from table using merge function I work with mobile app data and I have a table with app names that need to be cleaned up / replaced. For eg, "App V2" needs to be changed to "App". I was told to "Select all data except app and app_name (see below) from the table and then rewrite app name with the correct app name, then use a MERGE function to overwrite the table."  The table I have is session_data.
The columns I have are:
  date,
  country,
  app_id,
  app_name,
  app,
  SUM(daily_active_users) AS daily_active_users

*

*Sample Data:

*Date: 2020-08-01

*Country: US

*app_id: 1234

*app_name: app v2

*app = app v2

*daily_active_users = 5

I haven't got a clue where to begin and I am turning to the Stack Overflow community. Thank you in advance!

A: Updating a BigQuery table can be costly affair. If you know all the values to be updates, you can do this by using a case statement while selecting the columns and then overwrite the same table (Kind of simulating the update)
Step 1
select date,
  country,
  app_id,
  case when app_name = 'App V2' then 'App'
       when app_name = 'App V3' then 'App3'
       .
       .
       .
   end as app_name ,
  app,
  SUM(daily_active_users) AS daily_active_users
from session_data

Step 2
Now direct this output in temp table and then overwrite the session_data using all the data from stage table
Here you are simulating the update statement


text:
Q: Update SQL syntax error I'm creating a program which requires updating user data in an ACCESS Db.
While running the code I get above error. my update statement is..
con.Open();
string update = "UPDATE userdata SET full_name='"+name+
                "', user_type ='" + user_type +
                "', gender = '" + gender +
                "', password='"+password+
                "', tel_number='"+tel_number+
                "', blood_type ='"+blood_type+
                "'WHERE user_id='" + user_id + "'";

cmd = new OleDbCommand(update, con);
cmd.ExecuteNonQuery();

con.Close();
MessageBox.Show("Userdata successfully updated!");

A: SQL.... 'WHERE user_id='"

Try changing it to ' WHERE user_id='"
Notice there is a space there.

A: Here is how you should frame your query. Also it's good practice to wrap your oledbCommand inside using statement
  con.Open();
  using (OleDbCommand cmd = con.CreateCommand())
  {
   cmd.CommandText="UPDATE userdata
                  SET full_name= @full_name, user_type= @user_type,
                      gender= @gender,password= @password, tel_number= @tel_number,
                      blood_type= @blood_type Where user_id= @user_id;

       // add named parameters
       cmd.Parameters.AddRange(new OleDbParameter[]
       {
           new OleDbParameter("@user_type", user_type ),
           new OleDbParameter("@gender", gender),
           new OleDbParameter("@password", password),
           ...
       };

       // execute
       cmd.ExecuteNonQuery();

  }


text:
Q: Can a GraphStream Node be an href link? Is it possible to assign a href/url attribute to a GraphStream Node such that when it's click, a new browser/tab opens to the specified URL?

A: Use ViewerListener to handle your graph events, then you can do what you want.
See here how it works : http://graphstream-project.org/doc/Tutorials/Graph-Visualisation/
Here you can see some examples with the last version : https://github.com/graphstream/gs-ui-javafx/tree/master/src-test/org/graphstream/ui/viewer_fx/test


text:
Q: GCDAsyncSocket and send SIP packet i try to send INVITE to SIP server:
        GCDAsyncSocket *outgoingCallSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketOutgoingCallQueue];

        BOOL result = [outgoingCallSocket connectToHost:currentSoftswitch.ip onPort:5060 error:&error];

inside
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

and then, when socket connected:
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
{
    NSLog(@"Connected socket to %@:%hu", host, port);
    [sock writeData:finalData withTimeout:-1 tag:OUTGOING_CALL];
    NSLog(@"\n===================SEND START TO currentSoftswitch.ip->%@:5060 =================\n%@\n===================SEND FINISH=================\n",host,[[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding]);

here is result:
> ===================SEND START TO currentSoftswitch.ip->195.26.84.147:5060 ================= INVITE
> sip:380442399740@91.224.223.42;transport=tcp;lr SIP/2.0 Via:
> SIP/2.0/TCP 195.26.84.147:5060;rport;lr SIP/2.0 Max-Forwards: 70 From:
> "alex@ixc.ua"
> <sip:897542@91.224.223.42>;tag=Ztr3.0MabqPlVkNJHHVdvAdeNGUXsz8E To:
> sip:380442399740@195.26.84.147 Contact: "alex@ixc.ua"
> <sip:897542@10.129.244.143:5060;transport=TCP;ob> Call-ID:
> zu.MBTPcv87dylX2i-BsA.b551Kyflic CSeq: 25575 INVITE Route:
> <sip:195.26.84.147;transport=tcp;lr> Route: <sip:195.26.84.147;lr>
> Allow: PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, SUBSCRIBE, NOTIFY,
> REFER, MESSAGE, OPTIONS Supported: replaces, 100rel, timer, norefersub
> Session-Expires: 1800 Min-SE: 90 User-Agent: CallsFreeCalls
> SSContent-Type: application/sdp Content-Length: 480
>
> v=0 o=- 3566574154 3566574154 IN IP4 46.211.183.202 s=pjmedia c=IN IP4
> 46.211.183.202 b=AS:84 t=0 0 a=X-nat:6 m=audio 40000 RTP/AVP 104 18 108 3 8 0 96 c=IN IP4 46.211.183.202 b=TIAS:64000 a=rtcp:40001 IN IP4
> 46.211.183.204 a=sendrecv a=rtpmap:104 SILK/8000 a=fmtp:104 useinbandfec=0 a=rtpmap:18 G729/8000 a=rtpmap:108 iLBC/8000 a=fmtp:108
> mode=30 a=rtpmap:3 GSM/8000 a=rtpmap:8 PCMA/8000 a=rtpmap:0 PCMU/8000
> a=rtpmap:96 telephone-event/8000
>
> ===================SEND FINISH=================

but when i check in whireshark, a packet don't detect like SIP. where i'm wrong?

A: SIMPLE ANSWER - wrong content-lenght!


text:
Q: Why multiple DbContext classes? When I program using LINQ with a .dbml file, there is only one context.  But, when I do an MVC site, it seems like I have separate contexts for each entity (which is the way the MVC tutorial showed me how to do it; with "movies" context).
I have:
public class AccountsContext : DbContext
{
    public AccountsContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Account> Accounts { get; set; }
}

And, I have:
public class ClientsContext : DbContext
{
    public ClientsContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Client> Clients { get; set; }
}

When I call these, I have to create separate contexts, like:
private AccountsContext db = new AccountsContext();
private ClientsContext clientsContext = new ClientsContext();

... Which is both annoying, and it seems redundant since I know that when I use LINQ, I only have to instantiate a single database object.
Is there a way to use only one contextб and is this recommended?

A: There shouldn't be anything stopping you from using one context. The database, and the tooling used to access it, should be completely independent of anything outside of it (business logic, service layer, UI, etc...).
The number of contexts, or how you use them, shouldn't change based on your client technology.
What about MVC leads you to believe that you would need more than one context? And what's stopping you from doing so?
If you think you need to use a context for each entity, because the sample was that way, you don't. Just use one context.
If it helps, this is what a simple context looks like with more than one entity:
public partial class abook_dbEntities : DbContext
{
    public abook_dbEntities()
        : base("name=abook_dbEntities")
    {
    }

    public DbSet<Entity> Entities { get; set; }
    public DbSet<Contact> Contacts { get; set; }
}

If it helps, a typical business flow looks like this:

UI -> Controller -> Business logic -> Data access -> Database

Your data contexts would go in your data layer. Your logic would go in your business logic layer.


text:
Q: VPC Network Upgrade I'm trying to upgrade our legacy network on GCP to a VPC network with this command: gcloud beta compute networks update default --switch-to-custom-subnet-mode but I get this error in response:
ERROR: (gcloud.beta.compute.networks.update) The first 2 IPs in this network's range 10.240.0.0/16 must be in used.
I thought that this meant that I need to use 10.240.0.2 and 10.240.0.3 since they are the first two usable IPs in the subnet. I can't use 10.240.0.0 or 10.240.0.1. But I still get the error message. Has anyone ever gotten a similar error message when upgrading to a VPC network? How did you solve it?
Thanks.
All devices are in us-central1
Updating to include information
gcloud beta compute networks update default --switch-to-custom-subnet-mode
Network [default] will be switched to custom mode. This operation cannot be undone.
Do you want to continue (Y/n)?  Y
X  Migrating Network from Legacy to Custom Mode
Validating Network
Creating Subnetwork
Updating Instances
Updating Instance Groups
Updating Forwarding Rules
Converting Network to Subnet Mode
Failed.
ERROR: (gcloud.beta.compute.networks.update) The first 2 IPs in this network's range 10.240.0.0/16 must be in used.
Network info
default
Description Default network for the project
Subnet creation mode: Legacy VPC network
Dynamic routing mode: Regional
VPC network ULA internal IPv6 range: Disabled
DNS server policy: None
Maximum transmission unit: 1460
Addresses: 10.240.0.0/16
Gateway: 10.240.0.1
Internal IP addresses
10.240.0.3
10.240.0.4
10.240.0.7
10.240.0.11
10.240.0.15
10.240.0.19
10.240.0.21
10.240.0.27
10.240.0.40
10.240.0.46
10.240.0.53
10.240.0.56
10.240.0.65
10.240.0.76
10.240.0.87
10.240.0.99
10.240.0.108
10.240.0.109
10.240.0.111
10.240.0.116


text:
Q: Не проходит последние тесты, задача C++ В классических ролевых играх есть 3 стандартных класса: Воин (Warrior), Маг (Mage), Вор (Rogue). Для каждого из классов важен определённый атрибут: для Воина - сила, для Мага - интеллект, для Вора - ловкость.
По значению атрибутов определите предпочтительный класс для персонажа.
Входные данные. Три неотрицательных целых числа через пробел - атрибуты персонажа: сила, интеллект, ловкость.
Формат результата
Выходные данные. Необходимо вывести строку с названием предпочтительного класса (см. примеры), если предпочтительный класс выявить невозможно вывести Any
1)
Входные данные
14 5 5
Результат работы
Recommended class for character (14,5,5) is Warrior.
2)
Входные данные
14 21 1
Результат работы
Recommended class for character (14,21,1) is Mage.
#include <iostream>
using namespace std;
int main() {
    unsigned long long W, M, R;
    cin>>W>>M>>R;
    if (W>M && W>R) {
        cout<<"Recommended class for character"<<" "<<"("<<W<<","<<M<<","<<R<<")"<<" "<<"is Warrior.";
    }
    else if (M>W && M>R) {
        cout<<"Recommended class for character"<<" "<<"("<<W<<","<<M<<","<<R<<")"<<" "<<"is Mage.";
    }
    else if (R>M && R>W) {
        cout<<"Recommended class for character"<<" "<<"("<<W<<","<<M<<","<<R<<")"<<" "<<"is Rogue.";
    }
    else if (R==M || M==W || W==R) {
        cout<<"Any";
    }
}


text:
Q: Odoo 15.0 - assign: action = {...} not working I am trying to automatically print a report when a field is triggered with an automated action. In the documentation is says to return an action assign: action = {...} but nothing is happening. Here is my code. I'm just trying to download the basic package report pdf so I can then print the pdf.
action = {
    'type': 'ir.actions.report',
    'name': 'Package Barcode (PDF)',
    'model': 'stock.quant.package',
    'report_type': 'qweb-pdf',
    'report_name': 'stock.action_report_quant_package_barcode_small',
   }

I have also tried to use the report_action() method to download and then print the pdf report but I have had no luck with that either.
env.ref('stock.action_report_quant_package_barcode_small').report_action(record)

Any help would be appreciated. I don't want to rely on a third party module. I'm just looking for the same functionality if you where to click on the print button and then select the report you wanted to print from the UI. It downloads the pdf then you can open it and print it from there.

A: The automated action will run the corresponding server action and ignore the returned value. It will not execute the returned action.
You see that in the documentation because the delegate parameter is set to True on the server action field which make fields of the target model (Server Action) accessible from the current model (corresponds to _inherits).
The automated action inherited the server action fields


text:
Q: Tkinter, playsound, simpleaudio, pydub. Играет только один последний загруженный звук При нажатии на кнопку, которая должна воспроизводить определенный звук она проигрывает не свой звук, а тот, что был загружен последним.
Я попробовал уже все библиотеки для воспроизведения звуков в Python но ни одна не работает как мне это надо.
playsound
from tkinter import *
import configparser
from os.path import abspath as wd
from playsound import playsound

def main():
    #config part
    config = configparser.ConfigParser()
    config.read(f'{wd("")}/soap_config.ini')

    #window part
    window = Tk()
    window.title(config["window"]["title"])
    window.geometry(config["window"]["size"])

    #construction func's part
    def create_spc():
        space = Label(window, text='    ')
        space.pack(side=LEFT)

    def create_btn(text, command):
        create_spc()
        btn = Button(window, text=text, command=command)
        btn.pack(side=LEFT)

    #buttons \w files part
    btns_names = config["btns"]["names"].split("/-/")
    btns_sounds = config["btns"]["sounds"].split("/-/")
    sounds_folder = config["btns"]["folder"]

    for n in range(0, 3):
        create_btn(btns_names[n], lambda: playsound(f"{sounds_folder}/{btns_sounds[n]}.wav"))

    window.mainloop()

if __name__ == "__main__":
    main()

Остальные варианты меняют только импорты и часть после #buttons \w files part
simpleaudio
for s in range(0, len(btns_sounds)):
    btns_sounds[s] = sa.WaveObject.from_wave_file(f"{sounds_folder}/{btns_sounds[s]}.wav")

for n in range(0, len(btns_names)):
    create_btn(btns_names[n], lambda: btns_sounds[n].play())

pydub
for s in range(0, len(btns_sounds)):
    btns_sounds[s] = AudioSegment.from_wav(f"{sounds_folder}/{btns_sounds[s]}.wav")

for n in range(0, len(btns_names)):
    create_btn(btns_names[n], lambda: play(btns_sounds[n]))

A: Попробуйте так:
...
    for n in range(0, 3):
        create_btn(
            btns_names[n],
# ---------------> vvv  ---------------------------------------> v
            lambda i=n: playsound(f"{sounds_folder}/{btns_sounds[i]}.wav")
        )
...


text:
Q: modal dialog in jquery that doesn't block the whole site how to achieve this?
let's say that I have 3 dialogs A, B and C. I can work with them at the same time by having them one next to the other, drag them around, put them one on top of another, etc...
now, at some point, the B dialog opens a dialog X. I must still be able to work with dialogs A and C but I must not be able to work with B until I close X.
like the "modal" approach of visual basic
thanks in advance!!

A: I'd say the easiest thing would be to use the "disable" method of dialog B when X opens and then call "enable" on B when X closes.

A: Find the width and height of dialog B and create an overlay on that dialog alone with a message telling the user the action they must take to clear that overlay.
I would also suggest providing a visual prompt any time the user tries to select dialog B while dialog X is open. Something as simple as throbbing the border of dialog a few times would be more than enough.
You may want to explore a way of visually defining the relationship between dialog B and dialog X as well, so that moving one will move the other.


text:
Q: JQuery remote Validation only after form submission Instead of verifying the value after each change, I would like my remote call to be invoked only after form submission.. Is this possible?
<input type="text" remote="validate_url.php" >

A: Did you try if something like this works? Set the remote field to ignore and validate it manually when the form is submitted.
$("#yourFormSelector").validate({
    ...
    ignore: 'input[remote]',
    submitHandler: function(form) {
        if($(form).validate().element("input[remote]"))
            form.submit();
        else
            alert("Nope. Remote failed");
    }
});

A: check http://docs.jquery.com/Plugins/Validation/validate
if you want to validate only on submission, you can disable other events:
$("#form").validate({
   onsubmit: true,
   onkeyup: false,
   onclick: false,
   onfocusout: false,
...
})

A: <input type="text" remote="validate_url.php" id="place" name="place">

And inside the JQuery page load, I added the following:
 $().ready(function() {
        $("#form-id").validate({
            onkeyup: false,
            messages: {
                place: {
                    required: "Please enter Place",
                    remote: jQuery.format("Please enter a valid Place or select one form the List")
                }
            }
        });

    });

Here I am trying to achieve the following: (1) User can either enter a Valid Place or (2) Choose one place from the List.
(when started typing the autosuggestion will list the matched Places). Now user may continue typing or select one form the list. If the user going to select one from list, the "controll" lost from the "text box" and the "remote" validation starts & returns error before the user selected the valid Place Name..
Actually I need to invoke the remote validation when the "control is out of the text box and autosuggestion list".. The autosuggestion values are inside a class "autosuggestion".


text:
Q: last 6 months total in Teradata I have to calculate total quantity sold for last 6 months. For example in case of January 2018 , I have to calculate told quantity sold from July - Dec 2017. This total should be grouped by primary key.
Thanks
Primary Key Date    qty     last 6 months quantity sold
1          1-Oct    4   0
1          1-Nov    10  4
1           5-Dec   20  14
1          1-Jan    3   34
1          1-Sep    88  0

A: You can calculate the range using ADD_MONTHS plus TRUNC:
WHERE datecole BETWEEN Trunc(Add_Months(Current_Date, -6), 'mon')
                   AND Trunc(Current_Date, 'mon') -1


text:
Q: Advantages to continuity at a point A scalar field $f : \mathbb{R}^n \to \mathbb{R}$ is said to be continuous at a point $\boldsymbol{a}$ if
$$ \lim_{\boldsymbol{x} \to \boldsymbol{a}} f(\boldsymbol{x}) = f(\boldsymbol{a}) $$
So in other words, $f$ has to be defined at $\boldsymbol{a}$ and also has to have a limit at $\boldsymbol{a}$. But isolated points are also defined to be continuous.
It seems to me like, given this definition, there isn't really an advantage to having a function continuous at a point, and continuity is only useful on an set or interval, because of the following:

*

*$f$ can be continuous at a point but not differentiable (e.g. $f(\boldsymbol{x}) = \|\boldsymbol{x}\|$ at $\boldsymbol{0}$)

*$f$ can be continuous at a point but the limit doesn't exist (e.g. $f(\boldsymbol{x}) = \sqrt{-\|\boldsymbol{x}\|}$ at $\boldsymbol{0}$ if $f(\boldsymbol{x}) \subset \mathbb{R}$)

*$f$ can be continuous at a point but the first-order partials don't exist

So if $f$ is continuous at a point $\boldsymbol{a}$, is there anything we can say about $f$ at $\boldsymbol{a}$? Or is it just a nice-to-have?

A: Continuity is a very important property to have, in particular when studying topology. For analysis you usually want something more, for example you'd like the function to be $C^1$ or $C^\infty$ in order to differentiate.
Also, it is nice to have a definition of continuity at a point because it shows that continuity is a local property.

A: Let's start in $R^n$ which is where you are asking the question.
I think continuity at a point is the beginning of a process.  Leaving out your suggestion of isolated points, once you have defined what you mean by continuous at a point (in any number of dimensions) you can now define what you mean by continuous on an interval (or ball in $R^n$, but I'm just going to use the word 'interval'),namely that the function is continuous at every point in the interval.
Now we have something to work with.  For example, a function which is continuous on a closed, bounded interval (compact set) is bounded there and is guaranteed to have a maximum and minimum there.  It is also guaranteed to be uniformly continuous, which is a stronger condition.  It is guaranteed that there is a polynomial on the interval which approximates the function to any desired degree of accuracy.  It is (Riemann and Lebesgue) integrable on that interval and has an anti-derivative in each variable, so you have some help with integration, double integration, etc.  Even if you can't figure out what this antiderivative is, the fact that it exists is quite helpful for certain proofs.
Then the entire theory of derivatives is built on top of continuity.  If the function is not continuous it cannot be differentiable.  In $R^n$ differentiability (as opposed to having partial derivatives, which do not even imply continuity) tell us that the curve is smoother than a merely continuous one; and that in a small enough neighborhood of any point it is nearly linear (nearly can be defined exactly).  This means that if you are asked to prove something and you can prove it for linear functions -- often quite easy -- you might be able to extend your proof to differentiable functions, the argument being that nearly linear is good enough.
The existence of each additional derivative (2nd, 3rd, etc) implies that the function is smoother and smoother.  This is very helpful if you are trying to approximate a function with something easier to work with or show the existence of certain things, like the solution to a differential equation.
In the complex plane the existence of a derivative even at one point is an extremely strong statement, telling you the function is analytic in some vicinity of that point. Analytic functions have many, many properties that merely differentiable ones do not, and they are the cornerstone of many solutions to problems in physics.
Getting away from $R^n$ and into other spaces, continuity can still be defined, and again continuity on a compact set has many implications -- how many and what they are depends on what space you are talking about.
So you start with continuity at a point and build a huge structure on top of that concept. As they say, the longest journey starts with but a single step.

A: Even though continuity doesn't imply differentiability, the fact that $f$ is not continuous at $\boldsymbol{a}$ means $f$ is not differentiable, and hence not continuously differentiable, at $\boldsymbol{a}$.


text:
Q: Passing elements of array to method that accepts ints (Java) I'm trying to create an array of numbers, pass them to a static method that only accepts ints as parameters, and returns the maximum int to main to be printed(these are the homework specs). The max method works in its own, but I can't pass the array I input in main to the function, and get the max value back. Any help is appreciated.
import java.util.Scanner;

public class findMax {
    public static int max(int val1, int val2, int val3) {
        int[] intArray = new int[3];
        val1 = intArray[0];
        val2 = intArray[1];
        val3 = intArray[2];
        int max = Math.max(Math.max(val1, val2), val3);
        System.out.println(max);
        return max;
    }

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] intArray = new int[3];
    System.out.println("Enter 3 integers: ");
    for (int i = 0; i < intArray.length; i++) {
        intArray[i] = sc.nextInt();
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < intArray.length; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        sb.append(intArray[i]);
    }
    System.out.println("Input values: " + sb.toString());
    max(intArray[0], intArray[1], intArray[2]);
    System.out.println(max(intArray[0], intArray[1], intArray[2]));
    sc.close();
}

}

A: Your max method overwrites its' parameters with zeros, so no it doesn't work on its' own.
public static int max(int val1, int val2, int val3) {
    int[] intArray = new int[3]; // {0, 0, 0}
    val1 = intArray[0]; // <-- val1 = 0
    val2 = intArray[1]; // <-- val2 = 0
    val3 = intArray[2]; // <-- val3 = 0
    int max = Math.max(Math.max(val1, val2), val3);
    System.out.println(max);
    return max;
}

should be something like
public static int max(int val1, int val2, int val3) {
    return Math.max(Math.max(val1, val2), val3);
}

Then your main method should work as expected (but you don't need to call max twice like that, just once when you print it).
// max(intArray[0], intArray[1], intArray[2]);
System.out.println(max(intArray[0], intArray[1], intArray[2]));

and you might prefer Arrays.toString(intArray); over your current for loop.
Alternatively, you might make max variadic (and assuming you are using Java 8+, use an IntStream). Like,
public static int max(int... values) {
    return IntStream.of(values).max().orElse(-1);
}

Which can be called like
System.out.println(max(intArray));

or
System.out.println(max(1, 2, 3, 4, 5));


text:
Q: How can i setup default route in angular4? Hi i am new to this angular i want to setup default route in my application
below is my app.routing.ts
    import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

currently its loading LoginComponent i want to change this to RegisterComponent  how can i do this can anyone help me out move forward
Below is my app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

// used to create fake backend
import { fakeBackendProvider } from './_helpers/index';

import { AppComponent }  from './app.component';
import { routing }        from './app.routing';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { JwtInterceptor } from './_helpers/index';
import { AlertService, AuthenticationService, UserService } from './_services/index';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        routing
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent
    ],
    providers: [
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: JwtInterceptor,
            multi: true
        },

        // provider used to create fake backend
        fakeBackendProvider
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

A: In your AuthGard class canActivate method, in the case of a false answer, you can simply redirect the client to /register.
export class AuthGuard {

  constructor( private authService : AuthService, private router : Router ) {
  }

  canActivate( route : ActivatedRouteSnapshot, state : RouterStateSnapshot ) {
    if(this.authService.isLoggedIn())
      return true;
    else // This:
      this.router.navigate(['DESIRED/PATH']);
  }
}

A: Please change your app routes sequence and add pathMatch attribute.
const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },
    { path: '', component: HomeComponent, canActivate: [AuthGuard], pathMatch: 'full' },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

A: You can use like this,
// otherwise redirect to home
{ path: '**', redirectTo: '/' }


text:
Q: Beautifulsoup: extracting td list in table I'm stuck with a BeautifulSoup problem that I think is simple but I can't seem to solve. It is about extracting each td from the following table to create a loop and a list:

Team
Name
Number
Tipo
Motivo
Minute
Bloque

Barcelona
Player 1
16
Tarjeta Amarilla
Derribar a un contrario en la disputa del balón
88
Segundo tiempo

Real Madrid
Player 2
8
Tarjeta Amarilla
Sujetar a un adversario impidiendo su avance.
12
Primer tiempo

What I need is to create a dictionary with some elements of each tr to create a dataframe later. I would like to have a list with:

*

*Team: Barcelona

*Name: Player 1

*Number: 16

*Minute: 88

*Team: Real Madrid

*Name: Player 2

*Number: 8

*Minute: 12

As you can see, there are some tds that I don't need and I'd also like to 'jump' on them for my final df.
I've tried with this code (I only put a simplified example) but it doesn't work because I always take the name of the 1st team:
tabla = amonestaciones.find('table', class_='tabla-clasificacion-home marratua tablageneral tabla-actas')

rows = tabla.find_all('tr')

for row in rows:
    team = row.find('td')
    name = row.findNext('td')
    lista = {
        "Team": team,
        "Name": name
    }

This is the output I get (I also would like to remove the code  but if I try .text or .get_text() I have the error 'NoneType' object has no attribute 'text'):
{'Team': Real Madrid	, 'Name': Real Madrid	}

I sense that I'm very close to the solution but I am stuck and I can't move forward. Thanks in advance for your help!

A: You have to first retrieve all the rows, then call row.findAll('td') on each row and store it in a variable. After which you can use an index on it to retrieve the required columns and append it as a dictionary to a list:
table = soup.find('table', class_='tabla-clasificacion-home marratua tablageneral tabla-actas')
tbody = table.find('tbody')
tr = tbody.findAll('tr')
lista = []
for row in tr:
    td = row.findAll('td')
    lista.append({ 'Team': td[0].text, "Name": td[1].text, "Number": td[2].text, "Minute": td[5].text })

A: If you feel like learning something new, you don't even need bs4 (well, sort of). All you need is pandas (you get a dataframe out of the box) to get this:
-  -----------  --------  --  ----------------  -----------------------------------------------  --  --------------
0  Barcelona    Player 1  16  Tarjeta Amarilla  Derribar a un contrario en la disputa del balón  88  Segundo tiempo
1  Real Madrid  Player 2   8  Tarjeta Amarilla  Sujetar a un adversario impidiendo su avance.    12  Primer tiempo
-  -----------  --------  --  ----------------  -----------------------------------------------  --  --------------

With this:
import pandas as pd
from tabulate import tabulate

sample_html = """

Team
Name
Number
Tipo
Motivo
Minute
Bloque

Barcelona
Player 1
16
Tarjeta Amarilla
Derribar a un contrario en la disputa del balón
88
Segundo tiempo

Real Madrid
Player 2
8
Tarjeta Amarilla
Sujetar a un adversario impidiendo su avance.
12
Primer tiempo

"""

df = pd.read_html(sample_html, flavor="bs4")
df = pd.concat(df)
print(tabulate(df))
df.to_csv("your_table.csv", index=False)

The code also dumps your table to a .csv file:


text:
Q: Tradução oficial do bbPress para o idioma Português Não encontrei nenhum download oficial do bbPress para o idioma Português. Encontrei no Google todo tipo de sugestão mas creio que é para versões antigas do plugin bbPress.
Já instalei e está totalmente funcional, mas falta os arquivos .po / .mo. Se não, como faço para traduzir o plugin?

A: Se já tiver uma conta em http://translate.wordpress.org use-a do contrario crie uma e se log.
Depois faça download dos arquivos .po e .mo, versão 2.4 ou mais recente em  http://translate.wordpress.org/projects/bbpress/2.4.x/pt-br/default/export-translations .
CORREÇÃO: O link correto é http://translate.wordpress.org/projects/bbpress/dev/pt-br/default como comentatado pelo @brasofilo. O link pra versão 2.4 que aparece no site do bbPress está desatualizado e não deve ser utilizado !

Supondo que os arquivos foram baixados para ~/Downloads e que seu site está em ~/www faça:
cd ~/www
cp ~/Downloads/bbpress-dev-pt-br.po  wp-content/languages/bbpress/bbpress-pt_BR.po
cp ~/Downloads/bbpress-dev-pt-br.mo  wp-content/languages/bbpress/bbpress-pt_BR.mo
# conferindo ...
ls -lA wp-content/languages


text:
Q: How to make Exception handling Loop (Unlimited amount of times) Responses to previous question , my initial answer to that question had been solved, but I had another problem when it came down to looping which was later solved by simply using a for loop.
However, my problem is I do not want the user to constantly have to restart the program after an exception is handled, rather I want it to loop the same beginning questions to the user. I've tried placing print statements after the return statements, and also tried completely copying the logic code after the try catch, however, realizing that that would not cause the user to loop unlimited times for the exception. Also, on a side note yes my previous question had good answers, however, no one managed to answer my more recurring problem, which is why no one got the check mark towards their answer.
import java.io.*;
import java.text.DecimalFormat;

public class Test
{

    public static void main(String[] args) throws IOException
    {

        double x;
        x = circlemethods(0.0, 0.0, 0.0, 1.0);

    }

    public static double circlemethods(double volume, double surfacearea,
            double area, double radius) throws IOException
    {

        BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));

        String numInput;
        String reqInput;
        String amountStr;
        double numInt = 0;
        double num = 0;
        double answer = 0;
        double amount = 0;
        double answer2 = 0;
        double answer3 = 0;
        double answer4 = 0;

        for (double i = 0; i < 999; i++)
            ;
        try
        {

            // for (double i = 0; i < 999; i++);

            // while (numInt != 999) {

            System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
            System.out.println("The program will use four methods to achieve this, all calling back to the main method");
            System.out.println("Press any key to continue");
            numInput = myInput.readLine();

            System.out.println("First, what would you like to calculate?");
            System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
            reqInput = myInput.readLine();
            numInt = Double.parseDouble(reqInput);

            System.out.println("Now enter the radius of the required shape(Half of diameter)");
            numInput = myInput.readLine();
            num = Double.parseDouble(numInput);

            DecimalFormat nextAmount = new DecimalFormat("0.00");
            amountStr = nextAmount.format(amount);

            if (numInt == 1)
            {
                System.out.println("You chose to calculate circumference, given the radius :" + num);
                answer = (3.14) * (2) * (num);
                System.out.print("The circumference of that sphere is :");
                System.out.println(answer + "cm³");
                return answer;
            }
            else if (numInt == 2)
            {
                System.out.println("You chose to calculate area, given the radius :" + num);
                answer2 = (3.14) * 2;
                System.out.print("The area of the circle is :");
                System.out.println(answer2 + "cm²");
                return answer2;
            }
            else if (numInt == 3)
            {
                System.out.println("You chose to calculate volume, given the radius :" + num);
                answer3 = 4 / 3 * (3.14) * (num) * (3) * (3) * (3);
                System.out.print("The volume of that sphere is : cm³");
                System.out.println(answer3 + "cm³");
                return answer3;
            }
            else
            // if (numInt == 4)
            {
                System.out.println("You chose to calculate surface area, given the radius :" + num);
                answer4 = 4 * (3.14) * (num) * (2) * (2);
                System.out.print("The Surface area of that sphere is :");
                System.out.println(answer4 + "cm²");
                return answer4;

            }

        } catch (Exception e)
        {
            System.out.println("Please do not enter any string values, next time input enter a number ");
            return 0;
            // how to loop this untill the user inputs a number????

        }

    }

}

A: You need to loop until you get a valid value. One way to do that is loop until a boolean value is set to true. Try something similar to this:
boolean inputIsValid = false;
while (!inputIsValid) { ...

Then when you have determined you have a valid input, add the line:
inputIsValid = true;

Your loop will continue until inputIsValid becomes true.
You could also create an endless while loop. Then when you receive a valid input, break out of the loop:
while(true) {
    //when valid input is received
    break;
}

A: First, you use a while(true) loop instead of looping for 999 times. (That loop doesn't actually do anything considering there is a semicolon right after it.)
Then, you remove the return 0; from your catch block.
So it would be
while(true) {
    try {
        .... //your code
    }
catch {...}
} //while loop end bracket

This way, the loop will only end if it reaches one of your return statements.


text:
Q: Angular 2 / 4 / Universal - How to use JSON-LD data? I have an Angular 4 Universal application and I want to start using microdata in the format of JSON-LD.
It uses a script tag with some content, e.g.:
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  ...
}
</script>

Since this data should change per view, I'm looking for a way to inject this data on route change in Angular 4. Currently, script tags are stripped from templates. When using a workaround with docuemnt.createElement, this doesn't work on the server-side Angular Universal app.
How would I do this?
EDIT
I use Angular 4.x.x, which is now referred to as plain Angular.
I inject document like so:
import { DOCUMENT } from '@angular/platform-browser';

class Test {
  constructor(@Inject(DOCUMENT) private _document) {
  }

  public createScriptTag() {
    this._document.createElement('script'); // doesn't work server-side
  }
}

A: EDIT: as pointed out in the comments, this solutions is a hacky solution and to be used with caution.
You can inject some other type and function "ɵgetDOM" and "ɵDomAdapter" to get a reference to the dom. Sorry for calling it "some" service and function, cause I don't have a clue why they name it like this. I just looked into source code and how the angular team is doing it with the MetaService.
import { Inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { ɵgetDOM, ɵDomAdapter, DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class SeoService {

  private dom: ɵDomAdapter;

  constructor(@Inject(DOCUMENT) private document: any,
              private titleService: Title,
              private metaService: Meta) {

    this.dom = ɵgetDOM();

    let scriptEl = this.dom.createElement('script');
    // ..

  }
}

I've tested this and use it in production.


text:
Q: Access PageContext inside jsp declaration One of my jsp has a function in declaration
<%!
public String performLogic(String state) throws Exception {

    String resposeXML = "";

    resposeXML = GetRequestViaXML(pageContext);

}
%>

This performLogic function need to call a GetRequestViaXML function by passing pagecontext as parameter,So this pagecontext will be used to get all attributes which are set previously in jsp's .
I cannot modify parameters of performlogic nor GetRequestViaXML.
Is it is possible to get the page context inside declaration part of jsp like
pageContext.setAttribute("AppName","IVR");
pageContext.setAttribute("TransactionName","Billing");

A: You can access pageContext Object inside your declaration only if you pass it as parameter:
public String performLogic(String state, PageContext pc) throws Exception {
    pc.setAttribute("AppName","IVR");
    ......
}


text:
Q: How to improve performance of multiple "or" in Case statement I am realizing that a particular subquery is killing performance and curious is there is a better way to write such a Case statement. I am trying to use "=" when possible but often need the "like" statement. My questions are:
If column_a = 1, will this statement return a value immediately, or will it still read through the subsequent "or" statements?
case

  when column_a = 1
    or column_b like '%string a%'
    or column_b like '%string b%'
    or column_b like '%string c%'
  then 'Return A'

  when column_a = 2
    or column_b like '%string d%'
    or column_b like '%string e%'
    or column_b like '%string f%'
  then 'Return B'
.
.
.
  else 'Return Z'
end

Is it better to have a long list of "or" as shown, or better to put each check in its own case statement, i.e.
case

  when column_a = 1
  then 'Return A'

  when column_b like '%string a%'
  then 'Return A'

  when column_b like '%string b%'
  then 'Return A'
.
.
.

A:
If column_a = 1, will this statement return a value immediately, or will it still read through the subsequent "or" statements?

The statement will return result immediately without evaluating rest of ORs

Is it better to have a long list of "or" as shown, or better to put each check in its own case statement

I would recommend former  - to at least keep it readable
Another option to rewrite multiple LIKEs statement is to use
REGEXP_CONTAINS(column_b, r'string a|string b|string c')


text:
Q: Outputting to CSV via .txt --looking for more elegant solution I've recently written a few python scripts that count the number of words in a csv file and then print as output two columns: "Prefix" and "Count" where prefix is the first word in a name in a row and count is the sum of all occurences of that name.
My question is that if I try to output to a .csv file directly, everything gets put in one column and it doesn't look nice. However, if I output first to a .txt file, and then open that file in excel such that it asks me to make a space delimiter, it looks correct.  I bet the answer is pretty basic, but I'm just wondering if there is a simpler way to do this than saving as a .txt and then re-opening as a .csv.  Additionally, why can I open a new excel file and open the .txt file from there and it works, whereas if I try to just "open with" the .txt file directly into excel it does not work (and instead gives me the old result with everything in one column)?
Much thanks for any help you can provide!
EDIT:
        Output looks like the following when I open the .txt file as a csv with the "open with" button:
    Word      Count
    the 333
    Family 54

When I open a new excel file and open the .txt file from there and use the delimiter options that come up before the file opens, it looks correctly like this:
    Word, Count
    the, 333
    Family, 54

A: CSV = comma separated values
You need to output the data separated by comma and not space. You can save this as .csv and double-click to open in excel. Then the data appears in two columns.

Additionally, why can I open a new excel file and open the .txt file from there and it works, whereas if I try to just "open with" the .txt file directly into excel it does not work (and instead gives me the old result with everything in one column)

Same reason. If you open a .txt file in excel, it will just open as text. It doesn't know how to interpret this data (what goes into which columns). When you "open a new excel file and open the .txt file from there", you are "importing" the data and you tell excel to interpret the data as two columns with space as delimiter, so it works.
You can also open the .txt file directly in excel using "open with" and then use the "Text to Columns" feature to remodel the data in a spreadsheet-friendly way.


text:
Q: Eigenvalues from the relation $2M + I = M^2$ $$M=
        \begin{bmatrix}
        0 & 1  \\
        1 & 2  \\
        \end{bmatrix}
$$
How can we use $2M + I = M^2$ to find the eigenvalues of M.

A: $$det(M - \lambda I) = 0$$
$$ \iff(-\lambda)(2-\lambda) - 1 = 0$$
$$\iff -2\lambda + {\lambda}^2 -1 = 0$$
$$\iff {\lambda}^2 = 2\lambda + 1$$
Notice this is the same as replacing $M$ by $\lambda$ in the relation you wrote.
I'll leave the rest up to you.

Edit
I've just learned that this is a consequence of the Cayley-Hamilton Theorem.
It states that any square $\left (n \times n \right)$ matrix $A$ satisfies its own characteristic polynomial $p(\lambda)$.

A: If we are using row vectors, then $\lambda$ is an eigenvalue if and only if there exists $\vec x\ne\vec 0$ such that
$$\vec x M = \lambda \vec x$$
From this you get:
$\vec x M^2 = \lambda \vec x M = \lambda^2 \vec x$
$\vec x (2M+I) = 2\vec x M + \vec x = 2\lambda\vec x+\vec x = (2\lambda+1)\vec x$
Since we have $(2\lambda+1)\vec x=\lambda^2 \vec x$ for a non-zero vector $\vec x$, we get that
$$2\lambda+1=\lambda^2.$$

There is nothing special about the choice of the polynomial in this particular example. To learn more about this, you can read about relation of eigenvalues to minimal polynomial and characteristic polynomial of a matrix.


text:
Q: Get entities references number in xml by using libxml2 I use libxml2 to parse the XML data, please see the raw data below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE payload [
    <!ENTITY a "A">
]>
<payload>&a;&a;&a;</payload>

I am using unsigned long    nbentities;    /* number of entities references */ from the xmlParserCtxt object to count the total number of entities references, but get 5 in the above case which I think 3 is the correct answer.
Any ideas? Many thanks!


text:
Q: Making Highcharts scatter circle shadow I am using highcharts (link) to display some data. Everything looks fine except I could not figure it out how to make a drop-shadow on each scatter circle data. I have fiddle here for this.
And I tried this one too:
series: (function() {
    var seriesArray = new Array();
var bubbleColor = ['#5f97ba', '#c7edc0', '#fc9026'];
for(var n=0; n<inputData.length; n++) {
    seriesArray.push({
         shadow: true, // This is not working
     marker: {
         symbol: 'circle',
         radius: 8
    },
    name: '',
    color: bubbleColor[n],
    pointInterval: 24 * 3600 * 1000,
    data: [] // I have some data here
    return a;
        })()

I checked in their api documents but no success. How can I make a drop shadow on each scatter circle as shown in this mock-up!

A: http://api.highcharts.com/highcharts#plotOptions.bubble.shadow has the information you're looking for:
plotOptions: {
    series: {
         shadow: true
    }
}


text:
Q: b2c and b2e integration with Azure AD What is ideal way of integrating both  Azure AD b2c and b2e in an angular application, can we give two separate buttons on  login page and can redirect based on user selection? Is that feasible? or via social login but that would force b2e tenants to signup with b2c?
Any reference link or good suggestions would be helpful.

A: Lets answer your question one by one.

*

*can we give two separate buttons on login page and can redirect based on user selection?
Yes, you have to use azure ad b2c and there you can add flows for azure ad b2b (b2e).
2.Is that feasible?
Yes, I have used it personally with react js and it works flawlessly.

*or via social login but that would force b2e tenants to signup with b2c?
it depends on the usecase.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-identity-provider  <- these are the providers
https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-azure-ad-single-tenant?pivots=b2c-user-flow <- this one you should use


text:
Q: Проверка подключения к интернету в среде делфи Я использую функцию InternetGetConnectedState, но когда я отключаю интернет она продолжает возвращать мне True. В связи с этим возникает ошибка. Как быть?

A: Ошибка была в том, что функция возвращает true, потому что, есть активный модем. В эту функцию не следует передавать параметр Internet_Connection_Modem.

A: function CheckInetLink(URL: string): byte;
begin
  Result := CheckInetConnect;
  if URL <> '' then
    if Result <> 0 then
      if not CheckUrl(URL) then
        Result := 0;
end;

Если не передать URL, то просто проверит соединение (но бывает что соединение есть, а интернета нет), а если передать URL то проверит его доступность (это более надежный вариант). Лучше передавать URL например на Google или Yandex.


text:
Q: How to find the sum of $\sum_{n=1}^{\infty} (-1)^{n-1} \frac{3^n}{n5^n}$? In particular, it's the $\frac{1}{n}$ term that throws me off; without it, it's a simple geometric series, but I was under the impression that, broadly speaking, the only infinite sums whose value we could calculate were either geometric or telescoping. Thank you in advance for your help.

A: Integrating the series $\displaystyle\sum\limits_{n\geqslant0}x^n=\frac1{1-x}$, one gets $\displaystyle\sum\limits_{n\geqslant1}\frac{x^n}n=-\log(1-x)$ for every $|x|\lt1$. Use this for a specific value of $x$...

...namely, $x=-\dfrac35$.


text:
Q: Css3 Transition Blur Flickering edges I'm trying to add an effect where if you click a button it blurs the background, but the original problem was that the edges where white for some reason, so i pushed them out by using negative margins which worked, but then when i tried to animate the blur and the edges seem to came back then disappear when the animation is done causing a flickering effect?
Jsfiddle: https://jsfiddle.net/xq2ohL4x/
$(function(){
    $("#clickme").click(function(){
        setTimeout(function(){
        $(".image").css("-webkit-filter", "blur(18px)");
    },1000);
    });
});

Any ideas?
Thanks in advanced :)

A: See if this works for you. Change your transition to this.
transition: 2s -webkit-filter linear;


text:
Q: Wordpress: Check if slug exists in specific custom post type I'm using the code below to check if a slug exists, but it's searching on all post types and I need to check only on a specific custom post type.
function the_slug_exists($post_name) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
        return true;
    } else {
        return false;
    }
}

Usage:
if (the_slug_exists($term)) :
    echo 'Ok';
endif;

Is it possible to modify this code to search only on a specific custom post type?

A: function the_slug_exists($post_name, $post_type) {
    global $wpdb;
    if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "' AND post_type = '" . $post_type . "'", 'ARRAY_A')) {
        return true;
    } else {
        return false;
    }
}

Usage
if (the_slug_exists($term,$type)) :
    echo 'Ok';
endif;


text:
Q: Syntax for using toEpochDate with a Dataframe with Spark Scala - elegantly The following is nice and easy with an RDD in terms of epochDate derivation:
val rdd2 = rdd.map(x => (x._1, x._2, x._3,
                         LocalDate.parse(x._2.toString).toEpochDay, LocalDate.parse(x._3.toString).toEpochDay))

The RDD are all of String Type. The desired result is gotten. Get this, for example:
...(Mike,2018-09-25,2018-09-30,17799,17804), ...

Trying to do the same if there is a String in the DF appears too tricky for me, and I would like to see something elegant, if possible. Something like this and variations do not work.
val df2 = df.withColumn("s", $"start".LocalDate.parse.toString.toEpochDay)

Get:
notebook:50: error: value LocalDate is not a member of org.apache.spark.sql.ColumnName

I understand the error, but what is an elegant way of doing the conversion?

A: You can define to_epoch_day as datediff since the beginning of the epoch:
import org.apache.spark.sql.functions.{datediff, lit, to_date}
import org.apache.spark.sql.Column

def to_epoch_day(c: Column) = datediff(c, to_date(lit("1970-01-01")))

and apply it directly on a Column:
df.withColumn("s", to_epoch_day(to_date($"start")))

As long as the string format complies with ISO 8601 you could even skip data conversion (it will be done implicitly by datediff:
df.withColumn("s", to_epoch_day($"start"))

A: $"start" is of type ColumnName not String.
You will need to define a UDF
Example below:
scala> import java.time._
import java.time._

scala> def toEpochDay(s: String) = LocalDate.parse(s).toEpochDay
toEpochDay: (s: String)Long

scala> val toEpochDayUdf = udf(toEpochDay(_: String))
toEpochDayUdf: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,LongType,Some(List(StringType)))

scala> val df = List("2018-10-28").toDF
df: org.apache.spark.sql.DataFrame = [value: string]

scala> df.withColumn("s", toEpochDayUdf($"value")).collect
res0: Array[org.apache.spark.sql.Row] = Array([2018-10-28,17832])


text:
Q: C# Menu Class Access i would like to use a menu to control the web browser. But i am not familiar with class access.
xaml code
<Menu IsMainMenu="True">
<MenuItem Header="Back"></MenuItem>
<MenuItem Header="MainMenu">
<MenuItem Header="subItem1"
x:Name="subItem1" Click="subItem1_Click">
</MenuItem>
</MenuItem>
</Menu>

Class code
public partial class Window1 : Window
{
    public Window1(): this(OverlayStyle.WinForms)
    {
    }
    public Window1(OverlayStyle style)
    {
        InitializeComponent();

            WebBrowserOverlayWF wbo = new WebBrowserOverlayWF(_webBrowserPlacementTarget);
            System.Windows.Forms.WebBrowser wb = wbo.WebBrowser;
            wb.Navigate(new Uri("http://live.com"));

    }

How can i create access the "wb" control from menu item
        private void subItem1_Click(object sender, RoutedEventArgs e)
    {

    }

Many Thanks

A: You can't: it's only in scope in the constructor. Move the declaration outside the constructor but still in the class, and keep the assignment inside the constructor. Than youll have access to it.
Try this
public partial class Window1 : Window
{
    System.Windows.Forms.WebBrowser wb;

    public Window1(): this(OverlayStyle.WinForms)
    {
    }

    public Window1(OverlayStyle style)
    {
        InitializeComponent();

        WebBrowserOverlayWF wbo = new WebBrowserOverlayWF(_webBrowserPlacementTarget);
        wb = wbo.WebBrowser;
        wb.Navigate(new Uri("http://live.com"));
    }
}

Then inside your event handler or other method, you can use wb as you will.


text:
Q: Android apk - How to exclude a .so file from a 3rd party dependency using gradle I have an android project with several dependencies.
Two of them (let's call them dependency A and B) have native libraries (.so files).
Dependency A has the following architectures: arm64-v8a, armeabi, armeabi-v7a, x86 and x86_64.
Dependency B has the following architectures: armeabi, x86
Thus when my app runs on an armeabi-v7a device (for instance), and dependency B calls a native method, it cannot find the relevant library to get it from (as it is not present in armeabi-v7a folder and does not fall back automatically to armeabi where the library is).
Is there any way to work around this?
For instance, can I add some configuration to my build.gradle file in order for arm64-v8a, armeabi-v7a, and x86_64 folders not to be integrated to my final apk?
I have tried packagingOptions / exclude, but with no results : the folders in questions are still there.

A: Try a clean build, I didn't and it was still picking up the files from the previous build. I ended up deleting my app/build/ folder just to be sure.
android {
    packagingOptions {
        exclude 'lib/armeabi-v7a/libSomeLibYouDontWant.so'
    }
}

Worked for me on an app that was previously crashing.
An alternative would be to use
android{
    defaultConfig{
        ndk{
            abiFilters "armeabi", "x86"
        }
    }
}

There are some similar questions which might be helpful
Gradle exclude arm64 libs
How to use 32-bit native libraries on 64-bit Android device


text:
Q: Passing Value to EJS File I am trying to pass a value from a POST route to an EJS file and display it. I have tried redirecting, sending and rendering the results, but it won't get passed to the EJS file.
This is my POST for my login.js:
router.post('/', (req, res) => {
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
  if (err) throw err;
  var dbo = db.db("tmai");
  dbo.collection('users').findOne({username: req.body.user, password: req.body.pass}, function (err, result) {
  if (err) console.log(err);
  if (result === null) res.send('null');
  else {
    res.send({user: result.username});
    // res.redirect('/login');
    // res.render('login/login', {user:req.body.user});
  }
  db.close();
    });
  });
});

This is my GET for my homepage where I am trying to get the value to user. After the send request from the POST above, I still get user as undefined:
router.get('/', (req, res) => {
  console.log(req);
  res.render('home/home', {user: req.body.user});
});

A picture of my folder structure if it helps.

A:
This is my GET for my homepage where I am trying to get the value to user. After the send request from the POST above, I still get user as undefined:

Sounds like you need some sessions.
Sessions helps your app save/keep user data in mind when the user is currently using your app, example, After login.
After you have verified user information on login you get to store some credentials about that user (username/ID) in session store so it will be accessible on that user's requests, like this.

const express = require('express');
const session = require('express-session');

const app = express();

//- Apply & configure a session middleware
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))

//- Usage in routes
router.post('/', (req, res) => {
  //- Db user lookup code to get result.username

  //- Save username in session

  req.session.username = result.username;

  //- Then goes your rendering & redirects code
});

From here you will be able to refer to that username value we have in a session on other routes the user visits with;

router.get('/', (req, res) => {
  console.log(req.session.username);
  res.render('home/home', {user: req.session.username});
});

Read more on express-sessions
GitHub: express-sessions


text:
Q: Test Class: How to Create an Outbound EmailMessage? Is it possible to completely replicate in a unit test creating an outbound emailmessage record against a Case? By that I mean including the Task creation.
I've tried the below in a test class (and also in execute anonymous) but no related Task was created:
emailMessage outboundOne = new emailMessage(
ParentId = testCase.Id,
Subject = 'First outbound email subject',
TextBody = 'First outbound email textbody',
ToAddress = newContact.Id,
Status = '3',
Incoming = false
);

Maybe this is handled via the EmailAuthor page and/or the URL parameters...which isn't reproducible in a unit test?
Some background:
Basically there is a code based Roll up summary field for inbound/outbound email message - it's code based due to complicated logic around what emails to include in the count.


text:
Q: Android - Detect app moving to background and foreground If application is gone to background and come back after 5 minutes, I need to restart the app.
We can leave the restart part, how will we detect the app moving to background and to foreground? Please help.
If there is a link on details of its official impossibility or possibility, please share.

A: when it moves to the background it does onPause() and when it resumes it does onResume(), see the activity lifecycle.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

A: Override onStop() in each Activity. This method will be called when activity goes in background. Then note the time.
Override onStart(). This will be called when activity moves from background to foreground. Then note the time here.

A: I had a similar problem where every time the app returned from background Fragment B kept recalculating results based on the output from Fragment A in the activity (where Fragment A sends data to Fragment B based on user input). The following solution uses a simple Boolean check and should work for most purposes. This allowed me to keep the old FragmentB results even after a long time away from the app (assuming the results in FragmentB aren't so memory-hungry that Android cleans them after some time).
//Code from Fragment B
public class FragmentB extends Fragment {
    Boolean app_was_in_background;
    @Override public void onPause() {
        super.onPause();
        app_was_in_background = true;
    }
    @Override public void onResume() {
        super.onResume();
        if (getArguments() != null) {
            String output_to_FragmentB = getArguments().getString("input_from_FragmentA");

            if (app_was_in_background == null || !app_was_in_background) {
                app_was_in_background = false;

                PerformMyAlgorithm(output_to_FragmentB);
            }
        }
    }
    public void PerformMyAlgorithm(String input) {
        //Code that includes Spinners and calculations, where I want to app
        //to return to the user's chosen spinner location and display
        //results as the user saw them before switching to another app
        //on the device. All this without explicitly "saving" the Spinner
        //position and data in memory.
    }
}

As a side note, applying the same logic to onStart() instead of onResume() can lead to unwanted results:
PerformMyAlgorithm receives the FragmentA output (ie. String output_to_FragmentB) again automatically at onResume() without the user choosing to to so by clicking a Button in FragmentA (my guess is that this due to the way Android manages Fragment lifecycles).
I don't want this since when returning from background (ie. onResume) the FragmentB Views and calculations are reset and redisplayed/recalculated instead of immediately showing the user the results prior to sending the app to background (ie. onPause).


text:
Q: How to convert ellipsoid to mesh3d in R? I use the ellipsoidhull method from cluster package to obtain the minimum volume enclosing ellipsoid (mvee) from a set of points. This method returns an object of class ellipsoid. I need to plot the generated ellipsoid. I tried to use the wire3d method from rgl package to plot ellipsoids but this method gets objects of class mesh3d as input parameter. How can I convert an ellipsoid object to a mesh3d object?

A: If you don't actually care about a mesh, and are just looking to plot a transparent ellipsoid you can use this:
library(rgl)
library(cluster)
open3d()

ellipsoid3d <- function(cen, a = 1,b = 1,c = 1,n = 65, ...){
  f <- function(s,t){
    cbind(   a * cos(t)*cos(s) + cen[1],
             b *        sin(s) + cen[2],
             c * sin(t)*cos(s) + cen[3])
  }
  persp3d(f, slim = c(-pi/2,pi/2), tlim = c(0, 2*pi), n = n, add = T, ...)
}

set.seed(123)
n <- 6
for (i in 1:n){
   cen <- 3*runif(3)
   a <- runif(1)
   b <- runif(1)
   c <- runif(1)

   clr <- c("red","blue","green")[i %% 3 + 1 ]
   elpf <- ellipsoid3d(cen,a=a,b=b,c=c,col=clr,alpha=0.5)
}

Yielding:

I modified the interesting answer from cuttlefish44 to get this - see this link: enter link description here
There is also a qmesh3d  answer from dww there that you could modify in a similar manner to get a mesh3d if that is what you really want, but I thought this more elegant.

A: library(cluster)
xyz <- cbind(rnorm(10), rnorm(10), rnorm(10))
e <- ellipsoidhull(xyz)
A <- e$cov
center <- e$loc
r <- sqrt(e$d2)

library(Rvcg)
sphr <- vcgSphere()
library(rgl)
ell <- translate3d(
  scale3d(
    transform3d(sphr, chol(A)),
    r, r, r),
  center[1], center[2], center[3])

shade3d(ell, color="red", alpha=0.3)
points3d(xyz)


text:
Q: Solving Dinesman's multiple-dwelling example using clojure's core.logic/core.match After watching Sussman's lecture http://www.infoq.com/presentations/We-Really-Dont-Know-How-To-Compute, I am inspired to give core.logic and core.match a go. The only examples I know are those constraint problem solvers that I used to do as a kid. This one was an example used in the SICP course as well as being mentioned in the talk:

Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors. Baker does not live on the top floor. Cooper does not live on the bottom floor. Fletcher does not live on either the top or the bottom floor. Miller lives on a higher floor than does Cooper. Smith does not live on a floor adjacent to Fletcher's. Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?

I found this on the rosettacode site:
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem#PicoLisp
But not too sure how that translates into clojure. I am hoping that someone can provide an example of solving this using core.logic or core.match

A: Here's a solution in core.logic. It's not exactly equivalent to the picolisp algorithm because we don't have the same primitives available, but it's the same general idea. Thanks for introducing me to the problem - it was fun to invent permuteo and beforeo, and I had my first excuse to use conda.  Edit: using conda there was horrible and wrong, and I'm back to conde now. Oh well, some day.
(ns dwelling.core
  (:refer-clojure :exclude [==])
  (:use clojure.core.logic))

(defn rembero [x l out]
  (fresh [head tail]
    (conso head tail l)
    (conde [(== x head) (== out tail)]
           [(fresh [new-out]
              (conso head new-out out)
              (rembero x tail new-out))])))

(defn permuteo [a b]
  (conde [(emptyo a) (emptyo b)]
         [(fresh [head tail b-tail]
            (conso head tail a)
            (rembero head b b-tail)
            (permuteo tail b-tail))]))

(defn beforeo [x y l]
  (fresh [head tail]
    (conso head tail l)
    (conde [(== x head) (fresh [more-tail]
                          (rembero y tail more-tail))]
           [(beforeo x y tail)])))

(defn not-adjacento [x y l]
  (fresh [head tail more]
    (conso head tail l)
    (resto tail more)
    (conde [(== x head) (membero y more)]
           [(== y head) (membero x more)]
           [(not-adjacento x y tail)])))

(run* [tenants]
  (fresh [a b c d e]
    (== [a b c d e] tenants)
    (permuteo tenants '[Cooper Baker Fletcher Miller Smith])
    (!= e 'Baker)
    (!= a 'Cooper)
    (!= a 'Fletcher)
    (!= e 'Fletcher)
    (beforeo 'Cooper 'Miller tenants)
    (not-adjacento 'Smith 'Fletcher tenants)
    (not-adjacento 'Fletcher 'Cooper tenants)))

;; ([Smith Cooper Baker Fletcher Miller])

A: I just started journeying into LP myself, and my first effort is https://github.com/amalloy/doors, a solver for the automatically-generated logic puzzles at http://rooms.jmpup.com. Right now I have some relations defined that are generally-useful for all puzzles, but I haven't done any work on actually translating a particular puzzle into core.logic programmatically. You can see the one puzzle I've manually translated - webpage presentation and core.logic encoding. Perhaps this will give you an idea of how to use core.logic, although I'm still new to it myself so there are bound to be imperfections.
Edit
After looking over the picolisp solution, I don't think it translates directly to core.logic because, as far as I know, direct negation support does not exist yet.


text:
Q: How to set full auto width for input tag I have 3 elements inline, first is span with image and defined with using padding left and right, I don't want to resize her width, just only like now width padding left and right.
My problem is on different resolution to fit this 3 inline element to be fit to container full 100% width.
How to set resizable width for INPUT on different resolution.
On small resolution I may to write new smaller width for INPUT tag.
Is it possible to set resizable input tag.
I want three elements to be 100% width in container of 90%, without resizing span elements, only INPUT.
I tried for this set width:78% of input tag, but thats it for large resolution, how to set for all resolution?
Is it posible to do using only HTML and CSS??
https://jsfiddle.net/4654eaue/4/
HTML

    <input type="text" name="fname" value="John Doe" disabled class="profileusername bordertop">

CSS
.container{
    width:90%;
}
input{
    width:78%;
    vertical-align:top;
    display:inline-block;
    height:23px;
}
span img{
    vertical-align:middle;
    padding-right:10px;
    padding-left:10px;
}
span{
    vertical-align:top;
    display:inline-block;
    background-color:grey;
}

A: Well, try this :
There is JSFiddle example
I remove those spans but add one div and place input inside him. I had to change input height to 29px ... using display:table; for container and for img and div table-cell .... if that's ok for You.
html :

<input type="text" name="fname" value="John Doe" disabled class="profileusername bordertop">

css :
.container{
    width:90%;
    display:table;
}
.container div {display:table-cell; width:100%; vertical-align:top; }
input{
    width:100%;
    box-sizing:border-box;
    height:29px;
    vertical-align:top;

}
.container img{
    vertical-align:middle;
    padding-right:10px;
    padding-left:10px;
    background-color:gray;
    display:table-cell;
}

Update :
There is example where input fixed height is avoided. Much better solution in comparing with above one. Simple, input height will fit to img height and rest of total width of container.
New fiddle example

A: Is this what you are going for? https://jsfiddle.net/4654eaue/10/
I added a background color to the container so that you can see it takes up all of it https://jsfiddle.net/4654eaue/11/
I used the css calc()
like this:
input{
    width: calc(100% - 125px);
    vertical-align:top;
    display:inline-block;
    height:23px;
}

So the input is now 100% of the 90% (minus the width of the span)

A: Try to use display:table, display:table-row, display:table-cell
HTML:

        <input type="text" name="fname" value="John Doe" disabled class="profileusername bordertop">

CSS:
.container{
    width:90%;
    display: table;
}
.wrapper {
    display: table-row;
    width: 100%;
}
input{
    vertical-align:top;
    display:table-cell;
    height:23px;
    width: 100%;
}
span img{
    vertical-align:middle;
    padding-right:10px;
    padding-left:10px;
}
span{
    vertical-align:top;
    display:table-cell;
    background-color:grey;
    width: 49px;
}

Working example: https://jsfiddle.net/4654eaue/4/


text:
Q: Solving differential system with repeated eigenvalue I am trying to solve $$ \frac{dx}{dt}=\begin{bmatrix}
1 &-2  & 0\\
2 & 5 & 0\\
2 &1  &3
\end{bmatrix}x$$
and find that it has only one eigenvalue $3$ of multiplicity $3$. Also, $ \begin{bmatrix}
0\\
0\\
1\end{bmatrix}$ is an eigenvector to $3$ and so, $ \begin{bmatrix}
0\\
0\\
1\end{bmatrix}e^{3t}$ is a solution to the system. Now in my book, if an eigenvalue is repeated twice, then it says how to achieve another solution. But, this eigenvalue is repeated thrice and I have no idea how to proceed further.

A: $$x'=Ax$$
You have a first eigenvector $v_1=\pmatrix {0,0,1}^t$ and a solution $x_1=v_1e^{3t}$
.Then for a second vector you have to calculate $v_2$:
$$(A-3I)v_2=v_1$$
$$\pmatrix {-2 & -2 &0 \\ 2&2&0 \\ 2&1&0} \pmatrix {v_{21} \\v_{22} \\v_{23}}=\pmatrix {0 \\0\\1}$$
You can take $v_2=\pmatrix {1 ,-1,0}^t$. Then a second solution is:
$$x_2=(v_2+tv_1)e^{3t}$$
For the third eigenvector solve for $v_3$:
$$(A-3I)v_3=v_2$$
Then the solution is:
$$x_3=e^{3t} \left(\dfrac {t^2}2v_1+tv_2+v_3\right)$$
And the complete solution is:
$$x(t)=c_1x_1+c_2x_2+c_3x_3$$


text:
Q: Imagemagick crop transparent image to mask So here is my original image (note the transparent border) src.png:

Here's the mask I want to use to crop. White means keep, black means crop mask.png: (Note that it isn't necessarily going to be a square. It could be a heart or a star or anything)

I also have transparent.png, which is a fully transparent image. All three images have the same dimensions.
So, running this command generates the following image:
convert transparent.png src.png mask.png -composite out.png

Which is masking perfectly, but now I want it cropped to the size of the white mask area. Using -trim is sort of close, but it gets rid of the transparent areas that are inside the mask.
How can I resize the masked image to the size of the white area in the mask?

A: I am not sure I understand what you want for the result. Why do you need the fully transparent image?  Do either of these do what you want?
Full sized transparent image with masked area showing:
convert src.png mask.png -alpha off -compose copy_opacity -composite result1.png

Trimmed to just the part you want:
convert src.png mask.png -alpha off -compose copy_opacity -composite -trim +repage result2.png

A: Not sure I understand what you are trying to do, not least why you need a full size transparent canvas. Your command does not give the same results on my ImageMagick version 7.
This command may be what you are looking for:
convert src.png mask.png -compose darken -composite -trim out.png

It gives this - I have artificially added a red border so you can see the full extent on StackOverflow's white background:

Or maybe you want the trim box from your mask and to use that to crop your source:
convert mask.png -format %@ info:
113x113+570+33

convert src.png -crop 113x113+570+33 result.png

A: If you want to crop a square from picture, you no needs using mask, just crop it:
magick Uq328.png -crop -crop 111x111+570+331 +repage cropped.png
according to https://legacy.imagemagick.org/Usage/crop/


text:
Q: How to use ServiceStack to get denormalized array of objects Could someone please provide or link to a simple-as-can-be example of how to use ServiceStack to return a denormalized array of objects from an existing SQLServer database with several joins?
The returned objects would only have a small subset of the columns from the query, and will have different names.
I would have preferred to use ORMLite, but am happy to use EF if need be.  I will be using this for read only operations.
E.g. if I was to query a db with the following joined tables: Customer, Order, Orderline, I would like to return a De-normalized list, like the following, but using different column names than used on the db:

*

*Customer Name

*Order Date

*OrderLine Number

*Prod Desc

*Qty

A: In OrmLite you can always fallback to custom SQL if you ever need to do a complex query or custom joins, e.g:
List<CustomerProductOrder> results = db.Select<CustomerProductOrder>(
  @"SELECT c.Name, o.Date, ol.Number, p.Desc, o.Qty
      FROM Order o INNER JOIN Customer c ON (o.CustomerId = c.Id) ...
     WHERE o.Id = {0}", 1001);

Or alternatively by using a parameterized query, e.g:
List<CustomerProductOrder> results = db.Query<CustomerProductOrder>(
  @"SELECT c.Name, o.Date, ol.Number, p.Desc, o.Qty
      FROM Order o INNER JOIN Customer c ON (o.CustomerId = c.Id)  ...
     WHERE o.Id = @orderId", new { orderId = 1001 });

Where CustomerProductOrder is a denormalized POCO for this query which will populate all the properties with the matching columns from the result set.
More OrmLite querying examples can be found on OrmLite's API Overview.


text:
Q: Convert tex to html with a xltabular I am trying to convert from tex to html. For this I use htlatex with the following command.
htlatex.exe %FILENAME%.tex "xhtml,html5,mathml,charset=utf-8" " -cunihtf -utf8"
In my tex file I use an xltabular. I get the following error message.
! Missing number, treated as zero.
<to be read again>
                   \ar:cnt
l.382 \end{xltabular}

That is the code of the xltabular
\begin{xltabular}{\textwidth}{l}
Test1\\
Test2
\end{xltabular}

Can anyone tell me where the problem lies I have no idea where the problem is. I can convert it to PDF without any problem.
Thank you in advance.


text:
Q: How to loop through all the referrer urls in Local storage? I have three different Urls displayed in the local storage. This happens upon clicking on the radio button for paypal express checkout. I want to access the second url https://www.sandbox.paypal.com but unfortunately, the code that I have written below will loop only for the first one https//master...... Can anyone please guide me on how do I access the second/third url in a local storage.
Code that I have for looping Local storage -
Object.entries(localStorage).forEach(([ key, value ]) => {
console.log(`${key} => ${value}`); })

Local storage screenshot -


text:
Q: Error message: "Operation value must be a number", on creation of new JIRA issue When creating a new JIRA issue using REST API in VBA, I'm getting the following error message for custom field 13744: "Operation value must be a number".
I've tested the following code without the numeric field, and everything works fine, the issue is created and all the other fields value are passed:
Public Pass As Variant

 Sub criarIssue()

    Dim JiraService As New MSXML2.XMLHTTP60
    Dim sErg As Variant
    Dim sRestAntwort As Variant
    Dim sSummary As Variant
    Dim sDescription As Variant
    Dim sProject As Variant
    Dim sIssueType As Variant
    Dim sData As Variant
    Dim sPath As Variant
    Dim sUsername As Variant
    Dim sPassword As Variant
    Dim sAux As Variant
    Dim sStatus As Variant
    Dim sEncbase64Auth As Variant

    sUsername = Environ$("UserName")
    Senha.Show

    sPassword = Pass

    sSummary = ActiveSheet.Range("C3").Value 'Issue name
    sIssueType = "Projeto"
    sProject = "EXP"

    sData = " { ""fields"" : { ""project"" : { ""key"" : """ & sProject & """ }, ""summary"" : """ & _
    sSummary & """, ""issuetype"" : { ""name"" : """ & sIssueType & """}, ""customfield_13744"" : ""1234"", ""customfield_13663"" : {""name"" : ""vitor.ribeiro""}, ""customfield_13670"" : ""2019-01-23 00:00:00"", ""customfield_13671"" :  {""value"" : ""SP"" , ""child"" : {""value"" : ""SAO PAULO"" }}}} "

    sEncbase64Auth = EncodeBase64(sUsername & ":" & sPassword)

    'Creates Issue
    With JiraService
        .Open "POST", "http://172.16.2.128:8080/rest/api/2/issue/", False
        .SetRequestHeader "Content-Type", "application/json"
        .SetRequestHeader "Accept", "application/json"
        .SetRequestHeader "X-Atlassian-Token", "nocheck"
        .SetRequestHeader "Authorization", "Basic " & sEncbase64Auth
        .Send (sData)
        sRestAntwort = .ResponseText
        sStatus = .Status & " | " & .StatusText
    End With

    ' JSON Response
    sAux = Replace(sRestAntwort, "{", "")
    sAux = Replace(sAux, "}", "")
    sAux = Split(sAux, ",")
    sAux = sAux(1)
    sAux = Split(sAux, ":")
    sAux = sAux(1)
    sAux = Replace(sAux, """", "")

    ActiveSheet.Range("J2").Value = sStatus
    ActiveSheet.Range("J3").Value = sRestAntwort & " | " & sAux
    ActiveSheet.Range("J4").Value = ActiveSheet.Range("J4").Value + 1
    ActiveSheet.Range("C2").Value = sAux

    With JiraService
    .Open "DELETE", "http://172.16.2.128:8080/rest/auth/1/session", False
        .Send
        End With

End Sub

Public Function EncodeBase64(text As String) As String

    Dim arrData() As Byte
    arrData = StrConv(text, vbFromUnicode)

    Dim objXML As MSXML2.DOMDocument
    Dim objNode As MSXML2.IXMLDOMElement

    Set objXML = New MSXML2.DOMDocument
    Set objNode = objXML.createElement("b64")

    objNode.DataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.text

    Set objNode = Nothing
    Set objXML = Nothing

End Function

All but custom field 13744 values are passed without a problem.
For this one I get the following error message:
{"errorMessages":[],"errors":{"customfield_13744":"Operation value must be a number"}
Why isn't it recognized as a number?

A: It turns out I just had to pass de numeric value without quotes, as suggested by @cyboashu. It's working now.

A: You must delete punctuation mark "


text:
Q: Commutator is a 3-cycle if... Suppose $n \ge 3$ and $g,h \in S_{n}$ are such that the only non-fixed point of both $g$ and $h$ is $k$.  I am trying to prove that the commutator of $g$ and $h$ is a 3-cycle with the only non-fixed points are $k, g(k)$, and $h(k)$. I think you would only need to look at four cases, computing each of these points under the commutator and one other point that is not any of these. So first, I used the convention that for any $\sigma, \tau \in S_{n}$, $\sigma\tau$ is the composition $\sigma \circ \tau$.
Now, assume $g(k) = i$ for some $i \neq k$ and $h(k) = j$ for some $j \neq k$. The first intuition is to apply the commutator to $k$: $ghg^{-1}h^{-1}(k)$.
I am not sure on how to proceed and deal with the inverses, but I think I am on the right track.

A: $h^{-1}(k)$ is not $k$, so it is different from $k$ and it is not a fixed point of $h$. This means that it is a fixed point of $g$ and thus of $g^{-1}$.
Therefore, $ghg^{-1}h^{-1}(k)=ghh^{-1}(k)= g(k)$.
A similar calculation with argument $h(k)$, $g(k)$ and finally $m$ different than the three numbers will give you the desired result.


text:
Q: Karate Automation Test Framework - need access to list of features included in run from karate-config.js From karate-config.js I need to know what .feature files are included in the run.  Is there an easy way to access that?
As a work around, have discovered that if I re-write Karate's Runner.parallel function, I can pass the feature names in an argument:
...
Map<String, Object> args = new HashMap<String,Object>();
...
String featureList = "";
for (int i = 0; i < count; i++) {
   Resource resource = resources.get(i);
   Feature feature = FeatureParser.parse(resource);
   featureList = featureList + feature.getName();
}
args.put("featureList", featureList);
...
CallContext callContext = CallContext.forAsync(feature, options.hooks, options.hookFactory, args, false);

However, I dont know how to access the featureList argument from karate-config.js.
Is there an easy way to access the list of feature for a test run from karate-config.js?

A: This is not supported today. This is unlikely to be supported unless you contribute code because no one has ever requested this.
Do note that if you are anyway creating a list of features before you start the test, you can pass that to karate-config.js by means of a Java singleton.


text:
Q: Optimum phase margin Controller Design I am designing a PI voltage and current Controller (Cascaded Control for Buck Converter with LC filter) and I am confused about what is the perfect phase margin to choose for the application.
I read and found out that the recommended phase margin is between 45 to 60 degrees for stable operation but I do not know which would be the optimum value for my application. I just know that 45 degrees might give a good transient response.
Is there a specific calculation using which I can decide which phase margin would be good for my application? Is comparing the settling time one of the criteria with which I can judge the optimum phase margin?
For Phase Margin = 60 (Stable)

*

*Voltage Controller Gain = 5.6398 A/V

*Voltage Controller Reset Time = 82.699μs

*Current Controller Gain = 5.1322e+04 V/A

*Current Controller Reset Time = 13.783μs

For Phase Margin = 45 (Stable)

*

*Voltage Controller Gain = 16.0719 A/V

*Voltage Controller Reset Time = 23.734μs

*Current Controller Gain = 7.2580e+04 V/A

*Current Controller Reset Time = 7.9577μs

For 45 degrees I do get lower reset time but the higher gain requirement. How do I find the optimum phase margin?
Requirement : Overshoot = 5 to 10%
Low settling time and lower voltage error.

A: When someone asks what amount of phase margin (PM) is acceptable, the answer should be "what transient response do you want?". If you need a fast-recovery system and tolerate some overshoot or, on the contrary, you cannot suffer overshoot at all and want the most conservative design, then these are two different phase margin goals.
For a second-order system, without any zeroes, it is possible to link the open-loop phase margin (the one you measure with a network analyzer for instance) with the closed-loop quality factor (when the converter regulates). It is a simplified approach but explains well the link between the design goal and the closed-loop performance:

Practically speaking, if you can't tolerate overshoot and accept a sluggish response, you can shoot for a 90° PM. This is a very conservative design but military and space applications usually require this type of margin. For practical design, shooting for 60-70° PM is a good starting point, giving enough freedom to endure unavoidable components values changes during production and operating life. If you want a "nervous" system, you will purposely reduce the phase margin, giving a faster recovery time but to the expense of some overshoot. A value closer to 45-50° is probably a better fit in this case. Keep in my mind that this is a typical value and it will move up and down as explained before hence the necessary margin. You have to ensure through sensitivity analyses or Monte Carlo that the PM does not approach 30° or so or unacceptable ringing will occur. The ringing can either trip the converter over-voltage protection circuitry or damage the downstream applications.
Below is a picture excerpted from my APEC 2018 seminar illustrating how playing with the phase margin brings different transient responses:

That being said, some converters are easier to stabilize than others: the buck and its derived family (forward, half-bridge etc.) are phase-margin friendly most of the time. It goes differently with non-minimum-phase converters like the boost or the buck-boost to cite the basic switching cells. The presence of the right-half-plane zero can make the compensation strategy a difficult exercise and having 50° for PM is sometimes the best you can obtain. Finally, keep in mind that specifying numbers with 3 or 4 digits behind the comma - as you did in the question - does not really make sense when you go to the bench and solder components affected by large tolerance for some of them : )


text:
Q: AJAX Function Not Respecting Local or Global Variable I'm new to jQuery and am struggling to figure out an issue that's plaguing me.
In my code, I am appending a new form after a DIV, and have set up a custom button for submission.  I set up an on-click jQuery event, but am having trouble accessing one of the local variables successfully.
....
callbacks {
  open function() {
    this.wrap.on('click.pinhandler' .socialLink', function(e) {
var fileName = $(this).attr('fileName');
var eventName = $(this).attr('eventName');
var destination = "test@test.com";
$(".test-area").after('<input type="email" id="emailShare" placeholder="enter your email">

GO

');
  });
 }
}
...

This is all embedded in a callback from a Magnific Popup button, in which a user clicks a button within the popup and the above is triggered.  In my code, I am setting the global destination variable with the code;
destination=$("#emailShare").val();
Just before my AJAX call, I am logging the state of destination, with successfully reports the proper user input of the #emailShare text field.  I am logging like so;
console.log("About to send mail to " + destination)
Both before the call, and in the response, I am successfully logging the proper variable.  But the actual variable being sent to the API is still the global variable, having never been updated.
I recognize this is complex, but I"m unsure if there's a better way...

A: For anyone that stumbles across this, @taplar's comment in the above question got me on the right path.  Specifically, this Stackoverflow post, discussed how to bind to dynamically created elements.
By refactoring my code, I ended up using the following;
$(document).on('click', '.doSocial', function(){
  //stuff happens here
});

In my case, .doSocial is a class applied to dynamically created buttons.  Once the user clicks a .doSocial button, I use the //do stuff here section to add my additional dynamic HTML elements, including the form field which is now recognized by my AJAX function.  If @taplar would like to answer, I'll happily mark it as correct.


text:
Q: Wait until condition in selenium How to put a wait condition in selenium web-driver for assert load. I want to test a web application, that application have background audio.
I can able to write a wait condition for DOM element is loaded or not. But how can I put wait condition for audio file whether it was fully loaded or not.

A: wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromMinutes(1));
wait.Until(ExpectedConditions.ElementToBeClickable(yourlocator));


text:
Q: Как удалить определенное значение из текстового файла? Python Имеется ids.txt файл с id пользователей в каждой строке:
1234
1256
5125
6246

Нужен код, который удаляет запрашиваемый id, если такой имеется в документе.
del = input('id')

ids = open('ids.txt', '*режим*' , encoding='UTF-8')
if del in ids:
    #код для удаления id в переменной del из файла ids

Если есть чудо-способ без удаления и создания нового файла, то буду очень рад

A: Можно просто перезаписать текущий файл. Открыть его сначала на чтение, поместить строки в переменную, потом на запись и записывать в него то, что вам нужно
with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "ненужный id":
            f.write(line)

Или вот такой способ с одним опеном, подсмотрел его на англоязычном SO, но не проверял. Открываем файл в режиме "r+":
with open("yourfile.txt", "r+") as f:
    lines = f.readlines()
    f.seek(0) # устанавливаем указатель в начало файла, перед имеющимися значениями
    for line in lines:
        if line != "ненужный id":
            f.write(line)
    f.truncate() # усекаем файл до позиции, на которой стоит указатель в данный момент

И не называйте переменные именами имеющихся дефолтных функций/методов (del)


text:
Q: Implement Cloudinary Signed Upload in Kotlin I am having a tough time in implementing signed upload to Cloudinary using Kotlin. I have implemented my backend to provide me a signture and timestamp. This is what I have done to build the config:
var config = HashMap<String, Any> ()
        config.put("cloud_name", "my_cloud_name");
        //config.put("apiKey", my_api_key);
        config.put("use_filename", true);

Now, I am unable to do the MediaManager.init using the signature. Can anyone please help? The Java code says to do the below, but I am unable to reproduce the same in Kotlin:
MediaManager.init(this, new SignatureProvider() {
    @Override
    public Signature provideSignature(Map options) {
        // call server signature endpoint
    }
}, null);

A: This is how you intialize MediaManager with a signature provider in Kotlin:
MediaManager.init(thiscontext!!, object: SignatureProvider {
        override fun provideSignature(options: MutableMap<Any?, Any?>?): Signature {
            return myBackendConnector.signRequest(options)
        }

        override fun getName(): String {
            return "myCustomSignatureProvider"
        }

    }, config)

This will work assuming your backend already has the api key (it should), and that the return type from your connector is Signature. Otherwise you'll need to adapt your backend's result to Signature (populate the POJO with the result your server provided).

A: Get the timestamp and signature from your backend then add those as options.
val options = mapOf(
  "timestamp" to // timestamp from backend,
  "signature" to // signature from backend,
  // other options from backend
)
MediaManager.get()
            .upload(uri)
            .options(options)
            .callback(uploadCallback)
            .dispatch()

So this means not creating a SignatureProvider in the MediaManager.init().
I came to using this because I could not get this to work with the SignatureProvider in the MediaManager.init().


text:
Q: Can someone see what's wrong in this code in GML? var xpos = 0;
var ypos = 0;
xpos = obj_magnet.x;
ypos = obj_magnet.y;
if (xpos > 435 && xpos < 704 && ypos > 350 && ypos < 640)
{
    with(obj_lamp)
    {
        instance_change(obj_lamp_light, true);
    }
    if obj_lamp_light.image_index == 5
    {
        obj_lamp_light.image_speed = 0;
    }
    with(obj_arrow)
    {
        instance_change(obj_arrow_move_one_direction, true);
    }
    if obj_arrow_move_one_direction.image_index == 4
    {
        obj_arrow_move_one_direction.image_speed = 0;
    }
    with(obj_arrow_move_opposite_direction)
    {
        instance_change(obj_arrow, true);
    }
    exit;
}
else
{
    with(obj_lamp_light)
    {
        instance_change(obj_lamp, true);
    }
    with(obj_arrow_move_one_direction)
    {
        instance_change(obj_arrow_move_opposite_direction, true);
        if obj_arrow_move_opposite_direction.image_index == 4
        {
            obj_arrow_move_opposite_direction.image_speed = 0;
        }
    }
    exit;
}

This is a game which I am trying to create where the obj_arrow_move_opposite_direction and obj_arrow_move_one_direction contains 5 sub images and the obj_lamp_light contains 5 sub images.

A: You stated that each object contains 5 sub-images, correct? Looks like you're looking for a nonexistent sub-image (5) on line 7.
This appears to be a simple typo, but if not it's important to note that image_index starts at 0. So 5 images would be 0-4, rather than 1-5.
var xpos=0;
var ypos=0;
xpos=obj_magnet.x;
ypos=obj_magnet.y;
if(xpos>435&&xpos<704&&ypos>350&&ypos<640) { with(obj_lamp){
instance_change(obj_lamp_light,true);} if
obj_lamp_light.image_index==5{ obj_lamp_light.image_speed=0;} // should be object_lamp_light.image_index == 4
with(obj_arrow){
instance_change(obj_arrow_move_one_direction,true);}
if obj_arrow_move_one_direction.image_index==4{
obj_arrow_move_one_direction.image_speed=0;}
with(obj_arrow_move_opposite_direction){
instance_change(obj_arrow,true);}
exit;
}
else{
with(obj_lamp_light){
instance_change(obj_lamp,true);}
with(obj_arrow_move_one_direction){
instance_change(obj_arrow_move_opposite_direction,true);
if obj_arrow_move_opposite_direction.image_index==4{
obj_arrow_move_opposite_direction.image_speed=0;}}
exit;
}

Better yet, if you're checking to make sure that the object's image_indexes are equal to the last sub-image you could use image_number and subtract by one. This way if you ever add more sub-images you could ensure your code is still checking for the last frame.