text:
Q: Hello World With NRF24L01 I have Arduino and a Duinotech NRF24L01, I am trying to send the string "Hello world" with maniacs bug RF24 library however, I think it cannot detect the incoming RF signal.
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(7, 8); // CE, CSN

    const uint64_t pipe = 0xF0F0F0F0E1L;
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(0, pipe);
      radio.startListening();

    }

    void loop() {
      if (radio.available()) {
        char text[32] = "";
        radio.read(&text, sizeof(text));
        Serial.println(text);
      }
      else {
        Serial.println("Data was not found");
      }

In the read code, it would always execute data was not found. This makes me think that maybe it does not find the RF signal at all.
Here is the code that writes the data.
 #include <SPI.h>
 #include "nRF24L01.h"
 #include "RF24.h"

 RF24 radio(7, 8); // CE, CSN
 int text = 1;
 const uint64_t pipe = 0xF0F0F0F0E1LL;

 void setup() {
   Serial.begin(9600);
   radio.begin();
   radio.openWritingPipe(pipe);
   radio.stopListening();
 }
void loop() {
  radio.write(&text, sizeof(text));
  Serial.println("Sending Data");
  delay(1000);
 }

A: Try this
For the transmitter Instead of const uint64_t pipe = 0xF0F0F0F0E1LL; use const byte address[6] = "00001"; as the address and then have you void setup like the code below
void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

Then ensure that you have a value set for the test variable to be transmitted as below
 void loop() {
      const char text[] = "Hello World";
      radio.write(&text, sizeof(text));
      Serial.println("Sending Data");
      delay(1000);
    }

At the receiver end have this code running
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text); //This will print out the received value
  }
}

PS: Ensure that all the connections are done to the right pins
AND you can test if the NRF24L01 chip is connected correctly by adding the code below
bool result = radio.isChipConnected ();

Serial.println (result);

it should print out a 1 to the serial monitor if the NRF24L01 chip is connected correctly


text:
Q: Facing issue with UISwitch on/off There are 6 switch controls in the screen. At one time only one switch should be enable.If 5th switch is on then, one label and one text field should be visible either it should be hidden.
I am facing issue, when 5 switch is changed to on from off and again changed to off. The label and text filed should be hidden but it's not working as per requirement.
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.sw_switch1.on = NO;
    self.sw_switch2.on = NO;
    self.sw_switch3.on = NO;
    self.sw_switch4.on = NO;
    self.sw_switch5.on = NO;
    self.sw_switch6.on = NO;

    lbl_desc.hidden = YES;
    txt_desc.hidden = YES;

}

-(IBAction)switchChange:(id)sender
{

        if(sw_switch1.isOn)
        {
            //self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;

        }

        else if(sw_switch2.isOn)
        {
            self.sw_switch1.on = NO;
            //self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;

        }

        else if(sw_switch3.isOn)
        {
            self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            //self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;

        }
        else if(sw_switch4.isOn)
        {
            self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            //self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;

        }

        else if(sw_switch5.isOn)
        {
            self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            //self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;
            lbl_desc.hidden = YES;
            txt_desc.hidden = YES;

        }

        else if(sw_switch6.isOn)
        {
            lbl_desc.hidden = NO;
            txt_desc.hidden = NO;
            self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            //self.sw_switch6.on = NO;
        }

    [self viewWillAppear:NO];

}

A: You hide the labels (.hidden = YES) when the switched is swithed to on. But you do not unhide (.hidden=NO) when the others are switched off. Your code is a bit unlogical anyway.
I suggest:
-(IBAction)switchChange:(id)sender
{

            UISwitch *theSwitch = (UISwitch *) sender;
            BOOL switchState = theSwitch.on; //this method is called when changed to on or off.

            self.sw_switch1.on = NO;  // force all switches off
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;

            theSwitch.on = switchState; // recover the state set by the user.

            //now hide or unhide the labels depending on the state of switch 5.
            lbl_desc.hidden = self.sw_switch5.on;
            txt_desc.hidden = self.sw_switch5.on;

    // [self viewWillAppear:NO];   // What the h.... is this? You are not supposed to call that method. Use self.view.setNeedsDisplay or so instead.

    [self.view setNeedsDisplay];  // This may not be reqired but it forces the view to re-display itself.

}

A: You can try this
if(sw_switch5.isOn)
        {
            self.sw_switch1.on = NO;
            self.sw_switch2.on = NO;
            self.sw_switch3.on = NO;
            self.sw_switch4.on = NO;
            //self.sw_switch5.on = NO;
            self.sw_switch6.on = NO;
            lbl_desc.hidden = NO;
            txt_desc.hidden = NO;
        }
        else
        {
            lbl_desc.hidden = YES;
            txt_desc.hidden = YES;
        }

My suggestion is you should use tag value also for each switch control.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    sw_switch1.tag = 101;
    sw_switch2.tag = 102;
    sw_switch3.tag = 103;
    sw_switch4.tag = 104;
    sw_switch5.tag = 105;
    sw_switch6.tag = 106;
    self.sw_switch1.on = NO;
    self.sw_switch2.on = NO;
    self.sw_switch3.on = NO;
    self.sw_switch4.on = NO;
    self.sw_switch5.on = NO;
    self.sw_switch6.on = NO;

    lbl_desc.hidden = YES;
    txt_desc.hidden = YES;

}

Edit: Use the tag value like this if((theSwitch.tag == 105) && self.sw_switch5.on).
Now you can the try the below optimized code
-(IBAction)switchChange:(id)sender
{
    UISwitch *theSwitch = (UISwitch *) sender;
    BOOL switchState = theSwitch.on; //this method is called when changed to on or off.

    self.sw_switch1.on = NO;  // force all switches off
    self.sw_switch2.on = NO;
    self.sw_switch3.on = NO;
    self.sw_switch4.on = NO;
    self.sw_switch5.on = NO;
    self.sw_switch6.on = NO;

    lbl_desc.hidden = YES;// force the label and textfield should be hidden
    txt_desc.hidden = YES;

    theSwitch.on = switchState; // recover the state set by the user, so at a time only one switch should be on

    //now hide or unhide the labels depending on the state of switch 5 only

    if((theSwitch.tag == 105) && self.sw_switch5.on){
    lbl_desc.hidden = NO;
    txt_desc.hidden = NO;
    }
    else{
        lbl_desc.hidden = YES;
        txt_desc.hidden = YES;
    }

    [self.view setNeedsDisplay];

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java thread not stopping even after calling cancel method? public class my {
public static void main(String[] args) throws InterruptedException {
    SomeService service = new SomeService();

    CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
        try (AutoClosableResource<SomeService> resource = new AutoClosableResource<>(service, service::disconnect)) {
            resource.get().connect();
            int i = 0;
            while (true) {
                System.out.println("--------------inside while" + i);
                Thread.sleep(500);
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    System.out.println("ouside while");
    Thread.sleep(2500);
    async.cancel(true);
    System.out.println(async.isCompletedExceptionally());
    Thread.sleep(1000);

}

public static class SomeService {
    public void connect() {
        System.out.println("connect");
    }

    public Integer disconnect() {
        System.out.println("disconnect");
        return null;
    }
}

public static class AutoClosableResource<T> implements AutoCloseable {

    private final T resource;
    private final Runnable closeFunction;

    private AutoClosableResource(T resource, Runnable closeFunction) {
        this.resource = resource;
        this.closeFunction = closeFunction;
    }

    public T get() {
        return resource;
    }

    @Override
    public void close() throws Exception {
        closeFunction.run();
    }
}

}
-------output--------

ouside while connect
--------------inside while0
--------------inside while1
--------------inside while2
--------------inside while3
--------------inside while4 true
--------------inside while5
--------------inside while6

Q: Why thread is still running and printing isCompletedExceptionally() = true even I'm manually stopping it with, async.cancel(true);

A: Short answer:
Thread is still running because CompletableFuture
cancel method has no effect to runAsync process, and doesn't interrupt the Thread.
async.isCompletedExceptionally() returns true, because cancellation throws exception CompletionException
The details:
Info from javadoc about cancel method:

If not already completed, completes this CompletableFuture with a
  CancellationException. Dependent CompletableFutures that have not
  already completed will also complete exceptionally, with a
  CompletionException caused by this CancellationException

This method just complete CompletableFuture and methods, which dependent from waiting the result getting CompletionException caused by this CancellationException. Method should be used not to interrupt thread, but to finish work on dependent methods. Future would be completed exceptionally
You should use this method in processes, where you make some work, and decided to cancel it
So, your thread continue work and terminates because of System.exit()
look into public static ForkJoinPool commonPool() javadoc

Returns the common pool instance. This pool is statically constructed;
  its run state is unaffected by attempts to shutdown or shutdownNow.
  However this pool and any ongoing processing are automatically
  terminated upon program System.exit. Any program that relies on
  asynchronous task processing to complete before program termination
  should invoke commonPool().awaitQuiescence, before exit.


text:
Q: SOAPUI - Insert a collection of objects in a single value field How can I insert this collection of objects into a single value? (for a POST request)
"data": {
    "Idtest": 1,
    "Nametest": "test",
    "OBJECT" : {
                  "ID":1,
                   "NameTest": "BLA"
                }
  }

*

*The parameter is: OBJECT.

*And I want to insert in a value field this collection: {"ID":1,
"NameTest": "BLA" }

Is this step possible in SOAPUI?

A: This should work:

Does it help?
Maybe you want to send parameter "data", then it should be like:


text:
Q: Why does the compiler tell me that no operators match the operand type in my 'if' and 'else if' statements? What is the problem in this code? I have been trying, but I don't know why I can't use = or == in the if statement.
#include <vector>

#include <cstdlib>

#include <time.h>

using namespace std;

/* I am trying to make the program output a periodic t symbol

so then it asks the user what the element is */

void symbols(std::vector<std::string> alcalinos) {

alcalinos = { "H", "Li", "Na", "K", "Rb", "Cs", "Fr" };

std::string elemento;

cout << "Introduce el elemento correspondiente al símbolo(en minusculas) : \n";

srand(time(NULL));

int random = rand() % 7;

cout << alcalinos[random];

cin >> elemento;

if ((alcalinos = "H") && (elemento = "hidrogeno")) {

    cout << "correcto\n";

}

else if ((alcalinos = "Li") && (elemento = "litio")) {

    cout << "correcto\n";

}

else if ((alcalinos = "Na") && (elemento = "sodio")) {

    cout << "correcto\n";

}

else if ((alcalinos = "K") && (elemento = "potasio")) {

    cout << "correcto\n";

}

else if ((alcalinos = "Rb") && (elemento = "rubidio")) {

    cout << "correcto\n";

}

else if ((alcalinos = "Cs") && (elemento = "cesio")) {

    cout << "correcto\n";

}

else if ((alcalinos = "Fr") && (elemento = "francio")) {

    cout << "correcto\n";

}

else {

    cout << "incorrecto\n";

}

int main(); {

    void symbols();

     }

A: I must be in a good mood, I've added comments to indicate the errors you made
void symbols() { // no parameter for function

    // local declaration of vector instead of parameter
    std::vector<std::string> alcalinos = { "H", "Li", "Na", "K", "Rb", "Cs", "Fr" };

    std::string elemento;

    cout << "Introduce el elemento correspondiente al símbolo(en minusculas) : \n";

    int random = rand() % 7;

    cout << alcalinos[random];

    cin >> elemento;

    // compare alcalinos[random] not alcalinos
    // use == not =
    if ((alcalinos[random] == "H") && (elemento == "hidrogeno")) {
        cout << "correcto\n";
    }
    else if ((alcalinos[random] == "Li") && (elemento == "litio")) {
        cout << "correcto\n";
    }
    else {
        cout << "incorrecto\n";
    }
} // missing }

int main() { // no ; after main()

    srand(time(NULL)); // seed RNG once in main

    symbols(); // no void before function call
}

When you are making this many mistakes, it means that you are trying to write too much code at once. When you are a beginner add your code literally one line at a time. And test the code after each line that you add. That way you are only trying to fix one problem at a time. You will find it much easier that way.


text:
Q: ExpressionChangedAfterItHasBeenCheckedError when using scroll event In my website, the logo rotate when user scroll in the page.
The code is very basic :
Component
@HostListener('window:scroll', ['$event'])
scrollPos(){
  if (typeof window !== 'undefined') {
    return Math.round(window.scrollY);
  }
}

HTML

However, sometimes this basic code generate this error when navigating in the website :(
 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it
 was checked. Previous value: 'rotate(397deg)'. Current value: 'rotate(331deg)'.

How can I update my above codes in order to avoid having this error?
thank you for your support

A: You should generally avoid returning things from @HostListeners because... they're not supposed to be called by anything but the events they listen to;
Instead, assign window.scrollY to a property in your component and access it from your component;
public wScrollY: number = 0;

@HostListener('window:scroll', ['$event'])
scrollPos(){
  if (typeof window !== 'undefined') {
    this.wScrollY = Math.round(window.scrollY);
  }
}

Template


text:
Q: How to find the cheapeast combination of products to buy from multiple bundles for a shopping list Let's say I have different bundles of products, each associated with a price.
Name               Price      Products
Fruit Overdose     5$         2 Apples, 1 Orange, 1 Banana
Doctors Darling    1$         1 Apple
The Exotic         3.50$      2 Oranges, 1 Banana
Vitamin C          1.5$       1 Orange

And I have a shopping list, e.g. I want to buy:
4 Apples, 1 Orange, 2 Bananas.

The question
How would I go about finding the cheapest combination of bundles to buy for the given shopping list? Buying more than requested by the shopping list is valid.
I just need a language agnostic hint how I could approch this problem most efficiently.
My real world problem is a little bit more complex also including a list of products I already own; but this shouldn't really matter too much.

A: This is a dual linear programming problem:

*

*The objective you want to minimise is the total price, which is a linear function.

*The constraints can be formulated as a matrix equation, where each row corresponds with a bundle, and each column corresponds with a kind of product.

You can solve it by constructing the dual which will be a standard linear programming problem, applying a standard algorithm such as the simplex algorithm, then converting the solution back into a solution to the original dual problem.

A: This kind of problem can be solved handily with a SAT/SMT solver. Z3 is an open source solver with bindings for many languages, including a nicely integrated binding with Python.
In the solver, you just declare a few variables (4 for the weights of each bundle, and 1 for the total price). Then you write down the different constraints. In this case, the constraints are:

*

*The weights should be positive.

*The total is calculated by summing the price times the weight of each bundle.

*For each of the fruits, the desired minimum number should be bought.

Note that I calculated the price in cents to be able to work with integers, although that is not strictly necessary for Z3.
The Python code then looks like:
from z3 import *

bundles = [["Fruit Overdose", 5, {'apple': 2, 'orange': 1, 'banana': 1}],
           ["Doctors Darling", 1, {'apple': 1}],
           ["The Exotic", 3.50, {'orange': 2, 'banana': 1}],
           ["Vitamin C", 1.5, {'orange': 1}]]
desired = {'apple': 4, 'orange': 1, 'banana': 2}
num_bundles = len(bundles)

W = [Int(f'W_{i}') for i in range(len(bundles))]  # weight of each bundle: how many to buy of each bundle
TotalPrice = Int('Total')

s = Optimize()
s.add(TotalPrice == Sum([W[i] * int(b[1] * 100) for i, b in enumerate(bundles)]))
s.add([W[i] >= 0 for i in range(len(W))])  # weights can not be negative
for f in desired:
    s.add(Sum([W[i] * b[2][f]  for i, b in enumerate(bundles) if f in b[2]]) >= desired[f])

h1 = s.minimize(TotalPrice)
result = s.check()
print("optimizer result:", result)
if result == sat:
    s.lower(h1)
    m = s.model()
    print(f"The lowest price is: {m[TotalPrice].as_long()/100:.2f}")
    for i,b in enumerate(bundles):
        print(f"  Buying {m[W[i]].as_long()} of {b[0]}")

Output:
The lowest price is: 10.00
  Buying 2 of Fruit Overdose
  Buying 0 of Doctors Darling
  Buying 0 of The Exotic
  Buying 0 of Vitamin C

If you simply change the price of the Fruit Overdose to 6, the result would be:
  Buying 0 of Fruit Overdose
  Buying 4 of Doctors Darling
  Buying 2 of The Exotic
  Buying 0 of Vitamin C

The algorithm guarantees to find the best solution. In case there are multiple equally good solutions, just one of them is returned.


text:
Q: What is missing to get Oracle SELECT DATE type (DD-MON-YY) field ORDER BY field DESC to sorts on YY and not DD? Been trying to figure out why the sorting is being done by the DD of the value which is in the format of DD-MON-YY and not on the YY.
SELECT MY_DATE
FROM MY_DB
ORDER BY MY_DATE DESC;

Originally I had some TO_CHAR and TO_DATE functions in this but now it is as basic as it can be and yet it is still not sorting as I would expect it to.


text:
Q: Determining order of poles. I'm having some trouble understanding how to tell the order of poles. I understand simple cases I've seen online, but how about in something like ($z^{2}+1$)/($z^{3}-1)$? There's a pole at 1 and I think its of order 1. My questions arise when I split it into the form f(z)=g(z)/$(z-z_{0})^{m}$. In this case would g(z)=($z^{2}+1$) and have ($z^{3}-1)^{-1}$?

A: Your rational function factors as $$\frac{z^2+1}{(z-1)(z-\omega)(z-\omega^2)}$$ where $\omega=e^{2i\pi/3}$. So it has poles of order one at $1,\omega,$ and $\omega^2$: the order of a pole is just the multiplicity of the zero of the denominator at that pole, assuming you've cancelled common factors.


text:
Q: How to get the real type in a string? How can I get the real type that is in the string in c#?
For example, the method gets a string- "123" and it need to find it's real type- int, and convert this string to an int variable. Is there a simple way to do it?
Thanks in advance.

A: No, it's not possible. In your case, there are different types, that could be possible: int, short, long...
You should decide to what type you want to parse your string.


text:
Q: Fix foreign key issue: There are no primary or candidate keys in the referenced table CREATE TABLE Customer_MDM.membership_registration
(
    registration_num INT Primary key,
    registration_location VARCHAR(25),
    customerID INT /* FOREIGN KEY Customer details */,
    first_name VARCHAR(25),
    last_name VARCHAR(25),
    dob DATE,
    marital_status VARCHAR(25),
    gender VARCHAR(25),
    occupation VARCHAR(25),
    income_level VARCHAR(25),
    date_enrolled VARCHAR(25),
    phone_number VARCHAR(25),
    email VARCHAR(30),
    city VARCHAR(25),
    state VARCHAR(25),
    zipcode INT
);

Then:
CREATE TABLE Customer_MDM.loyalty_data
(
    customerID INT,
    loyalty_level INT,
    customer_age INT,
    reward_points INT,
    average_amount_spend INT,
    first_name VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    last_name VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    dob DATE /* FOREIGN KEY ('Membership_registration') */,
    marital_status VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    gender VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    occupation VARCHAR(25) /* FOREIGN KEY (Membership_registration'') */,
    income_level VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    city VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    state VARCHAR(25) /* FOREIGN KEY ('Membership_registration') */,
    zipcode INT /* FOREIGN KEY ('Membership_registration') */,
    PRIMARY KEY(customerID,loyalty_level)
);

Finally:
ALTER TABLE Customer_MDM.loyalty_data
    ADD FOREIGN KEY (first_name)
        REFERENCES Customer_MDM.membership_registration(first_name);

Trying to execute the ALTER TABLE statement I get these errors:

Msg 1776, Level 16, State 0, Line 42
There are no primary or candidate keys in the referenced table 'Customer_MDM.membership_registration' that match the referencing column list in the foreign key 'FK__loyalty_d__first__634EBE90'
Msg 1750, Level 16, State 1, Line 42
Could not create constraint or index. See previous errors.

A: Instead of all these complexities, simply create foreign key for membership table, once. Then all the other columns can be easily referenced.
CREATE TABLE Customer_MDM.loyalty_data (
    customerID INT,
    loyalty_level INT,
    customer_age INT,
    reward_points INT,
    average_amount_spend INT,
    registration_num INT,
    PRIMARY KEY(customerID,loyalty_level),
    FOREIGN KEY (registration_num) REFERENCES Customer_MDM.membership_registration(registration_num)
);

A: You need to create a unique index on first name in the membership_registration table first.  Hopefully you're not actually trying to foreign key something by the first name and this is just testing foreign keys.

A: When creating the table membership_registration you need to make sure the column  first_name is a key. It can be a primary key or a unique constraint.
Since the table already has a primary key, you can define this column with a unique constraint. For example:
CREATE TABLE Customer_MDM.membership_registration(
  registration_num INT Primary key,
  registration_location VARCHAR(25),
  customerID INT /* FOREIGN KEY Customer details */,
  first_name VARCHAR(25),
  last_name VARCHAR(25),
  dob DATE,
  marital_status VARCHAR(25),
  gender VARCHAR(25),
  occupation VARCHAR(25),
  income_level VARCHAR(25),
  date_enrolled VARCHAR(25),
  phone_number VARCHAR(25),
  email VARCHAR(30),
  city VARCHAR(25),
  state VARCHAR(25),
  zipcode INT,
  constraint uq1 UNIQUE (first_name) -- added constraint here
);

See running example at db<>fiddle.
In any case, first names are not good choices for a key since most likely your data model will need to accomodate multiple people with the same name.


text:
Q: How do you run just one test assertion with rails Test::Unit or minitest? I'm working on a project that has legacy tests written in minitest. How do you run just one assertion out of a test file?
Note: I have the answer for my question, I'll post it in a moment. I'm putting this here so that a) it can benefit others, and b) if I either lose track of my answer, or forget that I figured this out, hopefully I'll find this myself. And have a good laugh.

A: Answering my own question, so that others can benefit, and if I forget, hopefully I'll find it...
I discovered two discinct ways to run these tests, as well as how to specify the options. The syntax differs slightly depending on how you run them. However, the most important details are these:

*

*If you specify an exact name, you must prefix the actual test name with "test: " and suffix it with ". " - both of those trailing spaces are critical

*You can supply a regular expression, it will recognize an option of the form /whatever/ as a regex

*the name of the option is -n or --name
Here are two ways of running a single assertion from a single test file:
bundle exec ruby -Itest path/to_test.rb '--name test_: the exact test name as discovered by running with -v. '

bundle exec rake test TEST=path/to_test.rb TESTOPTS="--name 'test_: the exact test name as discovered by running with -v. '"

And here's how it looks if you use a regex:
bundle exec rake test TEST=path/to_test.rb TESTOPTS="--name '/test name as discovered/'"

Note that there are different ways to deal with the quoting/escaping of course, and it seems you can use -n=value in addition to -n value.


text:
Q: Can i reference a variable in my xcopy path? @echo off
set /p fileToCopy = "File you want to copy: "
set /p destinationFile = "Destination file (On Desktop): "
xcopy c:\users\jordean\desktop\%fileToCopy% c:\users\jordean\desktop\%destinationFile%
pause

Why does this not work? Am I using variables incorrectly? First day using command line and batch files.

A: You need to remove the SPACE before =, otherwise it becomes part of the variable name:
@echo off
set /P fileToCopy="File you want to copy: "
set /P destinationFile="Destination file (On Desktop): "
xcopy "C:\users\jordean\desktop\%fileToCopy%" "C:\users\jordean\desktop\%destinationFile%"
pause


text:
Q: Auto scaling ffmpeg in aws I am a newbie to aws platform. I would like to know how I could enable auto scaling for my application below
https://github.com/riyaskp/PHP-Video-Transcoder
The application is used to transcode the user uploaded video to mp4.
It is using PHP and rabbitmq for managing the upload and queue and FFMPEG for transcoding. The rabbitmq workers are configured using supervisor
The supervisor runs 8 consumer process to enable parallel execution of ffmpeg on 8 core CPU in a single AWS instant.
I would like to know how I can scale or how I need to approach this application to enable more parallel ffmpeg process when all the 8 process are transcoding.  what will be the right aproach in aws?
Thankyou for the help.


text:
Q: Android Picasso: Method call should happen from the main thread I am trying to get info from a server, including photos. I have created a class called ServerManager, which allows me to download the desired information. However, I cannot download images with Picasso because I get a java.lang.IllegalStateException: Method call should happen from the main thread..
This is what I am doing in ServerManager:
// Check if the photo is already downloaded
if (!checkInternalPhoto(member)) {
    final String outputURL = context.getFilesDir().getAbsolutePath() + "/" + member.photoPath;
    String photoURL = rootURL + "photos/" + member.photoPath;
    Picasso.with(context)
            .load(photoURL)
            .into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    File file = new File(outputURL);
                    try {
                        file.createNewFile();
                        FileOutputStream outputStream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        Log.e("IOException",e.getLocalizedMessage());
                    }
                }
                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                }
                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                }
    });
}

What can I do?
Edit: I tried to use the code in my MainActivity and I am getting the same error message...
 public void downloadPhotos(List<Member> memberList){
    String rootInURL = serverManager.getRootURL();
    String rootOutURL = serverManager.getOutputURL();
    for(int i = 0; i < memberList.size(); i++){
        if(!serverManager.checkInternalPhoto(memberList.get(i))){
            final String outputURL = rootOutURL + memberList.get(i).photoPath;
            String photoURL = rootInURL + "photos/" + memberList.get(i).photoPath;
            Picasso.with(this)
                    .load(photoURL)
                    .into(new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                            File file = new File(outputURL);
                            try{
                                file.createNewFile();
                                FileOutputStream outputStream = new FileOutputStream(file);
                                bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
                                outputStream.flush();
                                outputStream.close();
                                Toast.makeText(context, "YEpa: " ,Toast.LENGTH_LONG).show();
                            } catch (IOException e){
                                Toast.makeText(context, "Error: " + e.toString(),Toast.LENGTH_LONG).show();
                            }
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {

                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {

                        }
                    });
        }
    }
}

A: Try this and your error should disappear. This problem always happens when you use it in Unit Android test

kotlin code

 Handler(Looper.getMainLooper()).post {
 }

java code

new Handler(Looper.getMainLooper()).post(() -> {
});

A: You can't update an ui element from a different thread than the one which created that ui element. On Android that almost always means the main thread.
What you need to do is send back the photoUrl String to your activity or fragment on the main thread. The traditional way of doing it is by using a Handler. You can read about this more here: https://developer.android.com/training/multiple-threads/communicate-ui.html


text:
Q: how can I limit the number of message of AMQP in one time of consume? I am using node+typescript+amqplib to build a project with rabbitMQ cloud service,  if the QUEUE have 5 messages to consume, I use the code : channel.consume(queue, (msg) => {... }  to consume the messages, I will get all the 5 messages in one time.
how can I limit the number of message of AMQP in one time of consume?
I mean, if I can limit one time 2 messages, I can get 2 messages at the first time, then get 2 at the second time, then 1 at the 3rd time,
could you help me~

A: https://www.rabbitmq.com/consumer-prefetch.html
https://amqp-node.github.io/amqplib/channel_api.html#channel_prefetch

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: Criar planilha adicionando imagens e trocando cor das linhas Este método cria uma planilha do Excel, com int e string:
public function arrayToXls($input) {
    // BoF
    $ret = pack('ssssss', 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);

    // array_values is used to ensure that the array is numerically indexed
    foreach (array_values($input) as $lineNumber => $row) {
        foreach (array_values($row) as $colNumber => $data) {
            if (is_numeric($data)) {
                // number, store as such
                $ret .= pack('sssssd', 0x203, 14, $lineNumber, $colNumber, 0x0, $data);
            } else {
                // everything else store as string
                $len = strlen($data);
                $ret .= pack('ssssss', 0x204, 8 + $len, $lineNumber, $colNumber, 0x0, $len) . $data;

            }
        }
    }

    //EoF
    $ret .= pack('ss', 0x0A, 0x00);

    return $ret;
}

Gostaria de adicionar uma imagem, poderiam auxiliar na alteração que preciso fazer nesta linha para isso?
$ret .= pack('ssssss', 0x204, 8 + $len, $lineNumber, $colNumber, 0x0, $len) . $data;

E também necessito trocar a cor da linhs
$ret .= pack('ss', 0x0A, 0x00);

Alguém tem alguma documentação ou já fez isto?

A: Acabei optando pelo uso da biblioteca PHP Excel) .
Foi a maneira mais fácil de efetuar esta ação.

A: A forma mais boba para criar uma planilha do Excel é modificar o cabeçalho da resposta e transformar a página em planilha:
$fileName = "planilha.xls";
header("Content-type: application/vnd.ms-excel");
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=$fileName");
header("Pragma: no-cache");


text:
Q: How to Extract Value From Response Header with 302 Status Code? I've been trying to extract value from a response header. I tried using RegEx and Boundary Extractor but I coudln't make it. And that request always gives a 302 response code.
My Response Header:
HTTP/1.1 302
server: nginx
date: Wed, 23 Feb 2022 12:35:19 GMT
content-length: 0
x-frame-options: SAMEORIGIN
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
strict-transport-security: max-age=31536000 ; includeSubDomains
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
location: https://somedomainname.com/tr/checkout/orderConfirmation/2202231535500
content-language: tr
connection: close

What I want to extract is order confirmation number: 2202231535500 , which will be coming as a dynamic value during testing.

A: Use
orderConfirmation/([0-9]+)

See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
  orderConfirmation/       'orderConfirmation/'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [0-9]+                   any character of: '0' to '9' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1


text:
Q: How to save attachments and rename it I am having an issue getting my code to work.  This is my first time running a VBA script.  I have a large amount of emails coming in from a fax machine and I want to be able to download the attachments, rename the file to the subject line and then store them on my computer.
My first attempt, I tried to just write a macro so that I could manually do it but after doing some research, I was under the impression that I wanted to make rules work.
This is my first attempt at VBA so I'm not even sure I am running the macro or rule script correctly but I have a feeling I am just missing something in the code.  Any thoughts?
Public Sub saveAttachtoDiskRule(itm As Outlook.MailItem)

    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim fso As Object
    Dim oldName

    Dim file As String
    Dim DateFormat As String
    Dim newName As String

    Dim enviro As String
    enviro = CStr(Environ("USERPROFILE"))
    saveFolder = enviro & "\" & "\destinationfolder\"

    Set fso = CreateObject("Scripting.FileSystemObject")

     For Each objAtt In itm.Attachments
     file = saveFolder & objAtt.DisplayName
     objAtt.SaveAsFile file

     Set oldName = fso.GetFile(file)
     newName = itm.Subject
     oldName.Name = newName

     Set objAtt = Nothing
     Next

     Set fso = Nothing
End Sub

A: Here is simple rule script
Public Sub saveAttachtoDisk(olItem As Outlook.MailItem)
    Dim olAttachment As Outlook.Attachment
    Dim SaveFolder As String

    SaveFolder = "c:\temp\"

    For Each olAttachment In olItem.Attachments
        olAttachment.SaveAsFile SaveFolder & "\" & olAttachment.DisplayName
        Set olAttachment = Nothing
    Next
End Sub

Environ Function
The Environ function lets you get the Windows environment variables for the computer your code is currently running on, Like user name or the name of the temporary folder
Examples
user's profile folder example is
Environ("USERPROFILE") & "\Documents\Temp\"
result
Windows Vista/7/8:  C:\Users\Omar\
Windows XP:         C:\Documents and Settings\Omar\

"All Users" or "Common" profile folder
Environ("ALLUSERSPROFILE")

Temporary folder example is
Environ("TEMP") (or Environ("TMP") - is the same)
result: C:\Users\omar\AppData\Local\Temp


text:
Q: How could it had happened vs How could it have happened What is the difference between

How could it had happened

and

How could it have happened

It would be better if anyone can show its usage in some kind of situation.

A: John Lawler's comment provides a complete answer:

Could is a modal auxiliary and modal auxiliaries must be followed by an infinitive form of the next verb. Have is the next verb, and the infinitive form of have is have. Not had. That's all.

"How could it had happened" is therefore not a grammatical utterance.


text:
Q: Multinomial log. regression in SPSS with a dummy independent variable This is my test design which is simply a grouping variable:

When I choose to regress a gender variable (w/m) onto this grouping variable with a multinomial logisitic regression model I'll observe

Why does SPSS list both categories of gender with one being redundant rather then choosing one by default (the last category) as the reference?
If there's no reference for the gender variable the interpretation of the intercept gets rather confusing. Is there simply a mistake involved or do I miss something?

A: Gender = w is the reference category. It has B = 0 in all cases.


text:
Q: Can std::transform() be made exception-ignorant? This is probably an AB mistake on my part.
While reading my dataset usually some files are NOT a part of it. I want to be robust against that - to just ignore them, simply log the omission.
But I am in love with exceptions thus Spectrum read_csv( const fs:path & dataset ); throws.
I want to keep it that way because the .pdf and other files my supervisor has embedded into the data structure should stay there.
The following implementation seems elegant. But fails at the first wrong file. A try/catch alternative works. But is not as expressive. Can this work somehow while read_csv() throws; those exceptions to be at most logged?
// How do we make this exception-tolerant?
std::transform( files.cbegin()
              , files.cend()
              , std::back_inserter( ret )
              , read_csv
              );

A: This is not something you should be using exceptions for. If it's expected that read_csv() will fail as part of the normal execution of the code (e.g. because the file is missing) and the algorithm should proceed regardless, then exceptions are not the correct mechanism to employ here.
By long-standing convention, C++ exceptions are meant to only be used to denote unexpected failure. This has two big impacts:

*

*Compilers are willing to (and do) implement exceptions in a way that grind the program to a halt if it means that the code can run ever slightly faster when no exception is thrown.

*Programmers seeing exception handling code will automatically read it as code that runs when the algorithm fails. Diverging from this makes code hard to read and interpret, leading to a large increase in effective complexity.

Because of these two factors, the only thing exception handling code should ever do is rollback the program to the state it was in before the failed operation started. Anything else is almost certainly wrong.
I think you are looking for this (assuming a missing file is the expected error, you can adapt as needed):
for(const auto& f: files) {
  if(fs::exists(f)) {
    ret.push_back(read_csv(f));
  }
}

The big advantage here is that the failure you expect, the file not existing, will be handled cleanly and quickly, whereas failures you don't expect: running out of memory, reading junk data, etc. etc. will still cause an exception that will bubble up and report a failure of the algorithm as a whole.
That being said, your question can still be answered as asked so here it is:
std::transform produces something for every element in the input range. Because of that, you need to figure out what get pushed into ret when read_csv() fails.
The ideal way to handle that would be to use the proposed std::expected<>. If you can't or don't want to use a third-party implementation of the proposal, std::optional<> is the closest alternative in the standard library.
If you want to keep read_csv() untouched, you would also need a function adapter (let's call it Maybe) that swallows exceptions and produces an expected<> or optional<> on failure. That's not particularly difficult:
template<typename F>
struct Maybe {
  F func;

  template<typename... ArgsT>
  auto operator()(ArgsT&&... args) -> expected<decltype(func(std::forward<ArgsT>(args)...)), std::exception_ptr>{
    try {
      return func(std::forward<ArgsT>(args)...);
    }
    catch(...) {
      return unexpected(std::current_exception());
    }
  }
};

...

std::vector<expected<Spectrum, std::exception_ptr>> ret;
std::transform( files.cbegin()
              , files.cend()
              , std::back_inserter( ret )
              , Maybe(read_csv)
              );

You could take this further by also adapting the back_inserter() so that it pushes the value on success, and does nothing on errors. This way you could go back to producing a std::vector<Spectrum>, but that introduces yet more error swallowing, which is just asking for trouble in my book.
see on godbolt

A: You need to come up with your own transform taking a functor to call upon exception thrown. This is probably a (really) bad design though as that implementation would need to "catch everything".
You might be in love with exceptions, but this is a scenario where you do not want to use them. After all, you're expecting some file to be missing. You wouldn't write
void add(int lhs, int rhs)
{
 throw lhs + rhs; // DON'T!!!
}

int main ()
{
  try {
    add(40, 2);
  } catch (int result) {
    std::cout << "answer: " << result << ".\n";
  }
}


text:
Q: Rails: Subclass not registering as instance of parent class In a Rails app I am working in, I have code like the following:
# app/models/a.rb
class A < ActiveRecord::Base; ...; end
# app/models/b.rb
class B < A; ...; end

# /app/elsewhere...

do_case(B.new)

def do_case(letter)
  case letter
  when A
    "not nil"
  end
end

When I run this locally it performs as expected and I get "not nil" as the return value. But I get nil in my test environment.
The test environment shows that A is among the ancestors (B.ancestors) of letter (B.new), but fails to register as a subclass with the case equality operator or is_a?(A).
A === B.new #=> false in test environment, true locally
B.new.is_a?(A)  #=> false in test environment, true locally

This seems like a Rails autoloading issue, but I'm not sure why these methods would be failing if the parent class is included in the ancestors in both environments. What's going on?

A: Agree, this looks like an autoloading issue. While not ideal, you can resolve it by adding a require_dependency call in B.
As far as where to look for the root issue, it's possible that you have some library dependencies in your test environment that don't exist on Test. I would load a REPL on Test and inspect A. Some useful methods:
class A
  def self.what_is_my_nesting
    Module.nesting
  end
end

A.what_is_my_nesting
A.ancestors
B.ancestors

etc


text:
Q: IGMP v3 JOIN sent but no traffic from switch I'm trying to join an IGMP multicast stream from a Centos 8 machine but after sending a JOIN, there is no traffic coming from the switch.
Simple connection:
MUX <-----------> cisco3850 <--------> Centos8
192.168.117.13                         192.168.117.21

The upstream switch (cisco catalyst 3850) is fed an MPEG-TS to 239.1.1.1:4000 from the MUX.
I've tried both socat and my own program to open a socket, join the stream, and hold the socket open.  Both send the same IGMP join message as confirmed by wireshark:
Internet Group Management Protocol
    [IGMP Version: 3]
    Type: Membership Report (0x22)
    Reserved: 00
    Checksum: 0xe9fb [correct]
    [Checksum Status: Good]
    Reserved: 0000
    Num Group Records: 1
    Group Record : 239.1.1.1  Change To Exclude Mode
        Record Type: Change To Exclude Mode (4)
        Aux Data Len: 0
        Num Src: 0
        Multicast Address: 239.1.1.1

Using ip route add I created routes for multicast groups to the interface:
224.0.0.0/4 dev eth1 scope link
225.0.0.0/8 dev eth1 scope link
239.0.0.0/8 dev eth1 scope link

and cat /proc/net/igmp shows the group has been joined:
cat /proc/net/igmp
Idx     Device    : Count Querier       Group    Users Timer    Reporter
3       eth1      :     2      V3
                                030101E1     1 0:00000000               0
                                010000E0     1 0:00000000               0

I suspect this is a problem with the switch rather than a Linux problem, but the customer (who owns the switch) says everything is fine.
What else can I do on the Linux side to investigate/fix this issue?
If it is an issue on the switch then what?  What needs to be configured there? (need to explain to customer)

For reference, my program which joins and holds the socket open looks like:
// Error checking omitted for brevity
fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes);

memset(&saddr, 0, sizeof(saddr));
saddr.sin_family      = PF_INET;
saddr.sin_addr.s_addr = mcastAddr;
saddr.sin_port        = htons(port);

bind(fd, (struct sockaddr *)&saddr, sizeof(saddr);

struct ip_mreq mcastReq;
mcastReq.imr_multiaddr.s_addr = mcastAddr;
&mcastReq.imr_interface.s_addr = interfaceAddr;

setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcastReq, sizeof(mcastReq);

A: In the end, the customer switch could not/would not activate IGMPv3, so we set our machine to use IGMP v2 by creating a file under /etc/sysctl.d.
The JOIN then worked, but Linux did not respond to multicast membership queries so the switch dropped the stream after 1-2 minutes (even though we had net.ipv4.conf.default.rp_filter set to zero.
It turns out to fully disable return path validation, we needed to set all of the rp_filter settings to zero (including explicitly listing the interface)
# Set IGMP Version for eth1
# Set to '2' or '3' depending on what is enabled in the switch
net.ipv4.conf.eth1.force_igmp_version = 2

# Disable source route verification
# In addition to 90-torque.conf, also explicitly set eth1 to ignore
# return path validation
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.eth1.rp_filter = 0


text:
Q: Kafka - Does local state store consumes application memory(JVM) I have a consumer API thread running in my application(running on different node), my goal is to consume the incoming record from Kafka which will have unique id as key. Looking for an option to store the record processed by Kafka Consumer API so that my order can use it for display.
Planning to use Stream API to process and create a Ktable on Kafka broker. If I choose to use the persistent state store, does it still consumes my local application memory? If so, is it like temporarily and releases memory as soon as record is processed? Trying to avoid any memory issues within the application and see which state store option would best suits my use case. Many thanks!

A:
If I choose to use the persistent state store, does it still consumes my local application memory?

It depends on the underlying storage, it can be: a RocksDB, an in-memory hash map, or other data structure.

If so, is it like temporarily and releases memory as soon as record is processed?

No
By the way: You should not deploy your Kafka Streams app on any Kafka broker.

A:
create a Ktable on Kafka broker

A KTable will be populated client side.

If I choose to use the persistent state store, does it still consumes my local application memory?

Even RocksDB would use some local memory obviously (note that memory would be off-heap as RocksDB is a C++ application that is integrated into the JVM via JNI). Or course, you can fine-tune/configure RocksDB to your needs and limit it's memory consumption accordingly. In general, RocksDB spills to disk and thus you can hold state that is larger than main-memory.

Is it like temporarily and releases memory as soon as record is processed?

No. If you read a topic as a changelog, each record will be either an insert/update/delete (delete via tombstone, ie, value=null). Given that each record has unique ID, all records would be inserts and your KTable would grow unbounded.
How do you define "processed" for a record? If you can determine when a record is fully processed, you could use a KafkaProducer to write a tombstone into table input topic. KafkaStreams would eventually read and process this tombstone and delete the message from the KTable. It would be of course an async delete, but it might just work fine.


text:
Q: How to clear wxpython frame content when dragging a panel? I have 3 panels and I want to make drags on them.
The problem is that when I do a drag on one this happens:
http://img41.yfrog.com/img41/9043/soundlog.png http://img41.yfrog.com/img41/9043/soundlog.png
How can I refresh the frame to happear its color when the panel is no longer there?
This is the code that I have to make the drag:
def onMouseMove(self, event):
    (self.pointWidth, self.pointHeight) = event.GetPosition()
    (self.width, self.height) = self.GetSizeTuple()
    if (self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15) or self.parent.dragging:
        self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))

        """implement dragging"""
        if not event.Dragging():
            self.w = 0
            self.h = 0
            return
        self.CaptureMouse()
        if self.w == 0 and self.h == 0:
            (self.w, self.h) = event.GetPosition()
        else:
            (posw, posh) = event.GetPosition()
            displacement = self.h - posh
            self.SetPosition( self.GetPosition() - (0, displacement))
    else:
        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

def onDraggingDown(self, event):
    if self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15:
        self.parent.dragging = 1
        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
        self.SetBackgroundColour('BLUE')
        self.parent.SetTransparent(220)
        self.Refresh()

def onDraggingUp(self, event):
    self.parent.dragging = 0
    self.parent.SetTransparent(255)
    self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

and this are the binds for this events:
self.Bind(wx.EVT_MOTION, self.onMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.onDraggingDown)
self.Bind(wx.EVT_LEFT_UP, self.onDraggingUp)

With this, if I click on the top of the panel, and move down or up, the panel position changes (I drag the panel) to the position of the mouse.

A: To refresh the parent on every repositioning of self, you could add
self.parent.Refresh()

right after your existing call to self.SetPosition in your def onMouseMove method. Right now you're refreshing the frame only in the def onDraggingDown method, i.e., the first time the mouse left button is clicked and held down, not every time the mouse is moved while said button is held down (i.e., the "dragging" action itself).
I was unable to download your code for testing purposes, due to the rather "spammy peculiar" site you chose to upload it to -- the site keeps bombarding me with ads, no clear way for me to just do the download, occasionally complaining that it doesn't support my machine (I use a Mac and Google Chrome, the site at some spots insists on Windows with IE or Firefox...), etc etc. I'm sure you can find other sites, more usable than that one, for people who are trying to help you out!-)


text:
Q: Add unbound combo box to form that can trigger a BeforeUpdate() event? I have a datasheet form ItemsForm based on table Items.  Items is one-to-many related to table StatusHistory, between Items.ID and StatusHistory.ItemID.  There is also a Status table, with the relationship between Status.ID and StatusHistory.StatusID.
I want to add a StatusBox combo box to ItemsForm so that when the user selects a Status value from the box and then moves out of the record, which should trigger the Form_BeforeUpdate() event, a new entry is added to StatusHistory with the Items.ID of the currently selected entry.
I've successfully added the StatusBox field to the form and populated its list by setting its RowSource with a query of Status.  But there are two big problems:

*

*I can scroll through the values in the box's list, but after I
select one, it doesn't show up in the field; the field stays blank.

*When I select a value in StatusBox, and then click onto another
record, the Form_BeforeUpdate() isn't triggered.  It seems that
Form_BeforeUpdate() is only triggered if I modify data in the
fields from Items that the form is based on.  Is there a different event that I should be using here?

A: Solved it as follows:

*

*The ID field for Status is actually named StatusID instead of
ID.  Fixing this allowed me to enter values into the field.

*I put the code into the BeforeUpdate() event for StatusBox, viz:

Private Sub StatusBox_BeforeUpdate(Cancel As Integer)

End Sub

This means it gets triggered whenever I select an item in the list, rather than when I move to a new record, but for now that's all I need.


text:
Q: HTML5 checkValidity and Invisible Fields I have a simple form as below:
<form id="form1" runat="server">

        Line 1: <asp:TextBox ID="Line1TextBox" runat="server" placeholder="e.g. Street 9" required ></asp:TextBox>

        Fill Line 2? <asp:CheckBox ID="Line2CheckBox" runat="server" OnClick="Line2CheckBox_Chekced();"  />

            Line 2: <asp:TextBox ID="Line2TextBox" runat="server" placeholder="e.g. Street 9" required ></asp:TextBox>

        <asp:Button ID="NextButton" runat="server" Text="Next" OnClientClick="return NextButton_Click();" />

</form>

The Line2CheckBox is toggling the Line2Panel with the following script:
function Line2CheckBox_Chekced() {
     $("#Line2Panel").toggle();
}

In the NextButton_Click I am checking whether the form is valid or not as follows:
function NextButton_Click() {
    if ($('#form1')[0].checkValidity()) {
        alert("from is valid");
   } else {
        alert("from is NOT valid");
   }
}

I have noticed the following:

*

*If I enter some value in the Line1TextBox and attempt to submit the form, while Line2TextBox is hidden, the form is not submitted because the form in not valid (checkValidity() returns false).

*If I click on the CheckBox to show Line2TextBox and enter some value in it, the form is submitted correctly.

*If I mark Line2TextBox as disabled and don't put any value, the form is submitted.

My questions are:

*

*Is this the default behavior of HTML5 forms (invisible hidden fields but not disabled fields)?

*More importantly, how to stop HTML5 from validating invisible fields (I have tried to use oninvalid event to check wehther the field is visible or not, $(obj).is(":visible"), then cancel the event but it didn't work)?

My goal is that if the field is invisble then mark it as valid, something like the following but I don't know where to write it (or to which event I should attach this code):
if (obj.willValidate && !$(obj).is(":visible"))
    //cancel the validation event or consider the field as valid

A: I think these could be logical answers to my questions:

*

*It mekes sense to validate invisible fields. For example if a field is invisible because it is in an accordion control or in a collapsible panel, it should be validated.

*One way to stop HTML5 from validating invisible fields is to mark them as not required. In my case when I check / uncheck the CheckBox I do the following:
function Line2CheckBox_Chekced() {
    var isChecked = $("#Line2CheckBox").is(":checked");
    if (isChecked) {
         $("#Line2Panel").show();
         $("#Line2TextBox").attr("required", "");
    } else {
         $("#Line2Panel").hide();
         $("#Line2TextBox").removeAttr("required");
    }
}

So I think I will be checking the following now:

*

*How to cancel the validation of a certain control?

*How to show the error message from invisible fields?

A: Adding Alexander Farkas's comment as an answer because it helped me (emphasis mine):

Adding/removing required attribute isn't always suitable because:
a) There are other possible HTML5 constraints.
b) You don't want to keep track of all those elements inside of a form group.
The best way is to add the disabled property on the element itself or on the fieldset element

Example:
<fieldset disabled>
  <input type="text" name="foo" required />
</fieldset>


text:
Q: Use Ionic components with an existing Angular 8 project My goal is to be able to serve my Angular 8 application to both web and mobile in the future with a single code base.
Currently, I have an existing Angular 8 project that was created using Angular CLI.  To run it, I would enter ng serve -o from the command prompt. The web browser would launch with localhost:4200.
I do not know if it is possible to integrate the latest Ionic into my Angular 8 project without becoming an Ionic Project?  In other words, I do not want to enter "ionic serve" to start my existing Angular project, however, I would like to be able to take advantage of using the Ionic components within the Angular project.
If it is possible, would you be kind enough to provide
step-by-step guidance?


text:
Q: JWT: What's a good secret key, and how to store it in an Node.js/Express app? Firstly, what's a good method of generating a secret key? I should punch in a lot of random keys on my keyboard to generate one, but there must be a better solution to this. Explain the way to generate a very good key.
Second, what's a good way to store the key? I could write the key in my applications configuration, but that means that a compromise of the source code will compromise the entire system. What's good means of storing the secret key in a Node.js Express app?

A: To generate a secret programatically you could use node's crypto.randomBytes()
var crypto = require('crypto');
var jwt = require('jsonwebtoken');

crypto.randomBytes(256, function(ex, buf) {
  if (ex) throw ex;
  var token = jwt.sign({foo: 'bar'}, buf);
  var decoded = jwt.verify(token, buf);
});

As for storing this, you're absolutely correct, you should definitely not store secrets in your source control. A better way would be to load such sensitive information from environment variables, eg process.env.MY_SECRET.
Another less common pattern I've seen is to load secrets from a file stored separate from your code. You could have your node app look for a JSON file in ~/.myapp/secrets.json for instance.


text:
Q: Reloading Google Map on Form Submit I've created a Google Map that loads markers from a JSON file and plots them when the page first loads. This bit of functionality works correctly. However, my page also includes a form and I would like to fire the getJSON request again when the form is submitted to update the map. This is the bit I can't get to work. Can anyone see what I am doing wrong?
<!doctype html>

        <form id="filter">
            <select name="foo" id="foo">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>

            <select name="bar" id="bar">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>

            <input type="submit">
        </form>

A: call the destroy-method of the map before you initialize it again.

A: The "AJAX" Philosophy (from Mike Williams' v2 tutorial), would be to leave the map (don't re-initialize it), just change the displayed data (the markers).
Separate the map creation from the markers, initialize the map on page load and call your .getJSON for the original data.  On form submit (or button click), remove all the markers and call .getJSON again, passing in the appropriate data from the form.

A: Thanks Linuxios. That worked. Amended code for reference:
$('#filter').submit(function(e) {
  $('#map_canvas').gmap('destroy');
  initialise();
  e.preventDefault();
});

I also appended the current time to the getJSON URL to prevent caching.
$.getJSON( 'http://localhost:8888/googlemaps/demo.json?' + new Date().getTime()


text:
Q: Duplicate javascript references I have the to give some javascript to my clients to put on their pages.
That javascript code injects on my client pages reference to some javascript in my server.
Similar to this:
if (typeof MYSUPERVAR == 'undefined') {
      var head = document.getElementsByTagName('head')[0];
      var script = document.createElement('script');
      script.src = '//mywebsite.com/myjs.js';
      script.async = true;
      script.type = 'text/javascript';
      head.appendChild(script);
   }
   //After JS is loaded call MYJS_FUNCTION_A
   MYJS_FUNCTION_A()

"myjs" creates MYSUPERVAR and also creates a function that should be called for each time that the user wants (by adding the same javascript).
This is for adding some images functionality so the user has to put every time the script with the imageid.
The problem is that this creates a script reference for myjs all the time.
It's possible to know if myjs is correctly loaded before adding one more reference?

A: you can load js file and call callback function after loaded finish.
<script>
function loadJS(src, callback) {
    var s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onreadystatechange = s.onload = function() {
        var state = s.readyState;
        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() {
    // put your code here to run after script is loaded
});
</script>

A: You can set a global variable (like window.JSLOADED) in myjs.js, with a true value, and create a timer (with setInterval) that check if JSLOADED == true.
When myjs.js loads, it set JSLOADED, then you proceed with the rest.
Hope you solve it.


text:
Q: Refactoring. Flip all (b != a) and (b == a) occurrences in code I have many occurrences in my code such as :
if (null != object)

and

if (null == object)

On a new work place I need to refactor these occurrences to:
if (object != null)

and

if (object == null)

For more readable code.
I tried to make a search and manually flip the occurrences but it was taking much time of me (Idea found more than 1000 occurrences of each case). I also have several similar constructions of my current code.
So my question is how to FLIP ALL occurrences in all projects?
Is that possible do automatically or using macros?

A: You can search and replace with regular expression like
if\s*\(\s*null\s*([\!\=]=)\s*(\w+)\s*\)

Replace with
if ($2 $1 null)


text:
Q: Ruby on Rails: How do I execute a function before saving to the database? I want to alter the data and save it then to the database when using the new / create function of the app.

A: before_create :myfunction

def myfunction
  # Edit data
end

Should do the trick.

A: You should use active callbacks, as the two other answers stated. The *before_create* is definitely the one you are looking for. Always do that kind of logic in the model, and not in the controller. Rails mantra (one of many) is "thin controller, fat model", which enable code reuse more easily.
You can check the active callbacks documentation at :
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Also, here is an example of what you want to achieve
class MyClass < ActiveRecord::Base
    before_create :alter_my_data

    def alter_my_data
        # any manipulation you want to do here before saving
    end
end

A: class User < ActiveRecord::Base
  before_create :validate_username

  def validate_username
    raise "blank error" if username.blank?
    #....your code
  end
end

A: Your question has already been answered above, but I really recommend you check out the official Ruby on Rails guides:
http://guides.rubyonrails.org/
The guides are easy to comprehend and cover many parts of Rails. Your question is answered in the 'Active Record Validations and Callbacks' section.


text:
Q: How do I change my Workspace name in P4v? I have a Workspace that I would like to rename in P4V.
So far, I have tried doing so by navigating to Connection -> Edit Current Workspace. However, the 'Workspace name' field is not editable.
Does anyone know if it is possible to do this?

A: As documented on perforce documentation client (workspace) name is field read-only, so it is not editable.
You can still copy that workspace and name it differently.
To do so open Workspaces tab (View > Workspaces) and search for your workspace on the list. Right-click on it and select "Create new workspace from 'XXX'..."


text:
Q: geojson generated from mysql not working I have a function in php:
 public static function getGeoJSON() {
 // code that generates geojson from mysql
  return $geojson;
 }

In javascript i call this function:
     var geo = JSON.parse( '<?php echo json_encode($geo) ?>' );

    //this is where I want to put my generated geojson instead of a file.geojson

  d3.json('point.geojson', function(geojson){
    mapDraw(geojson);
    });

like this I want it:
  // replace static file with generated geojson
  d3.json(geo, function(geojson){
    mapDraw(geojson);
    });

I have printed the generated geojson and pasted it into a json file and it works. but when I try to put the
 var geo

as reference instead of the path it fails. Does anyone know why?
Thanks in advance.
    {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[xx.xxx,xx.xxx]},"properties":{"description":"bad description"}}]}


text:
Q: Good ruby url shortener gems? What good, reliable ruby gems do you use for shortening URLs?

A: There are many gems out there. It dependes on your need. Shortly gem provides many url shortener services(googl, bitly,...). Check that out.

A: Please, see https://github.com/zigotto/googl for this.
It's simple ruby gem for Google URL Shortener API.


text:
Q: Hazelcast Jet Kafka with not serializable event handler I want to use hazelcast-jet-kafka in my app, because in my case the number of kafka partitions is limited. How I understand jet-kafka parallelism doesn't depend on kafka partitions, it would be nice to find explanations of how jet-kafka achieve independence of the number of kafka partitions.
But my question is how I can handle events in jet when my event handler could not be serializable.
For example, I've found a solution - use map sink and add local event listener to this map,
but for me, it seems like a crutch, because I don't need to store these events in map. It is possible to set map size to zero in such scheme?
Also, I see in docs new type of sink - observable, it seems what I want, but observable listener could not get only local entries and for me, it is not suitable.
Could you help find the right solution? Or hazelcast-jet-kafka is not a good choice in that case?

A:
it would be nice to find explanations of how jet-kafka achieve independence of the number of kafka partitions.

One Jet thread can handle any number of partitions, so it's easy to achieve this independence. Jet just distributes all the partitions fairly among all the Kafka connector threads.

But my question is how I can handle events in jet when my event handler could not be serializable.

Hazelcast Jet doesn't require your event handler to be serializable. If you need a stateful handler, you have to supply a function that creates the state object. The function must be serializable, but the state doesn't have to be. If you just want a stateless mapping function, it must be serializable, but usually there's no problem with that.
If you are getting an error that says a function is non-serializable, this can be due to a common pitfall of capturing more state than you actually need in the lambda. You should show your code in that case.


text:
Q: consulta para obtener fecha maxima entre varias tablas ¿Es posible obtener la fecha más reciente entre varias tablas, dado el id de una tabla principal que está en todas las demás tablas? ¿Cómo podría obtener esto?
Tabla 1 principal
id_tabla1
descripcion

tabla 2
id_tabla2
fecha
fk_tabla1

tabla 3
id_tabla3
fecha
fk_tabla1

tabla 4
id_tabla4
fecha
fk_tabla1

He intentado lo siguiente:
select MAX(Fecha) as fecha
  from tabla1
 INNER JOIN tabla2 on tabla1.id_tabla1 = tabla2.id_tabla1
 GROUP BY tabla1.id_tabla1

Pero esa es la fecha más reciente de tabla2. ¿Cómo podría comparar luego con las demás y tener la más reciente de entre todas?

A: Una idea es que hagas un join de todas las tablas, haciendo el max de cada fecha, y luego usando GREATEST para devolver el máximo de todos los máximos:
select greatest(
         coalesce(max(t2.fecha), 0),
         coalesce(max(t3.fecha), 0),
         coalesce(max(t4.fecha), 0)) as max_fecha
  from tabla1 t1
  left join tabla2 t2
    on t2.fk_tabla1 = t1.id_tabla1
  left join tabla3 t3
    on t3.fk_tabla1 = t1.id_tabla1
  left join tabla4 t4
    on t4.fk_tabla1 = t1.id_tabla1

Edición
Me acabo de dar cuenta que en tu consulta incluyes GROUP BY tabla1.id_tabla1, lo que parece indicar que quieres la fecha máxima por id_tabla1. Si ese es el caso, simplemente agrégale la claúsula GROUP BY a la consulta:
select t1.id_tabla1,
       greatest(
         coalesce(max(t2.fecha), 0),
         coalesce(max(t3.fecha), 0),
         coalesce(max(t4.fecha), 0)) as max_fecha
  from tabla1 t1
  left join tabla2 t2
    on t2.fk_tabla1 = t1.id_tabla1
  left join tabla3 t3
    on t3.fk_tabla1 = t1.id_tabla1
  left join tabla4 t4
    on t4.fk_tabla1 = t1.id_tabla1
 group by t1.id_tabla1

Edición 2
Si quieres saber de cual tabla salió el valor máximo, es un poco mas complicado, pero se puede, usando una expresión CASE:
select t1.id_tabla1,
       greatest(
         coalesce(max(t2.fecha), 0),
         coalesce(max(t3.fecha), 0),
         coalesce(max(t4.fecha), 0)) as max_fecha,
       case when max(t2.fecha) = greatest(
                                   coalesce(max(t2.fecha), 0),
                                   coalesce(max(t3.fecha), 0),
                                   coalesce(max(t4.fecha), 0))
            then 'TABLA2'
            when max(t3.fecha) = greatest(
                                   coalesce(max(t2.fecha), 0),
                                   coalesce(max(t3.fecha), 0),
                                   coalesce(max(t4.fecha), 0))
            then 'TABLA3'
            when max(t4.fecha) = greatest(
                                   coalesce(max(t2.fecha), 0),
                                   coalesce(max(t3.fecha), 0),
                                   coalesce(max(t4.fecha), 0))
            then 'TABLA4'
       end as nombre_tabla
  from tabla1 t1
  left join tabla2 t2
    on t2.fk_tabla1 = t1.id_tabla1
  left join tabla3 t3
    on t3.fk_tabla1 = t1.id_tabla1
  left join tabla4 t4
    on t4.fk_tabla1 = t1.id_tabla1
 group by t1.id_tabla1

Por supuesto, cabe la posibilidad de que el valor máximo sea el mismo en más de una tabla. En ese caso, te devolverá una de las tablas.

A: Si quieres saber la fecha máxima entre todas las tablas no puedes hacer un join entre ellas. En su lugar, deberías obtener las fechas de todas ellas y obtener el valor máximo. Para esto, haces uso de UNION ALL:
SELECT MAX(T.fecha) AS 'Fecha_maxima'
FROM (
    SELECT fecha
    FROM tabla2 t2
      INNER JOIN tabla1 t1 ON t1.id = t2.fk_tabla1

    UNION ALL

    SELECT fecha
    FROM tabla3 t3
      INNER JOIN tabla1 t1 ON t1.id = t3.fk_tabla1

    UNION ALL

    SELECT fecha
    FROM tabla4 t4
      INNER JOIN tabla1 t1 ON t1.id = t4.fk_tabla1
) T;


text:
Q: Get all the Ti.API.info strings to an array I need to get all the Ti.API.info strings to an array by using some function at the end of the app.js file, How do I get all those string to array once it has been printed on console. For Example
Ti.API.info("Hello");
Ti.API.info("Good Morning");
Ti.API.info("Good Afternoon");
Ti.API.info("Good Evening");

at the end of the code I need to have an function to retrieve and store all the strings in array. How do I can do that, Can anyone help me?

A: You can override the existing Ti.API.info function, but, this isn't highly recommended as people might not know that you changed it (even if changes made doesn't impact the initial behavior).
I think that the best way is to define your own logger.
customLogger.js
var Logger = function () {
    /* Define an array to store logs */
    this._logs = [];
}

Logger.prototype.info = function () {
    /* Iterate over each msg and store them */
    for(var i = 0, msg; msg = arguments[i]; i++) {
        this._logs.push({date: new Date(), msg: msg.toString()});
    }

    /* Do the classic log */
    Ti.API.info.apply(Ti.API, arguments);
}

Logger.prototype.getLogs = function () {
    return JSON.stringify(this._logs, null, "\t");
}

/* Export The API */
var logger = new Logger(Ti.API);
exports.info = function() {
    Logger.prototype.info.apply(logger, arguments);
};

exports.getLogs = function () {
    return Logger.prototype.getLogs.apply(logger);
};

Then, in your app.js
var Logger = require("customLogger"); // Adapt the path to suits your architecture

Logger.info("My log message");

// ...

Ti.API.debug("Those are my logs:\n", Logger.getLogs());


text:
Q: What is idiom or proverb that is used to indicate 'the abuse of authority or money by foolish persons' When a foolish person gains wealth suddenly, s/he might start to spend it ostentatiously and sometimes even talks rubbish. If such people get a powerful position, they might even abuse it foolishly. Such persons need not necessarily be evil ones, but the results could be because of their foolishness.
There are a few proverbs in Telugu language which translates to when a poor person became rich all of a sudden, he asked the barber to dress his hair at midnight.
To take one a peg lower - does this convey the appropriate meaning?
What are the other English equivalent proverbs or idioms for the same?

A: There is an old saying A fool and his money are quickly parted*.
It dates from at least as early as the sixteenth century.
Thomas Tusser, in his rhyme Five Hundreth Pointes of Good Husbandrie (1573) says:
A foole & his money,
 be soone at debate:
 which after with sorow,
 repents him to late.
And more exactly to the point:
Dr. John Bridges, in Defence of the Government of the Church of England (1587) says:
If they pay a penie or two pence more for the reddinesse of them..let them looke to that, a foole and his money is soone parted.
Quotations from The Phrase Finder

A: Proverbs 13:11 English Standard Version: BibleHub has

Wealth gained hastily will dwindle, but whoever gathers little by
  little will increase it.

And I feel I have to include Proverbs 21:5
New Living Translation: BibleHub

Good planning and hard work lead to prosperity, but hasty shortcuts
  lead to poverty.

A:
spend money like a drunken sailor: to spend large amounts of money frivolously.
pour money down the drain: to waste money on something useless
(a less nice saying that means the same thing: piss money up the
wall)
wear a ten-dollar hat on a five-cent head: to be rich but stupid
more money than sense: same as above, with the implication that the person doesn't know how to spend the money sensibly.
money talks and bullshit walks: a rich person can get away with anything, or make others do their bidding, no matter how bad.

References:
http://idioms.thefreedictionary.com/money+talks+and+bullshit+walks http://idioms.thefreedictionary.com/piss+money+up+the+wall http://idioms.thefreedictionary.com/pour+money+down+the+drain http://idioms.thefreedictionary.com/He+wears+a+ten-dollar+hat+on+a+five-cent+head
http://idioms.thefreedictionary.com/spend+money+like+a+drunken+sailor
http://www.macmillandictionary.com/dictionary/british/have-more-money-than-sense


text:
Q: Enviar notificaciones cuando se inserte a MySQL desde Asterisk Deseo saber cómo enviar una notificación luego de haberse hecho una inserción en MySQL. Tenemos un sistema que usa Asterisk para registrar llamadas telefónicas de nuestro Call Center. El tema es que usando Nodejs y Socketio queremos notificar de las inserciones a modo de reporte a un usuario específico.
¿Alguna idea?

A: Yo lo hecho de la siguiente manera, espero lo puedas adaptar con Nodejs.
Debes utilizar:
1- Trigger en MySQL, Trigger es un disparador que se ejecuta cada vez que algo ocurre en una tabla ya sea insertando, actualizando o borrando registros, aprovechando esta propiedad de MySQL entonces creas un trigger para que cada vez que se inserta un registro en la tabla que es de tu interés también se cree un registro en una tabla nueva con los campos que tu desees incluyendo fecha y hora, por ejemplo el siguiente código crea un trigger que  se desencadena cada vez que se actualiza un registro en la tabla employees creando otro registro en la tabla employees_audit
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
 employeeNumber = OLD.employeeNumber,
    lastname = OLD.lastname,
    changedat = NOW();
END$$
DELIMITER ;

2- Para notificar al usuario que hubo una inserción puedes utilizar Nodej, PHP o algun lenguaje similar, yo te recomiendo algo simple como crear una pagina HTML que tenga siempre abierta el usuario y a través de AJAX se actualice sola, si no conoces AJAX entonces coloca un botón en la página para que el usuario refresque en forma manual.
3- Si quieres algo más avanzado puedes enlazar Nodej (si lo permite) o PHP con AGI de Asterisk (Asterisk Gateway Interface ) el AGI se comunica con otros lenguajes de programación para que utilices toda la potencialidad telefónica de Asterisk ya sea notificando a los teléfonos IP o bien generando llamadas, sobre AGI enontraras toda la informacion y ejemplos en https://www.voip-info.org/wiki-Asterisk+AGI.
Saludos

A: Hola para obtener los eventos del CDR usando nodejs efectivamente debes usar alguna librería de las tantas que ya proporcionan.
Puedes revisar en el siguiente repositorio tengo el uso de una de estas librerías: https://github.com/alancornejo/sockets_dashboard, en este caso uso asterisk.io.
La documentacion oficial del asterisk tambien indica la forma de capturar el evento con AMI dale una revisado a la wiki.asterisk.org "Asterisk -
 ManagerEvent_CDR"
Otras de las librerías que recomiendo es asterisk-manager, con esto también puede capturar los Eventos con nodejs.

A: 1.- nodejs: hay una libreria en la cual te conectas al ami, y ahi puedes ver el flujo de toda la llamada, desde que entra , que variables trae, quien la contesta, si esta en una cola, todo lo puedes ver, ahi pudieras lanzar tu notificacion que necesitas.
[https://www.npmjs.com/package/asterisk.io][1]
2.- agi, con esta estas un poco limitado, hay que averiguar en que momento quieres la notificacion cuando contesta el usuario o cuando culega, entonces lanzas un agi, como ya lo comento user20930


text:
Q: Custom loop next and previous post links not working I'm using WP Events Manager and Advanced Custom Fields to develop a site, I have a custom post type called 'event' which I want to display via the below:

                Cours
                Niveau
                Dates
                Heures

<?php

$args = array(
    'post_type' => 'event',
    'posts_per_page' => 10,
    'paged' => get_query_var('paged'),
    'order' => 'ASC',
    'orderby' => 'meta_value',
    'meta_key' => '_event_start_date');
$loop = new WP_Query( $args );

if($loop->have_posts()):

while ( $loop->have_posts() ) : $loop->the_post();

$EM_Event = em_get_event($post->ID, 'post_id');

?>

                <?php echo $EM_Event->output('#_EVENTLINK'); ?>
                <?php the_field('niveau'); ?>
                <?php if($slug != 'stages-ete'): ?>Chaque: <?php the_field('jours'); echo '
'; endif; echo $EM_Event->output('#_EVENTDATES'); ?>
                <?php echo $EM_Event->output('#_EVENTTIMES'); ?>

<?php endwhile;?>
<?php else: ?>

Pas de cours à venir.

<?php endif; ?>

<?php next_posts_link('« Older Entries'); ?>

<?php previous_posts_link('Newer Entries »'); ?>

But it's not displaying the previous and next links. Any ideas?
Thanks

A: Try adding the arguments this way instead
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'event',
    'posts_per_page' => 10,
    'paged' => $paged,
    'order' => 'ASC',
    'orderby' => 'meta_value',
    'meta_key' => '_event_start_date');
);


text:
Q: Google Cloud Platform fix SSH I have a problem with SSH access on my google compute engine. I made a server, set up the application on it and configured the domain and everything works. After a few days when I wanted to approach her to make changes my SSH didn't work. I have one assumption I was turning on firewall and I didn't add a rule for SSH, maybe that's a problem? But how to access the machine now and enable it?
Thanks in advance .

A: To solve your issue you can connect to your VM instance via serial console. Before connecting to the VM via serial console check if you enabled connections to your VM instance at GCP Firewall.
Please have a look at the step by step instructions below:

*

*Enable serial console connection with gcloud command:
 gcloud compute instances add-metadata NAME_OF_YOUR_VM_INSTANCE \
 --metadata serial-port-enable=TRUE

or go to Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> click on EDIT -> go to section Remote access and check Enable connecting to serial ports

*Create temporary user and password to login: shutdown your VM and set a startup script by adding at the section Custom metadata key startup-script and value:
 #!/bin/bash
 useradd --groups google_sudoers tempuser
 echo "tempuser:password" | chpasswd

and then start your VM.

*Connect to your VM via serial port with gcloud command:
 gcloud compute connect-to-serial-port NAME_OF_YOUR_VM_INSTANCE

or go to Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> and click on Connect to serial console

*Check what went wrong.

*Disable access via serial port with gcloud command:
 gcloud compute instances add-metadata NAME_OF_YOUR_VM_INSTANCE \
 --metadata serial-port-enable=FALSE

or go to Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> click on EDIT -> go to section Remote access and uncheck Enable connecting to serial ports. Keep in mind that accordingly  to the documentation Interacting with the serial console:

Caution: The interactive serial console does not support IP-based access
restrictions such as IP whitelists. If you enable the interactive
serial console on an instance, clients can attempt to connect to that
instance from any IP address. Anybody can connect to that instance if
they know the correct SSH key, username, project ID, zone, and
instance name. Use firewall rules to control access to your network
and specific ports.

In addition, have a look at 3rd party example Resolving getting locked out of a Compute Engine.
If you weren't able to connect via serial console check logs:

*

*Go to Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM -> at the VM instance details find section Logs and click on Serial port 1 (console)

*Reboot your VM instance again.

*Check full boot log for any errors or/and warnings.

If you found errors/warning related to disk space you can try to resize it accordingly to the documentation Resizing a zonal persistent disk, also accordingly to the article Recovering an inaccessible instance or a full boot disk:
If nothing helped, try to follow other recommendations from the documentation Troubleshooting SSH and update your question with your attempts.


text:
Q: Python: How do I remove the input character length limit? Recently, while trying to input a 5944 characters long string to my Python program, I noticed that only 4095 characters were being stored in the variable:
# file.py
var = input("Enter: ") # Input 4095+ characters long string.
print(len(var)) # Outputs 4095.

I tried doing the same in REPL and surprisingly, all the characters were stored in the variable!
>>> var = input("Enter: ") # Input 4095+ characters long string.
Enter: <6016 characters long string>
>>> len(var)
6016

So I have two questions:

*

*Why is there a limit of 4095 input characters when taking it from a .py file but not in REPL?

*Is there a way I can remove the input limit in the file as well?

I do plan on implementing a feature to let the user pass a file with their input instead, but I am curious about the answers to the above questions.


text:
Q: lit element event listener doesn't force re render I have the following code:
  @property({type: Number}) ScreenSizeEnum = ScreenSize.Desktop;

  @property({type: Array}) menuData: IMenu[] = [];
  @property({type: Boolean}) isMobileMenuOpen: boolean = false;

  constructor() {
    super();
  }

  connectedCallback() {
    super.connectedCallback();
    window.addEventListener('resize', this.onResizeEvent);
  }

  disconnectedCallback() {
    window.removeEventListener('resize', this.onResizeEvent);
    super.disconnectedCallback();
  }

  onResizeEvent() {
    let oldVal = this.ScreenSizeEnum;
    if (window.outerWidth > 1000) {
      this.ScreenSizeEnum = ScreenSize.Desktop;
    } else if (window.outerWidth > 700 && window.outerWidth < 1000) {
      //Tablet
      this.ScreenSizeEnum = ScreenSize.Tablet;
    } else if (window.outerWidth < 700) {
      // mobile
      this.ScreenSizeEnum = ScreenSize.Mobile;
    }

  }

  render() {
    let device = this.getDeviceType();

    if (device == "desktop" || this.ScreenSizeEnum == ScreenSize.Desktop) {
      return html`
      <nav class="animate__animated animate__bounce animate__slow">
        <ul class="menu-ul">
       ${this.menuData.map(
        menuItem => html`
           <universe-menu-main .linkText="${menuItem.linkText}" .link="${menuItem.link}" .subMenu="${menuItem.subMenu}"></universe-menu-main>
          `
      )}
        </ul>
     </nav>

    `
    } else if (device == 'tablet' || this.ScreenSizeEnum == ScreenSize.Tablet) {
      return html`
        <tablet-menu .menuData="${this.menuData}"></tablet-menu>
    `;
    } else if (device == 'mobile' || this.ScreenSizeEnum == ScreenSize.Mobile) {
      return html`
      <mobile-menu .menuData="${this.menuData}" .isOpen="${this.isMobileMenuOpen}"></mobile-menu>
    `;
    }

  }

  getDeviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
      return "tablet";
    }
    if (
      /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
        ua
      )
    ) {
      return "mobile";
    }
    return "desktop";
  };

The resize event is fired, however whenever it changes the ScreenSizeEnum, the render function does not run.
Why does this happen, and how might I fix this?

A: Your problem is on how you have subscribed to the events and the funky behaviour of this in JS:
window.addEventListener('resize', this.onResizeEvent);

This means that inside onResizeEvent() the term this will refer to the window being resized, not your component.
You can fix this by using a lambda to force the this context (as inside the => body this is always the current context, not the event's:
window.addEventListener('resize', () => this.onResizeEvent());

Now, when onResizeEvent() event fires, inside it this will refer to the control, not the window.
The problem is that now you can't unsubscribe. We need to keep a reference to the wrapped method to remove it:
connectedCallback() {
    super.connectedCallback();
    window.addEventListener('resize', this.resizeContext, { capture: false, passive: true });
}

disconnectedCallback() {
    window.removeEventListener('resize', this.resizeContext);
    super.disconnectedCallback();
}

private readonly resizeContext: () => void = () => this.onResizeEvent();

As this is an external event causing an update it's a better fit for a ReactiveController to fire an update on the window events, and isolate all this resize code from your component.


text:
Q: Mongoose - how to use model inheritance in a sub document collection I have this model setup.  I want a parent record with an array of sub docs.
The sub docs have a schema, and use inheritance.
//
// Children

function abstractSchema() {
    Schema.apply(this, arguments);

    this.add({
        name: String
    });
};

util.inherits(abstractSchema, Schema);

var mySchema = new abstractSchema();

//
// Inherited Types

var textPropertySchema = new abstractSchema({
    length: Number
});

var numberPropertySchema = new abstractSchema({
    dp: Number
});

//
// Parent Model

var myModelSchema = mongoose.Schema({
    name: String,
    properties : [mySchema]
});

When i save each an instance of numberPropertySchema or textPropertySchema, the _t (type is written) and is able to deserialise properly.
When however added as a sub doc array, they're all persisted with the base object properties only.
Is there any way round this? any extensions that could be used?
Thanks
sam


text:
Q: Android studio 2.1.2 gradle aapt Syntax error: Unterminated quoted string I am trying to run Android Studio 2.1.2 on 32bit linux Mint 17.3.
Android studio is freshly installed.
When I rebuild a project or create a new one, I get errors like this in the Gradle Console:
AAPT err(Facade for 19314581): /home/user/Android/Sdk/build-tools/24.0.1/aapt: 2: /home/user/Android/Sdk/build-tools/24.0.1/aapt: Syntax error: Unterminated quoted string

Aapt is set as executable in build-tools directory.
I have set:
export SLAVE_AAPT_TIMEOUT=30
export ANDROID_EMULATOR_FORCE_32BIT=true

Any other idea how to fix this?

A: I had the same problem. I fixed it by downgrading my build tools version from 24.0.1 to 23.0.3.

*

*Download older build tool version from http://dl.google.com/android/repository/build-tools_r23.0.3-linux.zip

*Extract the downloaded file and paste it in your SDK build-tools directory( mostly /home/user/Android/Sdk/build-tools)

*Now in your app:gradle file change the buildToolsVersion to "23.0.3"

*Sync your gradle file and you should be good to go

Hope google fixes its build-tools bug

A: It might be the case the newest Android Studio does not run on 32bit only system.
On AndroidStudio download page the requirements for Linux are:

64-bit distribution capable of running 32-bit applications

There are also other StackOverflow questions regarding this:

*

*Android Studio 64-bit ERROR: 32-bit Linux Android emulator binaries are DEPRECATED

*ERROR: 32-bit Linux Android emulator binaries are DEPRECATED
The former one states:

Either one will allow you to use the 32-bit binaries,but please be aware that these will disappear in a future Android SDK
  release. Consider moving to a 64-bit Linux system before that happens.

So it might be the case the newest version does not support 32bit anymore.
Please try suggestions mentioned in the related answers (updating kernel/system). For Linux Mint there is mentioned [1]:

*

*Go to terminal

*type gedit .profile

*paste the below line at end of the page

*export ANDROID_EMULATOR_FORCE_32BIT=true

*type source .profile in terminal or restart system

But it also might be the case the newest Android Studio version does not support 32bit-only system anymore. In that case try to use an older version.


text:
Q: Separate functions in node.js file I want to separate functions in my node.js file. I don't know how to do it.
Here is an example:
    var var1 = 'I want to use this var along across all included files';
    var var2 = 'I want to use this var along across all included files';
    var actions = {
        send1() { //function 1 with var1 & var2 },
        send1a() { //function 1a with var1 & var2},
        send2() { //function 2 with var1 & var2},
        send2a() { //function 2a with var1 & var2}
    };

I want to export send1() & send1a() in function1.js and send2() & send2a() in function2.js in order to have clean files and use  var1 & var2.
How can I do that correctly?

A: Create 2 module files:
fun1.js
var var1 = "CONSTANT"

var actions = {
    // Whatever you want to export, you can write it here
    send1: function () {
        console.log("send1", var1)
    },
    send1a: function () {
        console.log("send1a")
    },
    a: "asdsad",
    b: 45,
    c: [1, 2, 3, 4, 5, 6],
    var1: var1
}

module.exports = actions

/*
 Or you can export using
 module.exports = {
     actions: actions,
     variableX: "something"
 }

 then in other modules, import it as
 var fun = require('./module_path')

 And use it as fun.variableX, fun.actions.send1 etc
 */

fun2.js
// Import variable from other module
var fun1 = require('./fun1')
// or just import var1
// var var1 = require('./fun1').var1

var actions = {
    send2: function () {
        console.log("send2", fun1.var1)
    },
    send2a: function () {
        console.log("send2a")
    }
}

module.exports = actions

Then in main file
main.js
// Import all modules
var fun1 = require('./fun1')
var fun2 = require('./fun2')

console.log(fun1.a) // Prints array

// fun1 will have all exported modules from fun1.js file
fun1.send1() // Prints send1 CONSTANT
fun1.send1a()

// fun2 will have all exported modules from fun2.js file
fun2.send2()  // Prints send2 CONSTANT
fun2.send2a()

A: What you would want to do is have an object containing all of your functions along side their "names" as the keys -
 You don't actually need the keys to be wrapped in quotes - I have done it here just for clarity.
var functions1 = require('./function1')
var functions2 = require('./function2')

var actions = {
    'send1':  functions1.send1
    'send1a': functions2.send1a
    ...
};

module.exports.actions = actions;

To call the functions via the actions object, all you would need to do is something like this -
var actionToDo = 'send1'; // key value that holds the function.
actions[actionToDo]() // here is the actual call to the `send1()` function from the `functions1,js` module.


text:
Q: AD Domain question In active directory on the user properties dialog and the account Tab there is a field.  The first textbox at top left is "User login name:", to the right of that there is a dropdown with @domain.local.  Does anyone know what property or object needs to be populates to put a value here when creating user programmatically?

A: That's the userPrincipalName (UPN). You typically set it to the value of sAMAccountName and add @domain.local. If your using the dsadd user command you need to specify the -upn parameter for this to be populated.