text:
Q: Adding Set-Cookie Header to Http Interceptor Angular I currently have an angular interceptor that sets some headers. I am aware that on api calls the set-cookie header is created. On my set-cookie header I am missing a secure flag and same-site flag. How would I go about setting those two flags?
import { Injectable } from "@angular/core";

import {
   HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from "@angular/common/http";

import { Observable } from "rxjs";
import { timeout } from "rxjs/operators";

@Injectable()
export class AcceptHeadersInterceptor implements HttpInterceptor {

   intercept(req: HttpRequest<any>, next: HttpHandler) {
    const newRequest = req.clone(
        { setHeaders: { "Accept": "application/json", "Content-Type": "application/json","X-Content-Type-Options": "nosniff" ,"X-Frame-Options": "SAMEORIGIN" }}
    );

    return next.handle(newRequest).pipe(timeout(100000)); //global request timeout after 10s for any api request. Prevent slow http requests.
   }
}


text:
Q: Django Creating form with a list Lets say I have a set of choices
choices1=(('mahi'),('is'),('awesome'))

I want to create a dropdown form menu to select those options. How would I do so?
I have tried
title1 = forms.CharField(max_length=2, choices=choices1) but get an error too many values to unpack.
What should I do?

A: You need ChoiceField which renders by default select field
title1 = forms.ChoiceField(choices=choices1)

And fix your choices to
(('mahi', 'mahi'),('is', 'is'),('awesome', 'awesome'))

It should be tuples

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invalid write of size 1, Address 0x... is not stack'd, malloc'd or (recently) free'd (Valgrind) I've tried to change the code to do what I want in different ways but doesn't seem to fix that Valgrind error.
Cadena::Cadena(unsigned tam, char c):s_(new char[tam+1]), tam_(tam)
{
    //c is ' ' by default
    memset(s_, c, tam+1);
    s_[tam]='\0';
}
...
Cadena& Cadena::substr(unsigned i, unsigned tam) const
{
    if(i>=tam_||i+tam>tam_) throw out_of_range("Posicion indicada fuera de rango");
    Cadena* subCad=new Cadena(tam);
    strncpy(subCad->s_, &s_[i], tam);
    return *subCad;
}

==9669== Invalid write of size 1
==9669==    at 0x1390CC: Cadena::Cadena(unsigned int, char) (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x13972B: Cadena::substr(unsigned int, unsigned int) const (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x12D436: test_cadena(_fctkern_t*) (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x137D42: main (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==  Address 0x105bc176f is not stack'd, malloc'd or (recently) free'd
==9669==
==9669==
==9669== Process terminating with default action of signal 11 (SIGSEGV)
==9669==  Access not within mapped region at address 0x105BC176F
==9669==    at 0x1390CC: Cadena::Cadena(unsigned int, char) (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x13972B: Cadena::substr(unsigned int, unsigned int) const (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x12D436: test_cadena(_fctkern_t*) (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==    by 0x137D42: main (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==9669==  If you believe this happened as a result of a stack
==9669==  overflow in your program's main thread (unlikely but
==9669==  possible), you can try to increase the size of the
==9669==  main thread stack using the --main-stacksize= flag.
==9669==  The main thread stack size used in this run was 8388608.

Another way:
Cadena& Cadena::substr(unsigned i, unsigned tam) const
{
    if(i>=tam_||i+tam>tam_) throw out_of_range("Posicion indicada fuera de rango");
    char res[tam+1];
    strncpy(res, s_+i, tam);
    res[tam]='\0';
    Cadena* subCad=new Cadena(tam);
    return *subCad;
}

==17029== Invalid write of size 1
==17029==    at 0x4C3304C: strncpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17029==    by 0x13979E: Cadena::substr(unsigned int, unsigned int) const (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==17029==  Address 0x1fff001000 is not stack'd, malloc'd or (recently) free'd
==17029==
==17029==
==17029== Process terminating with default action of signal 11 (SIGSEGV)
==17029==  Access not within mapped region at address 0x1FFF001000
==17029==    at 0x4C3304C: strncpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17029==    by 0x13979E: Cadena::substr(unsigned int, unsigned int) const (in /mnt/hgfs/mvpoosf/P1/test-P1-auto)
==17029==  If you believe this happened as a result of a stack
==17029==  overflow in your program's main thread (unlikely but
==17029==  possible), you can try to increase the size of the
==17029==  main thread stack using the --main-stacksize= flag.
==17029==  The main thread stack size used in this run was 8388608.

I'm passing this test (test-P1-auto):
  FCT_TEST_BGN(Cadena - Subcadena: tamanno mayor que longitud restante) {
    const Cadena a("0123456789");
    fct_chk_ex(out_of_range&, a.substr(9, 2));
  }
  FCT_TEST_END();

It returns a substring of two elements following the number 8. It's not possible as it throws out_of_range, so the test is OK. But when I use Valgrind, it's giving me those errors and I've been stuck here for hours.
Private part of my class Cadena:
private:
    char* s_;
    unsigned int tam_;

A: Sorry for the mistake guys, but as @Some programmer dude commented I didn't put the flag -g on my makefile that allows valgrind to tell me wich lines make the errors. Actually that wasn't the right test, it was the next one:
FCT_TEST_BGN(Cadena - Subcadena: tamanno negativo) {
    const Cadena a("0123456789");
    fct_chk_ex(out_of_range&, a.substr(9, -1));
  }
  FCT_TEST_END();

As I can see here Signed to unsigned conversion in C - is it always safe?, there's no way to get a negative value as unsigned and expect the sign "just to be removed". I solved it by changing it to int and checking inside the function if it's negative.
Thanks everyone for your help.


text:
Q: domain name UNC path is inaccessible if one domain controller goes down I have two domain controllers set up something like this:
ServerA.mydomain.local: 10.10.10.2 (Windows Server 2008)
ServerB.mydomain.local: 10.10.10.3 (Windows server 2008 R2)
For login scripts and the like, I use the path: \\mydomain.local\netlogon
This seems to always default to ServerB. If I turn off or restart ServerB (a process which takes several minutes), attempting to visit \\mydomain.local does not flip to ServerA. If I ping mydomain.local, it always returns the IP address of ServerB, even when it has been turned off.
I thought this was supposed to be a round-robin system.
Why am I seeing this behavior, and how can I fix it?

A: There's not really enough information here to answer your question, but hopefully some of this can give you a better understanding of how Active Directory functions and maybe you'll be pointed on the right path.

For login scripts and the like, I use the path: \\mydomain.local\netlogon

mydomain.local is a DNS zone that lives on the DNS servers for your Active Directory. By default, new domain controllers register A records for themselves in this zone and they also register A records for the zone name itself as their IP. The records should be in the mydomain.local zone and look like this:
(Same as parent folder) Host(A) 10.10.10.2 <timestamp>
(Same as parent folder) Host(A) 10.10.10.3 <timestamp>
If you do nslookup mydomain.local the DNS server should return a list of all domain controllers. If not, you're missing an A record at the very least.
If one of those is missing, you should re-create it manually and do some root-cause analysis to find why it's missing. When a client tries to look up \\mydomain.local in this case, it is doing it by the A record.
You should also check the _msdcs zone and make sure that both servers are listed there where they should be. If you can log on while serverB is offline, then this zone is likely OK.
You should use dcdiag.exe just to make sure that both domain controllers are in fact healthy and functioning properly.

Also, if you're not running DNS on both DCs, you should and your clients should use both servers for DNS.
Also, the DCs should use each other as the primary server for name resolution and themselves as secondaries to prevent replication issues. Just to clarify, this means:
serverA
Primary DNS    10.10.10.3
Secondary DNS  127.0.0.1

serverB
Primary DNS    10.10.10.2
Secondary DNS  127.0.0.1

If you don't do this, you run the risk of breaking replication in certain situations.

A: Based on the fact that DHCP is complaining when you try to add the server IP address I suggest you check the following:
At a Prompt:
C:\> nslookup
C:\> server servera
C:\> mydomain.local

Run this for both Server A & B. If you don't get a response from either of them you may have two issues:

*

*DNS Service is not running or enabled

*Firewall may be blocking traffic to the server

Let us know if the commands both come back properly.

A: If nslookup shows dns timeout 2 seconds, it generally means you are missing a pointer record for that server. Add pointer record  in the reverse zone to correct the "unknown" issue in nslookup and queries. I know this question is old. I just thought I would let anyone who has this issue know how to correct it.


text:
Q: 'hostViewController must not be nil on STPPaymentContext when calling pushPaymentOptionsViewController on it This is my SignUpViewController:-
 import UIKit
 import Firebase
  import Stripe

   class SignUpViewController: UIViewController {
    var paymentContext = STPPaymentContext()
   @IBOutlet weak var email: UITextField!
   @IBOutlet weak var password: UITextField!
   @IBOutlet weak var passwordConfirm: UITextField!
   @IBAction func signUpAction(_ sender: Any) {
      if password.text != passwordConfirm.text {let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

    alertController.addAction(defaultAction)
   self.present(alertController, animated: true, completion: nil)
        }else{
   Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in if error == nil {
      self.performSegue(withIdentifier: "signupToHome", sender: self)

                }
     else{
   let alertController = UIAlertController(title: "Error", message:    error?.localizedDescription, preferredStyle: .alert)
   let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

       alertController.addAction(defaultAction)
       self.present(alertController, animated: true, completion: nil)
           }
             }
         }
    }

     @IBAction func userIconClicked(_ sender: Any){

       let userSheet = UIAlertController(title: nil, message: nil, preferredStyle:    .actionSheet)

    let logout = UIAlertAction(title: "Logout", style: .default) { (action) in
        // Logout
        do {
            try Auth.auth().signOut()
        } catch {
            debugPrint(error.localizedDescription)
        }
    }

    let manageCards = UIAlertAction(title: "Manage Credit Cards", style: .default) {  (action) in
        // Display Stripe Widget
        self.paymentContext.pushPaymentOptionsViewController()
    }

    let manageBanks = UIAlertAction(title: "Manage Bank Accounts", style: .default) { (action) in
        // Manage Bank Accounts
    }

    let close = UIAlertAction(title: "Close", style: .cancel)

    userSheet.addAction(manageCards)
    userSheet.addAction(manageBanks)
    userSheet.addAction(logout)
    userSheet.addAction(close)

    present(userSheet, animated: true)
 }
func setupStripe() {

    Wallet.instance.customerContext = STPCustomerContext(keyProvider:  StripeApiClient())

    let config = STPPaymentConfiguration.shared
    paymentContext = STPPaymentContext(customerContext:     Wallet.instance.customerContext,
                                       configuration: config(),
                                       theme: .default())

    paymentContext.hostViewController = self

     }
   }

This what it is in the simulator:--

The "Button" on the right-hand-upper-corner is linked to "@IBAction func userIconClicked(_ sender: Any)". When I click on this button, the following shows up on the simulator: -

Now, when I click on "Manage Credit Cards", it  shows error in the AppDelegate - -  Thread 1: "hostViewController must not be nil on STPPaymentContext when calling pushPaymentOptionsViewController on it. Next time, set the hostViewController property first! as shown in the screenshot below:-

What am I doing wrong ?
Edit 1: after humnoz  comment, I called "setupStripe()", still same error -
  import UIKit
  import Firebase
  import Stripe

class SignUpViewController: UIViewController {
var paymentContext = STPPaymentContext()
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var passwordConfirm: UITextField!
@IBAction func signUpAction(_ sender: Any) {
    if password.text != passwordConfirm.text {let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
        }else{
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in if error == nil {
   self.performSegue(withIdentifier: "signupToHome", sender: self)

                }
 else{
   let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
   let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

    alertController.addAction(defaultAction)
    self.present(alertController, animated: true, completion: nil)
       }
            }
      }
}
func viewDidLoad(_ animated: Bool) {
    Auth.auth().addStateDidChangeListener { (auth, user) in
        // If there is a user logged in, stay here on homeVC
        // else, take them to the login page.

        if user == nil {
            let loginVC = LoginRegisterVC()
            loginVC.modalPresentationStyle = .fullScreen
            self.present(loginVC, animated: true)
        } else {
            UserManager.instance.getCurrentUser {
                self.setupStripe()
            }
        }
    }
}
@IBAction func userIconClicked(_ sender: Any){

    let userSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    let logout = UIAlertAction(title: "Logout", style: .default) { (action) in
        // Logout
        do {
            try Auth.auth().signOut()
        } catch {
            debugPrint(error.localizedDescription)
        }
    }

    let manageCards = UIAlertAction(title: "Manage Credit Cards", style: .default) { (action) in
        // Display Stripe Widget
        self.paymentContext.pushPaymentOptionsViewController()
    }

    let manageBanks = UIAlertAction(title: "Manage Bank Accounts", style: .default) { (action) in
        // Manage Bank Accounts
    }

    let close = UIAlertAction(title: "Close", style: .cancel)

    userSheet.addAction(manageCards)
    userSheet.addAction(manageBanks)
    userSheet.addAction(logout)
    userSheet.addAction(close)

    present(userSheet, animated: true)
}
func setupStripe() {

    Wallet.instance.customerContext = STPCustomerContext(keyProvider: StripeApiClient())

    let config = STPPaymentConfiguration.shared
    paymentContext = STPPaymentContext(customerContext: Wallet.instance.customerContext,
                                       configuration: config(),
                                       theme: .default())

    paymentContext.hostViewController = self

  }

}

A: This post helped me im my case   - https://it.wenda123.org/question/stack/40711655/stripe-checkout-ios-integration-with-storyboards-in-swift-3


text:
Q: How to clear a SAPUI5 input field with only value help input allowed? my SAPUI5 app has an input field where the valid values must be obtained through a value help:
<Input showValueHelp="true" valueHelpOnly="true"
                           valueHelpRequest="onValueHelpRequest"
                           value="{myModel>/myField}"

The value help is realized with a SelectDialog, where the only options are

*

*choose one or

*cancel

The problem is now the following flow:

*

*User opens value help dialog to choose one item and presses Confirm

*Input field now displays chosen value

*User wants to clear the input, because it's optional

Unfortunately,

*

*sap.m.Input doesn't provide a clear button

*sap.m.SelectDialog doesn't provide the possibility to add a custom button like Clear

*The input is layed out in a SimpleForm with 2 columns, labels and input fields, so it would be hard to add a clear button

*The Gateway entity set which feeds the value help dialog list doesn't have a totally empty line

*I don't like the workaround to switch the SelectDialog to multiSelect just for the purpose that the user can choose "one or none". I also think it would be hard to explain to the user "if you want to remove the value, hold the control key and click on the previously selected item again".

Any ideas out there how to easily implement a clear button or something similar?

A: valueHelpOnly="false"

// with this user can either fill by F4 (assisted input) or by typing input..
and if you want to clear you can add a button  and set the value to null
oInput.setValue("");


text:
Q: Improve file extension detection and restriction on upload I know there are many questions and answers related to this but I would like to know the best way to do the restriction on file extension on both server and client side.
PHP
$allowedTypes = array('gif', 'png', 'jpeg', 'jpg', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'mp3', 'mp4', 'rar', 'zip', 'txt');

$File_Name          = strtolower($_FILES['uploadfile']['name']);
$File_Ext           = pathinfo($File_Name, PATHINFO_EXTENSION);
if(!in_array($File_Ext, $allowedTypes)) {
    die('Unsupported File format!');
}

JS
var ftype = $('#uploadfile')[0].files[0].type; // get file type

        //allowed file types
        switch(ftype)
        {
            case 'image/png':
            case 'image/gif':
            case 'image/jpeg':
            case 'image/pjpeg':
            case 'text/plain':
            case 'text/html':
            case 'application/x-zip-compressed':
            case 'application/x-rar-compressed':
            case 'application/octet-stream':
            case 'application/pdf':
            case 'application/msword':
            case 'application/vnd.ms-excel':
            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
            case 'video/mp4':
                break;
            default:
                notify("Unsupported file type!");
                return false
        }

A: You can use accept attribute at <input type="file"> element

accept
If the value of the type attribute is file, this attribute indicates the types of files that the server accepts;
  otherwise it is ignored. The value must be a comma-separated list of
  unique content type specifiers:

*

*A file extension starting with the STOP character (U+002E). (E.g.:    ".jpg,.png,.doc")

<input type="file" accept=".gif,.png,.jpeg,.jpg,.pdf,.xls,.xlsx,.doc,.docx,.ppt,.pptx,.mp3,.mp4,.rar,.zip,.txt" />


text:
Q: Mantener Check Activado cuando se regresa de un pagina posterior Hola estoy implementando un check en mi html y cuando se da click y paso a la siguiente pagina y regreso el check ya no esta seleccionado y quisiera saber como mantener el check activado o como implementar el ng-checked
 oncheckvalidarTel(param:string){
      if(param=="Y"){
        this.isDisableTel?this.isDisableTel=false:this.isDisableTel=true;
        this.clienteBean.clienteResponse.detalle.Cliente.numeroTelfMovil="";
        this.clienteBean.clienteResponse.detalle.Cliente.codTelfPais="";
      }
    }

en mi html quiero colocar el ng-checked pero no se que tipo de valor pasarle
si alguien me pudiera ayudar. gracias.
   <mat-checkbox  (click)="oncheckvalidarTel('Y')">
      No tiene
   </mat-checkbox>

A: trata de usar el atributo [checked] para igualar a una variable iniciada, seria algo así:
<mat-checkbox [checked]="estado" (click)="oncheckvalidarTel()">
  No tiene

Y en el component.ts inicias la variable con el estado:
estado: boolean = true;
oncheckvalidarTel(){
  estado = !estado
  if(estado){
    this.isDisableTel?this.isDisableTel=false:this.isDisableTel=true;
    this.clienteBean.clienteResponse.detalle.Cliente.numeroTelfMovil="";
    this.clienteBean.clienteResponse.detalle.Cliente.codTelfPais="";
  }
}


text:
Q: which is faster spark.sql or df.filter("").select("") . using scala I have a table that is a df which also has a view created with
table.createOrReplaceTempView("table")

and the query is
spark.sql("SELECT column1 from TABLE where column2 = 'VALUE'")

i want to rewrite the query as
TABLE.filter(TABLE("column2") === "value").select(col("column1"))

so which query is much faster the normal spark.sql or with filter and select ? when using large datasets.

A: I assume that if their physical execution plan is exactly the same, performance will be the same as well. So let's do a test, on Spark 2.2.0:
scala> import spark.implicits._
import spark.implicits._

scala> case class Record(column1: String, column2: String)
defined class Record

scala> val table = List(Record("foo", "value"), Record("bar", "notvalue")).toDF
table: org.apache.spark.sql.DataFrame = [column1: string, column2: string]

scala> table.createOrReplaceTempView("table")

scala> val a = spark.sql("SELECT column1 from TABLE where column2 = 'value'")
a: org.apache.spark.sql.DataFrame = [column1: string]

scala> val b = table.filter(table("column2") === "value").select(col("column1"))
b: org.apache.spark.sql.DataFrame = [column1: string]

scala> a.explain()
== Physical Plan ==
*Project [column1#41]
+- *Filter (isnotnull(column2#42) && (column2#42 = value))
   +- LocalTableScan [column1#41, column2#42]

scala> b.explain()
== Physical Plan ==
*Project [column1#41]
+- *Filter (isnotnull(column2#42) && (column2#42 = value))
   +- LocalTableScan [column1#41, column2#42]

Looks like there's no difference at all...

A: Depends on your use case just try both of them which works fast is the best suit for you !
I would recommend you to use
1.spark.time(df.filter("").select(""))

2.spark.time(spark.sql(""))

you can print out the time and use the one which takes the least time to execute in your code to run it faster.

A: I may be wrong, but it is exactly the same. Spark is gonna read both codes, interpret it via Catalyst and generate RDD code through Tungsten optimization.
The main change is the ease of coding and debugging. With spark.sql, you won't have any infos at compile time about errors or type mistakes...
And using .filter, .select is much easier to indent, to read, etc...
TLDR : Performance Wise = the same / Coding wise = spark.sql so much worse


text:
Q: Appending blank rows to dataframe if column does not exist This question is kind of odd and complex, so bear with me, please.
I have several massive CSV files (GB size) that I am importing with pandas.  These CSV files are dumps of data collected by a data acquisition system, and I don't need most of it, so I'm using the usecols parameter to filter out the relevant data.  The issue is that not all of the CSV files have all of the columns I need (a property of the data system being used).
The problem is that, if the column doesn't exist in the file but is specified in usecols, read_csv throws an error.
Is there a straightforward way to force a specified column set in a dataframe and have pandas just return blank rows if the column doesn't exist?  I thought about iterating over each column for each file and working the resulting series into the dataframe, but that seems inefficient and unwieldy.

A:
I thought about iterating over each column for each file and working the resulting series into the dataframe, but that seems inefficient and unwieldy.

Assuming some kind of master list all_cols_to_use, can you do something like:
def parse_big_csv(csvpath):
    with open(csvpath, 'r') as infile:
        header = infile.readline().strip().split(',')
        cols_to_use = sorted(set(header) & set(all_cols_to_use))
        missing_cols = sorted(set(all_cols_to_use) - set(header))
    df = pd.read_csv(csvpath, usecols=cols_to_use)
    df.loc[:, missing_cols] = np.nan
    return df

This assumes that you're okay with filling the missing columns with np.nan, but should work. (Also, if you're concatenating the data frames, the missing columns will be in the final df and filled with np.nan as appropriate.)


text:
Q: Are S3 500 internal error retries necessary when using aws client? I've read that you should retry 500 internal errors with S3, but I also read that the client handles things like retries (defaults to 10), retry interval, circuitbreaker, etc. Are explicit retries necessary when using the aws client?

A: It looks like the answer is no. The AWS SDK handles retries fairly robustly.


text:
Q: Bank in java deleting account Hello I'm making a bank application in Java.
My problem is that I don't know how to delete created accounts.
When I create a new account it gets a new number, but I don't know how to delete an account if there are like 3 accounts and I want to delete the account number 2 and when I want to create a new account it would get the ID number 2. (There is number 1 and 3).
When I would like to create another account, I want to change its ID to 4.
Thanks in advance. :)
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    Bank myBank = new Bank();

    int user_choice = 2;

    do {
        //display menu to user
        //ask user for his choice and validate it (make sure it is between 1 and 6)
        System.out.println();
        System.out.println("1) Open a new bank account");
        System.out.println("2) Deposit to a bank account");
        System.out.println("3) Withdraw to bank account");
        System.out.println("4) Print short account information");
        System.out.println("5) Print the detailed account information including last transactions");
        System.out.println("6) Quit");
        System.out.println();
        System.out.print("Enter choice [1-6]: ");
        user_choice = s.nextInt();
        switch (user_choice) {
            case 1: System.out.println("Enter a customer name");
                    String cn = s.next();
                    System.out.println("Enter a opening balance");
                    double d = s.nextDouble();
                    System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
                    break;
            case 2: System.out.println("Enter a account number");
                    int an = s.nextInt();
                    System.out.println("Enter a deposit amount");
                    double da = s.nextDouble();
                    myBank.depositTo(an, da);
                    break;
            case 3: System.out.println("Enter a account number");
                    int acn = s.nextInt();
                    System.out.println("Enter a withdraw amount");
                    double wa = s.nextDouble();
                    myBank.withdrawFrom(acn, wa);
                    break;
            case 4: System.out.println("Enter a account number");
                    int anum = s.nextInt();
                    myBank.printAccountInfo(anum);
                    break;
           case 5:  System.out.println("Enter a account number");
                    anum = s.nextInt();
                    myBank.printTransactionInfo(anum);
                    break;
          default: System.out.println("Invalid option. Please try again.");

        }
}
while (user_choice != '6');
}

static class Bank {
private BankAccount[] accounts;     // all the bank accounts at this bank
private int numOfAccounts;      // the number of bank accounts at this bank

    //Constructor: A new Bank object initially doesn't contain any accounts.
public Bank() {
    accounts = new BankAccount[100];
    numOfAccounts = 0;
    }

// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {

    BankAccount b = new BankAccount(customerName, openingBalance);
    accounts[numOfAccounts] = b;
    numOfAccounts++;
    return b.getAccountNum();
}

// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
    for (int i =0; i<numOfAccounts; i++) {
        if (accountNum == accounts[i].getAccountNum()  ) {
            accounts[i].withdraw(amount);
            System.out.println("Amount withdrawn successfully");
            return;
        }
    }
    System.out.println("Account number not found.");
    }

// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
    for (int i =0; i<numOfAccounts; i++) {
        if (accountNum == accounts[i].getAccountNum()  ) {
            accounts[i].deposit(amount);
            System.out.println("Amount deposited successfully");
            return;
        }
    }
    System.out.println("Account number not found.");
}

// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
    for (int i =0; i<numOfAccounts; i++) {
                if (accountNum == accounts[i].getAccountNum()  ) {
                    System.out.println(accounts[i].getAccountInfo());
                    return;
                }
            }
    System.out.println("Account number not found.");
}

public void printTransactionInfo(int accountNum) {
    for (int i =0; i<numOfAccounts; i++) {
                if (accountNum == accounts[i].getAccountNum()  ) {
                    System.out.println(accounts[i].getAccountInfo());
                    System.out.println("Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
                    return;
                }
            }
    System.out.println("Account number not found.");
}

// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
    for (int i =0; i<numOfAccounts; i++) {
                        if (accountNum == accounts[i].getAccountNum()  ) {
                            System.out.println(accounts[i].getAccountInfo());
                            System.out.println(accounts[i].getTransactionInfo(n));
                            return;
                        }
                    }
    System.out.println("Account number not found.");
    }

}
    static class BankAccount{

       private int accountNum;
       private String customerName;
       private double balance;
       private double[] transactions;
       private String[] transactionsSummary;
       private int numOfTransactions;
       private  static int noOfAccounts=0;

       public String getAccountInfo(){
           return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
       }

       public String getTransactionInfo(int n)
       {
            String transaction = transactionsSummary[n];
            if (transaction == null) {
                return "No transaction exists with that number.";
            }
            else {
                return transaction;
            }
        }

       public BankAccount(String abc, double xyz){
         customerName = abc;
         balance = xyz;
         noOfAccounts ++;
         accountNum = noOfAccounts;
         transactions = new double[100];
         transactionsSummary = new String[100];
         transactions[0] = balance;
         transactionsSummary[0] = "A balance of : $" + Double.toString(balance) + " was deposited.";
         numOfTransactions = 1;
       }

    public int getAccountNum(){
        return accountNum;
    }

    public int getNumberOfTransactions() {
        return numOfTransactions;
    }

    public void deposit(double amount){

        if (amount<=0) {
            System.out.println("Amount to be deposited should be positive");
        } else {
            balance = balance + amount;
            transactions[numOfTransactions] = amount;
            transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was deposited.";
            numOfTransactions++;
        }
    }
    public void withdraw(double amount)
    {
        if (amount<=0){
             System.out.println("Amount to be withdrawn should be positive");
         }
        else
        {
            if (balance < amount) {
                System.out.println("Insufficient balance");
            } else {
                balance = balance - amount;
                transactions[numOfTransactions] = amount;
                transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was withdrawn.";
                numOfTransactions++;
            }
        }
    }

    }//end of class
}

A: Re-using account numbers is wrong in principle, but if you insist on doing it that way:
You'll probably want to mark accounts as active or non-active. When you create an account, mark it as active. When you delete an account, mark it as non-active.
When the program decides an account number for a "new" account, first get an ordered list of all the non-active accounts and choose the first one. If there aren't any non-active accounts, then use the incremented numOfAccounts variable.

A: Maybe you should consider re thinking the logic of this.
However, a solution could be marking a bank account for deletion adding a field such as:
class BankAccount{
...
private boolean isMarkedForDeletion = false;
...
}

And add getters and setters to it.
Now you would:
1) When deleting an account, switch that field to true.
public int closeAccount(int id) {
boolean isAccountFound = false;
int i = 0;
while(i < numOfAccounts && isAccountFound == false)
{
  // if() // Add here the condition to find the account to delete.
  // { accounts[i].isMarkedForDeletion = true; }
}

Now, no deposit or other actions should be performed on this account anymore.
2) When creating a new account, loop through each of the existing accounts and verify whether an account is marked for deletion - possibly using a while loop.
If an account was to be found as "marked for deletion = true"  then you would redeclare the element currently iterated to be a new account having the same id of the old one.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);

boolean isAccountFound = false;
int i = 0;
while(isAccountFound == false && i < accounts.length)
{
  // if() add conditions for this account to replace the old one.
  // hint: use the isMarkedForDeletion field!
  // Finally add the new value assignment ( accounts[i] = ... )
  // return the account number.
}
// This will happen in the case there were no matches.
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}

A: I would use the fact that there is a max number of accounts possible (100) and thus a fixed sized array.
public int openNewAccount(String customerName, double openingBalance) {
    for (int i = 0; i < 100; i++) {
        if (accounts[i] == null) { //Empty slot
            BankAccount b = new BankAccount(customerName, openingBalance);
            b.accountNum = i + 1;
            break;
        }
    }
    return b.getAccountNum();
}

and the delete would mean setting that slot to null
public void deleteAccount(int accountNo) {
    accounts[accountNo - 1] = null;
}

both methods could perhaps use some error handling depending on what feedback is needed. You would also need to remove unnecessary stuff from the BankAccount constructor.


text:
Q: Python - Lark - Grammar - Can not generate AST i am currently trying to generate an abstract syntax tree from a functional expression, which could be for example:
OR(FunctionOne("valueA", "valueB", "valueC"), FunctionTwo("valueD", "valueE", "valueF"))

Basically a simple concatenation of operators(AND | OR) and their functions(can be nested).
I would like to transfer this string to an abstract syntax tree, e.g. :
value
  OR
    FunctionOne:
      value1: valueA
      value2: valueB
      value3: valueC
    FunctionTwo:
      value4: valueD
      value5: valueE
      value6: valueF

What i did so far...
from lark import Lark
parser = Lark(r"""
    value: operator

    operator : operatorvalue"("function"(how_to_handle_params)"*")"
    operatorvalue : "OR" | "AND"

    function : "FunctionOne" | "FunctionTwo"

    """, start='value')

Can anybody help me out with this issue?
Just need some starting point, as docs only handle json...
Thanks and Greetings!

A: As a general rule, you should try to represent the responsibility of each entity in syntax. So, for example, a function contains its own arguments:
function: NAME "(" params? ")"

params: (NAME ","?)+

Lark has plenty of example grammars, such as a calculator, Python, and Lark (its own syntax)


text:
Q: Xamarin.iOS: NFC App Not Running in Simulator, throws error I've built up an NFC based app over Xamarin.iOS which reads and writes data on an NFC tag.
It works without any issues when run on an actual iPhone connected over USB.
However, I need to check its UI on different screen sizes so I attempted running it on simulator. However, it throws some compile time errors, first one of which is -
/.../iPhoneSimulator/Debug/device-builds/iphone 8-14.5/mtouch-cache/registrar.h(58,58): Error GE71D2E27: no type or protocol named 'NFCTagReaderSessionDelegate' (GE71D2E27) (WRConnectApp.iOS)
and then few occurrences of 'expected a type()' which seem to be related.
When ran on a physical device, I see no such errors at all.
I also checked that the iOS version on the phone and on the simulator is same.
I can understand that the Mac doesn't have NFC and the app depends on NFC libraries which it might not be finding during simulation, but I couldn't find a way around.
Is there a way to do so? Or is there some other problem which needs to be sorted in the first place?

A: To test an app with NFC feature, a real device must be used instead of an iOS simulator


text:
Q: create file using ansible variable i am trying to create file which will be use to create partition in windows.
I am using variables in below format.
additional_disks:
- drive_letter: E
  mount_point: TMP1
  disk_size: 7
  label: DBInstall
  block_size: 4096k
  datastore: vsanDatastoreCMP001
- drive_letter: F
  mount_point: TMP2
  disk_size: 9
  label: DBInstall1
  block_size: 4096k
  datastore: vsanDatastoreCMP001
- drive_letter: G
  mount_point: TMP3
  disk_size: 10
  label: DBInstall2
  block_size: 4096k
  datastore: vsanDatastoreCMP001

I am using below code:
- name: Testing Iteration
  copy:
    dest: /tmp/testtemp
    content: |
      {% for var in additional_disks %}
      select disk {{ my_idx | int +2 }}
      create partition primary
      assign letter "{{ item.drive_letter }}"
      format fs=ntfs label={{ item.label }} quick
      {% endfor %}
  with_items:
    - "{{ additional_disks }}"
  loop_control:
    index_var: my_idx
    label: " "
  delegate_to: localhost

Gettin output:
select disk 4
create partition primary
assign letter "G"
format fs=ntfs label=DBInstall2 quick
select disk 4
create partition primary
assign letter "G"
format fs=ntfs label=DBInstall2 quick
select disk 4
create partition primary
assign letter "G"
format fs=ntfs label=DBInstall2 quick

expected output:
select disk 2
create partition primary
assign letter E
format fs=ntfs label=DBInstall quick

select disk 3
create partition primary
assign letter F
format fs=ntfs label=DBInstall quick

select disk 4
create partition primary
assign letter G
format fs=ntfs label=DBInstall2 quick

Can you please help to get correct output

A: here is my code: you can just leverage jinja2 loop.index, you do not have to use loop_control here, if you add -D option, you will find that /tmp/testtemp was overwrite three times.
    - name: Testing Iteration
      copy:
        dest: /tmp/testtemp
        content: |
          {% for var in additional_disks %}
          select disk {{ loop.index | int +2 }}
          create partition primary
          assign letter "{{ var.drive_letter }}"
          format fs=ntfs label={{ var.label }} quick
          {% endfor %}
      loop: "{{ additional_disks }}"
      #loop_control:
      #  index_var: my_idx
      #  label: " "

and also I do not recommend use copy module here, from the ansible-doc copy:
- content
        When used instead of `src', sets the contents of a file directly to the specified value.
        Works only when `dest' is a file. Creates the file if it does not exist.
        For advanced formatting or if `content' contains a variable, use the [template] module.

so if you want to use template instead of copy module, here is the template file
{% for var in additional_disks %}
select disk {{ loop.index | int +2 }}
create partition primary
assign letter "{{ var.drive_letter }}"
format fs=ntfs label={{ var.label }} quick
{% endfor %}


text:
Q: Data validation without loosing values entered in the form by user Lets us consider a simple registrations form with fields like username, email, date of birth, password etc.
And there are some data validation rules applied like:
'email'=>array(
                'emailrule'=>array(
                    'rule' => 'email',
                    'message' => 'You have entered an invalid e-mail address.'
                ),
                'isUnique' => array(
                    'rule' => 'isUnique',
                    'message' => 'The e-mail address already exists.',
                ),

            ),

When the user submits the form the data gets validated. If invalid the user is redirect to the form  and error is shown to the user. But this time since the page has refreshed the values entered by the user have gone.
is there some way to retain those values??


text:
Q: How to stop excel copying adjecent formatting Excel seems to be determined to copy the format of an adjacent cell. For instance, when I have a cell that has a green background with a number in it, then when entering a number in an adjacent cell the background also becomes green. This is extremely annoying in many cases and requires me to clear the background.
Is there a way to turn this "Excel thinks for me" feature off?

A: Yes, there is this feature in Excel to Turn on or off extended formats and formulas.
For Excel 2007:
1. Click on Office Button  at the top left of the screen.
2. At the bottom, you will see the Excel Options button. Click it to open Excel Options Window.
3. Select Advanced from the list on the left side.
4. Uncheck Extend data range formats and formulas.

For Older versions of Excel:
Go to the Tools, Options and select the Edit Tab, then uncheck the Extend list formats and formulas.


text:
Q: ERROR : Gradle task assembleDebug failed with exit code 1 I recently started android app development and I am working with flutter on android studio. On clicking on RUN I get the following error. Can anyone suggest me a solution?
Launching lib\main.dart on Redmi 7A in debug mode...

Running Gradle task 'assembleDebug'...
Checking the license for package Android SDK Build-Tools 28.0.3 in C:\Users\Admin\AppData\Local\Android\sdk\licenses
Warning: License for package Android SDK Build-Tools 28.0.3 not accepted.
Checking the license for package Android SDK Platform 28 in C:\Users\Admin\AppData\Local\Android\sdk\licenses
Warning: License for package Android SDK Platform 28 not accepted.
FAILURE: Build failed with an exception.

*

*What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

Failed to install the following Android SDK packages as some licences have not been accepted.
   build-tools;28.0.3 Android SDK Build-Tools 28.0.3
   platforms;android-28 Android SDK Platform 28
  To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
  Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html

Using Android SDK: C:\Users\Admin\AppData\Local\Android\sdk

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 2s
Finished with error: Gradle task assembleDebug failed with exit code 1


text:
Q: Unknown record property / related component "permissions" on "sfGuardUser" I'm having a weird problem with my symfony backend. I can log in once, but after that I get
Unknown record property / related component "permissions" on "sfGuardUser"
Also, when I do login and try to edit a record from any module, I get
Fatal error: Call to a member function setLabel() on a non-object in plugins/sfDoctrineGuardPlugin/lib/form/doctrine/base/BasesfGuardUserAdminForm.class.php on line 28
Please help!

A: I found the problem. I had to delete all SFGuard Forms from lib/form/doctrine/base and reinstall.

A: Reinstalling did not help me. After all, this is a new install.
I had to modify the lines in /plugins/sfDoctrineGuardPlugin/lib/form/doctrine/base/BasesfGuardUserAdminForm.class
    //Fatal error: Call to a member function setLabel()
    if(isset($this->widgetSchema['groups_list']))
    {
      $this->widgetSchema['groups_list']->setLabel('Groups');
    }

    if (isset($this->widgetSchema['permissions_list']))
    {
    $this->widgetSchema['permissions_list']->setLabel('Permissions');
    }

in order to get to the next error
 of
Unknown record property / related component "permissions" on "sfGuardUser"


text:
Q: Convert NSArray to Swift Array and filter out Elements not matching T Converting NSArray to a Swift Array of Type T is easy, if all the elements are indeed of type T already:
let arr1 : NSArray = [1,2,3]
let arr2 = arr1 as? Array<Int> // works

But now assume a non-homogenous NSArray with objects that do not match T:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = arr1 as? Array<Int> // nil, as not all elements are of type Int

What I try to achieve is a downcast that filters out all elements not matching T. So in the above case I want to get an Array<Int> that contains the objects [1,2,3] only.
How to do that elegantly?

A: Condensed:
let arr1 : NSArray = [1,2,3,"a"]
let arr2 = (arr1 as Array<AnyObject>).filter { $0 is Int } as! Array<Int>

Step by step:
let arr2 = arr1 as Array<AnyObject>  // convert NSArray to Array of AnyObject
let arr3 = arr2.filter { $0 is Int } // keep only objects that are of type Int
let arr4 = arr3 as! Array<Int>       // force cast to Array<Int>, as now you know that all objects are of that type


text:
Q: query database for address and display it on a google map I have a db with addresses I need to display on a google map that would then add a marker to the map after the user has used the search form to search for the desired address. I have looked everywhere and I do not know how to link the google map to the db to show the address and display a marker. How do I connect the search form to query the db and then display it on a google map? I have researched static maps and adding markers but I cannot find how to do this. I have been searching for months and months and this is the final peice of info i need to complete this project. Can someonen please direct me or tell me how to do this? I would give my right arm for this information by now. Thank you in advance.

A: Take a look at this API, it will return coordinates based on an address: http://code.google.com/apis/maps/documentation/geocoding/
After that, look here, and insert the coordinates on the map for a static map: http://code.google.com/apis/maps/documentation/staticmaps/
If  you don't know how to do all this, I recommend doing some PHP/MySQL tutorials.


text:
Q: combine lists filling in with blanks python I have three lists
l1 = ['a', 'b', 'c']
l2 = ['1', '2', '3', '4']
l3 = ['z', 'l', 'd', 't', 'm']

I want to combine them to create
lc = [['a', '1', 'z'], ['b', '2', 'l'], ['c', '3', 'd'],
      [' ', '4', 't'], [' ', ' ', 'm']]

this question shows the roundrobin iter, but it just fills and doesn't do the blanks. I don't understand how to modify the iter to instead of removing the exhausted list but to keep on adding blanks


text:
Q: background image for CGContext Question: How do I display a background image underneath a CGContext?
I have created a view controller using the storyboard and placed a view with a full-screen background image.  Then, using the same view controller, I created a outlet to a UIView that has a CGContext where I draw a few lines.
Everything works except that the drawing takes place underneath the background image. (Suddenly I wonder if it's not the CGContext but the UIView that is the problem.)
I found a similar question here, but the solution makes it sound like the background image has to be constantly refreshed using CGContextDrawImage with a CGImageRef.  Which may be true, but a static image being constantly refreshed doesn't sound like a very elegant solution.  Thank you!

A: Create custom UIImageView subclass where you will draw your custom background.
Better to subclass UIImageView instead of UIView, because in this case you don't get problems with adding other views above this in Interface Builder.
Add UIImageView to your view controller, and change class to your custom class. Add all other views above.

A: Question: How do I display a background image underneath a CGContext?
Answer: Set the color of the view with the CGContext to Clear Color.
That way the background image is visible as well as the lines that are subsequently drawn. Guess I kind of overcomplicated that one.
Thank you for the response Vitaliy.


text:
Q: Accordion Troubleshooting I know I keep putting out these troubleshooting things, but I seriously have researched this on api documentation and looked for other answers on Stackoverflow and nothing is coming up. I have a accordion div that takes the right css, but is not working as an accordion. This is html code:

Page One

Subpage 1A

Subpage 1B

Subpage 1C

Page Two

Subpage 2A

Subpage 2B

Subpage 2C

Page Three

Subpage 3A

Subpage 3B

Subpage 3C

And my javascript code
$(document).ready(function () {
$('#accordion').accordion();
});

And Finally here is my css for the elements shown:
.ui-accordion .ui-accordion-header {
display: block;
cursor: pointer;
position: relative;
margin-top: 2px;
padding: .5em .5em .5em .7em;
min-height: 0; /* support: IE7 */
}
.ui-accordion .ui-accordion-icons {
padding-left: 2.2em;
}
.ui-accordion .ui-accordion-noicons {
padding-left: .7em;
}
.ui-accordion .ui-accordion-icons .ui-accordion-icons {
padding-left: 2.2em;
}
.ui-accordion .ui-accordion-header .ui-accordion-header-icon {
position: absolute;
left: .5em;
top: 50%;
margin-top: -8px;
}
.ui-accordion .ui-accordion-content {
padding: 1em 2.2em;
border-top: 0;
overflow: auto;
}

Here is the jsFiddle example:
Please review and help me know how to get this collapsing and expanding.

A: your html markup is wrong check out http://jqueryui.com/accordion/ (view source)

Section 1

Section 1 body

Section 2

Section 2 body

you have an extra ul tag inside the main container
updated your fiddle

A: I had only one
* combination. I needed to put the a combination in each content div like so:

I have corrected it and you can see the updated fiddle here.


text:
Q: Button to save data from a result to a data table; user token required error I'm trying to add a button that takes data from a search results page and adds it to a data table. For example the first search result displays properly and I want the Favorites Button to save the data for the logged in user.
I keep getting the "message": "Token is Missing!" from the helper.py.
Fairly new to all this so I know I'm not using the best methods but at this point would just like to get this to work somewhat.
I'm guessing this is due to the @token_required. But I'm not sure how to fix this.
This is the route.
@api.route('/movies', methods = ['POST'])
@token_required
def save_movie(current_user_token):
    title = request.json['title']
    tmdb_id = request.json['tmdb_id']
    user_token = current_user_token.token

    print(f"User Token: {current_user_token.token}")

    movie = SaveMovie(title, tmdb_id, user_token=user_token)

    db.session.add(movie)
    db.session.commit()

    response = movie_schema.dump(movie)

    return jsonify(response)

and this is the form I'm using
            <form action="/api/movies" method="POST">
                <input type="hidden" name="title" value="{{ results.0.title }}"/>
                <input type="hidden" name="tmdb_id" value="{{ results.0.id }}"/>
                <input type="hidden" name="x-access-token" value="Bearer {{ current_user.token }}"/>
                <button name ="submit" class="btn btn-primary" type="submit">Favorite</button>
            </form>

This is the Model
class Movie:
    """
    Movie class to define Movie Objects
    """

    def __init__(self,id,title,overview,poster):
        self.id = id
        self.title = title
        self.overview = overview
        self.poster = f"https://image.tmdb.org/t/p/w500/{poster}"

And these are the functions
def search_movie(query):
    data = requests.get(f"{BASEURL}/search/movie?api_key={API_KEY}&language=en-US&query={query}&page=1&include_adult=false").json()
    if data['results']:
        search_data = process_results(data['results'])
    return search_data

def process_results(movie_list):
    movie_results = []
    for movie_item in movie_list:
        id = movie_item.get('id')
        title = movie_item.get('original_title')
        overview = movie_item.get('overview')
        poster = movie_item.get('poster_path')

        if poster:
            movie_object = Movie(id, title, overview, poster)
            movie_results.append(movie_object)

    return movie_results

I've attempted to add the token in the form to see if that would help but that didn't work and I'm not sure if maybe I need a @login-required for the search results but that would not be ideal. Would creating another function as a go between fix this?


text:
Q: How to properly inject dependency into Laravel artisan command? Basically I want to call a method on a repository Repository.php from a laravel command.
Example\Storage\Repository.php
Example\Storage\RepositoryInerface.php
Example\Storage\RepositoryServiceProvider.php

I expect Interface in the command constructor and then set it to the protected variable.
In the service provider I bind the Interface to Repository class.
Right now, in start/artisan.php I just write:
Artisan::add(new ExampleCommand(new Repository());

Can I use an interface here? What is the correct way? I am confused.
Thanks in advance.
EDIT: To clarify, it only works the way it is now, but I don't want to hardcode a concrete class while registering the artisan command.

A: You could use the automatic dependency injection capabiltiies of the IoC container:
Artisan::add(App::make('\Example\Commands\ExampleCommand'));
// or
Artisan::resolve('\Example\Commands\ExampleCommand');

If ExampleCommand's constructor accepts a concrete class as its parameter, then it'll be injected automatically. If it relies on the interface, you need to tell the IoC container to use a specific concrete class whenever the given interface is requested.
Concrete (ignoring namespaces for brevity):
class ExampleCommand ... {
    public function __construct(Repository $repo) {
    }
}

Artisan::resolve('ExampleCommand');

Interface (ignoring namespaces for brevity):
class ExampleCommand ... {
    public function __construct(RepositoryInterface $repo) {
    }
}

App::instance('RepositoryInterface', new Repository);
Artisan::resolve('ExampleCommand');

A: You may use the interface in the constructor to type hint the depended object but you have to bind the concrete class to the interface in the IoC container using something like following, so it'll work.
App::bind('Example\Storage\RepositoryInerface', 'Example\Storage\Repository');

Read more on the documentation.


text:
Q: Правильно ли построен код на OOP Начал учить ООП php и вроде написал код который работает, но на 100% уверен что с ним что-то не так, но что именно не пойму. Это мини система авторизации и регистрации.
Класс регистрации
    class Registeret{
    private $serverhost;
    private $servername;
    private $serverpass;
    private $serverdb;

    private $name;
    private $pass;
    public $submit;
    private $error;
    private $errorIsNan;

    function __construct($name,$pass,$submit)
    {
        $this->name = $name;
        $this->pass = $pass;
        $this->submit = $submit;
    }
    function getInfoPersion()
    {
        $this->serverhost = 'localhost';
        $this->servername = 'root';
        $this->serverpass = '';
        $this->serverdb = 'marlincraft';
        $this->error = "Такой пользователь уже найден, поменяйте свой логин!";
        $this->errorIsNan = "Введите данные в поле!";
        $this->newLogin();
    }
    function newLogin()
    {
        if (isset($this->submit)){
            if ((strlen($this->name) < 5 || strlen($this->pass) < 8) || (strlen($this->name) < 5 & strlen($this->pass) < 8))
            {
                $_SESSION['error'] = $this->errorIsNan;
            }
            else
            {
                $this->checkingname();
            }
        }
    }
    function checkingname()
    {
        $connect = new mysqli("$this->serverhost", "$this->servername", "$this->serverpass", "$this->serverdb");
        $result = $connect->query("SELECT login FROM users WHERE login = '$this->name'");
        $user = $result->fetch_assoc();
        if (count($user) == 0){
            $this->verefySend();
        }
            $_SESSION['error'] = $this->error;
    }

    function verefySend()
    {
        $connect = new mysqli("$this->serverhost", "$this->servername", "$this->serverpass", "$this->serverdb");
        if ($connect->query("INSERT INTO `users` (login,password,email,age) VALUE ('$this->name','$this->pass','asdsd','42')"))
        {
            header("Location: /");
        }
    }
}

А вот код авторизации
    class SignIn{
    private $login;
    private $password;
    private $submit;
    private $errorIsNan;

    function __construct($login,$password,$submit)
    {
        $this->login = $login;
        $this->password = $password;
        $this->submit = $submit;
    }
    function getInfoPersionSign()
    {
        $this->serverhost = 'localhost';
        $this->servername = 'root';
        $this->serverpass = '';
        $this->serverdb = 'marlincraft';
        $this->errors = "Такой пользователь не найден!";
        $this->errorIsNan = "Введите данные в поле!";
        $this->verefyInfoSign();
    }
    function verefyInfoSign()
    {
        if (isset($this->submit)) {
            if ($this->login == "" || $this->password == "") {
                $_SESSION['errors'] = $this->errorIsNan;
            }
        }
        $this->signIntoSystem();
    }
    function signIntoSystem()
    {
        if (isset($this->submit)) {
            $connect = new mysqli("$this->serverhost", "$this->servername", "$this->serverpass", "$this->serverdb");
            $result = $connect->query( "SELECT * FROM `users` WHERE login = '$this->login' AND password = '$this->password'");
            if ($result->num_rows == 1){
                $row_auth = $result->fetch_assoc();
                $_SESSION['persen'] = array($row_auth['id'], $row_auth['login'], $row_auth['password'], $row_auth['email'],$row_auth['age']);
                header("location: /");
            }
            $_SESSION['errors'] = $this->errors;
        }
    }
}

и создание экземпляров
    $conect = new Registeret($_POST['name'],$_POST['pass'],$_POST['sign-in']);
    $conect->getInfoPersion();

    $signIn = new SignIn($_POST['login'],$_POST['password'],$_POST['submit']);
    $signIn->getInfoPersionSign();

A: Все плохо... Дублирование, смешивание, инъекции...

*

*Работу с БД (подключение, получение данных, обновление, удаление) - в отдельный класс, с которым будете взаимодействовать в любых других.

*Регистрация, авторизация, подтверждение пароля, обновление данных пользователя (через ЛК), удаление ЛК - в единый класс

A: Ну. Хорошо что атрибуты объявлены как private, но почему     public $submit ? :)
Главная Ваша ошибка в том что Вы по-прежнему думаете в терминах действий, поэтому даже класс назвали SignIn, например, что является действием, а не объектом. У классов должны быть названия существительные. Например, User. Как с вещами в реальном мире, стол, стул, кружка, кнопка и т.п.
Вот я немного набросал более ООП кода. Я не PHP-программист, мог где-то ошибиться в чисто PHP-шных вещах
class User {
    private $connection;
    private $login;
    private $row;

    function __construct($c, $login, $row) {
        $this->connection = $c;
        $this->login = $login;
        $this->row = $row;
    }

    function attrs() {
        if (!isset($this->attrs)) {
            $result = $this->connection->query( "SELECT * FROM `users` WHERE login = '$this->login'");
            if ($result->num_rows == 0)
                throw new UserNotFound($this->login);
            $this->row = $result->fetch_assoc();
        }
        return array($this->row['id'], $this->row['login'], $this->row['password'], $this->row['email'],$this->row['age'])
    }
}

class UsersStorage {
    private $connection;

    function __construct($c) {
        $this->connection = $c;
    }

    function user($login) {
        $result = $this->connection->query( "SELECT * FROM `users` WHERE login = '$login'");
        if ($result->num_rows == 0)
            return array();
        return array(new User(#this->connection, $login, $result->fetch_assoc()));
    }

    function add($login, $attrs) {
        $this->connection->query("INSERT INTO `users` (login,password,email,age) VALUE ('$login','$attrs[2]','$attrs[3]','$attrs[4]')");
    }
}

// login handler

$c = new mysqli("localhost", "root", "", "db");
$storage = new UsersStorage($c);
$user = $storage.user($_POST['login'])
if (count($user) == 0) {
   // user not found, register first
}
else {
    $_SESSION['person'] = $user->attrs();
}

// register handler

$c = new mysqli("localhost", "root", "", "db");
$storage = new UsersStorage($c);
$user = $storage.user($_POST['login'])
if (count($user) == 0) {
   $storage->add($_POST['login'], array($_POST['login'], $_POST['password'], $_POST['email'], $_POST['age']))
    $_SESSION['person'] = $storage->user($_POST['login']);
}
else {
    // already exists case, choose another login
}


text:
Q: Proof that integral of uniformly convergent series converges to sum of the integrals I'm confused about the proof of a simple corollary.
We're given that if $f_n \to f$ uniformly then $$
\lim_{n \to \infty} \int_a^b f_n(x)\,dx = \int_a^b f(x)\,dx.
$$
As a corollary, my textbook considers the case that if

*

*the sums $\sum_{k=1}^n g_k(x)$ converge uniformly

*the $g_k$ are Riemann integral on $[a,b]$

then $$
\int_a^b \left(\sum_{k=1}^\infty g_k(x)\right)\,dx =
\sum_{k=1}^\infty \left(\int_a^b g_k(x)\,dx\right).
$$
The proof defines $f_n(x) \triangleq \sum_{k=1}^n g_k(x)$ and states that the conclusion follows from the given since $$
\int_a^b f_n(x)\,dx \to \int_a^b f(x)\,dx.
$$
This proof seems incomplete to me, however. How do we know that $$
\int_a^b f(x)\,dx = \sum_{k=1}^\infty \left(\int_a^b g_k(x)\,dx\right) \text{ ?}
$$

A: $$
\begin{align*}
\int_a^b \left(\sum_{k=1}^\infty g_k(x)\right)dx &=
\int_a^b f(x)dx \\
&= \lim_{n \to \infty} \int_a^b f_n(x)dx\\
&= \lim_{n \to \infty} \int_a^b \left(\sum_{k=1}^n g_k(x)\right)dx\\
&= \lim_{n \to \infty} \sum_{k=1}^n \left(\int_a^b g_k(x)dx\right)\\
&= \sum_{k=1}^\infty \left(\int_a^b g_k(x)dx\right)
\end{align*}
$$
--- rk

A: For each $n$, we have $$\int_a^b f_n(x)dx=\int_a^b \sum_{k=1}^n g_k(x)dx=\sum_{k=1}^n\int_a^b g_k(x)dx.$$  Now we take the limit as $n\to\infty$.  The limit of the left side of this equation is $\int_a^b f(x)dx$ and the limit of the right side is $\sum_{k=1}^\infty\int_a^b g_k(x)dx$, so those two must be equal.


text:
Q: Unable to load specific dll for plugin I'm currently using MEF to load plugins for one of my applications. I want to move these plugins outside of the bin directory to a separate plugins directory so other applications can use the plugins. A problem that I'm running into is that one of the plugins is dependent on a custom xml serializing class in a separate dll and when I try to use the particular plugin, I get a "Could not load file or assembly" error when it tries to load the separate dll.
My app.config currently has the following:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="plugins"/>
  </assemblyBinding>
</runtime>

I had to add probing in order of my original application to work with this particular dll. All plugin dlls were originally located in a subdirectory inside the bin called "plugins". But now that I want to move the plugins into a common directory for all applications, I would I go about fixing this issue? Any assistance would be greatly appreciated.

A: you have to ensure that all dependencies you need are in your catalogs.
at it have to look like something like that:
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory));//dependencies your plugin dll needs
catalog.Catalogs.Add(new DirectoryCatalog(@"YourPluginFolderPath\Plugins\"));//your plugin dll's

 var cc = new CompositionContainer(catalog);
 var t = cc.GetExport<IMyPluginTestStuffExport>().Value;


text:
Q: I am trying to enter the values in a array by for loop but loop is taking only one value and than program is closed I created an array of user-defined size and trying to enter the values but when for-loop is executed it is only taking one value
#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int s;
    cin>>s;
    vector <int> arr;
    int input;
    for(int i=0;i<s;i++)
       {cin>>input;
        arr[i]=input;}
       for(int i=0;i<s;i++)
        cout<<" "<<arr[i];
}

my input
5
1 2
expected input
5
1 2 3 4 5
output
program crashed after entering the value 1
expected output
1 2 3 4 5


text:
Q: Chrome Apps Open one Page into another Page I am developing app for chrome apps in HTML5
My problem is: I have to open another page on clicking the link
anchor tag () is also not working
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Hello World</title>
    <link href="styles/main.css" rel="stylesheet">

Hello, World!

    Click Me

background.js:
chrome.app.runtime.onLaunched.addListener(function() {

  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 500;
  var height = 300;

  chrome.app.window.create('index.html', {
    id: "helloWorldID",
    bounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2)
    },
  });
});

How to open page1.html with a link from the app window?

A: There are a few ways to create new windows in a Chrome App. First is simply window.open, which is what you'd do for normal web content (i.e., stuff you'd open in a normal browser tab). This works much like a native app opening a browser window using whatever application is registered to handle .html file extensions, which is to say it'll open the web content in the user's default browser.
Next is the very same chrome.app.window.create that you used to create your app's initial window. So set a listener on the link or button you want to initiate the opening of the new window, and put the create() call in there. This is what you'd want in your case, because you're not trying to display regular web content but rather are showing HTML that's embedded in your app.
Finally, if you want window.open behavior but need to know it'll open in Chrome in the same profile as the app, see chrome.browser.openTab, whose progress you can follow at https://code.google.com/p/chromium/issues/detail?id=358315. (Update: I just spoke with rpaquay who says this API is live in dev channel.)
For completeness, I should also mention normal web content in a Chrome App window, for which you want <webview>, or else packaged/embedded resources in a <webview>, which require webview:partitions:accessible_resources (see codereview.chromium.org/308903002 for details). I don't think that last part is live yet, so the names might change.


text:
Q: gcc's extended initializer lists warning gcc will warn about the following example code:
struct someStruct {
    char c;
    int i;
};

int main() {
    someStruct s { 'a', 3 };

    return 0;
}

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I want to make my code compatible to older compilers having no C++11 support.
Now when I try to compile it with either -std=c++98 or even -ansi -pedantic it still issues the same warning and compiles.
Is this a compiler bug or am I missing something?

A: You're missing an =:
someStruct s = { 'a', 3 };


text:
Q: Setting Windows Permissions with Python I want to give a user only read access to a folder (a geodatabase) using Python. When I set the permissions manually through file explorer they work correctly. When using win32security and ntsecuritycon to set the permissions through Python I am able to give a user (myself) full control. However, when trying to give only read access to another user they are either not able to view the folder's contents, or are unable to even open the folder.
In both cases, whether the read permissions are set manually or with Python, I see the same permissions checked off in the "Permissions Entry for Folder_Name" window (navigated to by: right folder -> Properties -> Advanced -> Select user from list -> Edit). There is one difference between these two methods that I noticed; under the "folder_name" properties window there is a section that is titled Permissions for "User/Group_name". In this section there is a list of permissions with an associated allow and deny column; this is where the difference is. If the permissions are done manually then there will be a check for the "Read" row in the "Allow" column. If the permissions set with Python there will instead be a check for the "Special permissions" in the "Allow" column. I know don't if this is the issue, but I can't find any other difference between the two methods.
Here is the code I am using
`
def set_permissions(filefolderlist, readlist, authlist):
import sys
import win32security
import ntsecuritycon as con

for filefolderpath in filefolderlist:

    sd = win32security.GetFileSecurity(
        filefolderpath, win32security.DACL_SECURITY_INFORMATION
    )

    dacl = win32security.ACL()

    sysadmins, domain, type = win32security.LookupAccountName("", "SYSTEM")
    admins, domain, type = win32security.LookupAccountName("", "Administrators")
    user, domain, type = win32security.LookupAccountName("", read_user)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, sysadmins)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins)
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.GENERIC_READ, user)

    for auth_user in authlist:
        user, domain, type = win32security.LookupAccountName("", auth_user)
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user)

            sd.SetSecurityDescriptorDacl(1, dacl, 0)
    win32security.SetFileSecurity(
        filefolderpath, win32security.DACL_SECURITY_INFORMATION, sd
    )

set_permissions(folder_list,read_user,user_list)`


text:
Q: Click on Bar chart (text written on the chart ) doesnot work using Selenium I am automating an application built on HTML5 using Selenium with Python XML source behind:
<g class="enteringBarsGroup" transform="translate(0, 3.42308)">
<rect id="idx9-2011" class="bar" style="fill: rgb(107, 158, 226); pointer-events:      auto;" width="321" name="2011" title="2011: 136" height="13.692307692307692" rx="3" pointer-events="none" opacity="0.8" isMouseOver="false">
<text class="labelshadow" x="0" dx="10" y="6.846153846153846" dominant-baseline="middle" pointer-events="none">2011</text>
<text class="label" x="0" dx="10" y="6.846153846153846" dominant-baseline="middle" pointer-events="none">2011</text>
</g>

The page has Bar graphs and Pie charts. When I click on a value of bar chart, the resulting values on the other charts change.
This is my test scenario. I am unable to click on the bar chart. I have tried the options below
 #self.browser.find_element_by_id("idx9-2011").click()

and
 #self.browser.find_element(BY.NAME,"2011").click()

A: Firstly, you should rule out this issue (if you are using IE, you need to set zoom level to 100%).
Also, the other solutions on that page are worth trying too, e.g.,
self.browser.find_element_by_id("idx9-2011");
self.browser.execute_script("arguments[0].fireEvent('onclick');");

Sometimes it is not the click() which fires the event.  Have you tried, for instance issuing a mouse_down() followed by a mouse_up().  I'm not sure how to achieve this in Python, but you'd have to use the advanced user interactions.
In general with problems where Selenium has difficulty triggering a UI event, it is sometimes easier to find a solution using the Firefox Selenium IDE plugin and then transfer the solution to WebDriver.


text:
Q: Using Tally for computed list of values I'm trying to use Tally to count the duplicated values in a list resulting from solving a linear system
list={{0.300823},{0.121771},{0.258845},{0.0518388},{0.0255293},{0.0440367},{0.238642},{0.106291},{0.258845},{0.0376355},{0.194645},{0.121771},{0.106291},{0.0557113},{0.0440367},{0.0129854},{0.0255293},{0.0518388},{0.0376355},{0.0557113}};

Tally[list]//MatrixForm

Here is what I got

It seems that Tally sees the extended values not the approximated ones.

A: The issue is that the data in the OP's kernel has more significant digits than what we have on the question, so for that kernel two numbers that in the question appear as identical are internally different.
Anyhow, the question is ill-defined unless we define what two numbers count as the same. So we necessarily need to coarse-grain the data or provide an explicit test.
Done in Wolfram Cloud, given that the OP commented to be working "online".
$Version
(* 13.2.0 for Linux x86 (64-bit) (December 12, 2022) *)

list={
    {0.300823},{0.121771},{0.258845},{0.0518388},
    {0.0255293},{0.0440367},{0.238642},{0.106291},
    {0.258845},{0.0376355},{0.194645},{0.121771},
    {0.106291},{0.0557113},{0.0440367},{0.0129854},
    {0.0255293},{0.0518388},{0.0376355},{0.0557113}
};

Here I Round to $0.001$.
Tally[Round[list,0.001]]//MatrixForm

Alternatively another sameness test needs to be defined in Tally[data, test]

Tally[list,(Abs[First[#1-#2]]<1/1000)&]//TableForm


text:
Q: htaccess and https/non-www to https/www I know there are many posts on redirects, and I've read a lot of them now, but only a few that I've found seem to touch on what I need and often seem to contain conflicting information
I need to get:
http://example.com -> https://www.example.com
http://www.example.com -> https://www.example.com

and more importantly:
https://example.com -> https://www.example.com

I can find many solutions to the first two. Like this one:
#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

or this one:
RewriteEngine on

RewriteCond %{REQUEST_SCHEME} http [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

These rules look like what I should be after, but I've only got a certificate that covers https://www.example.com. Is the third redirect possible? (https://example.com to https://www.example.com). The answers in the question I linked seem to suggest it might be possible without another certificate, but there's disagreement.
I would have thought that there's no way around the problem, but I'm hoping there can be and would appreciate input.
*edit: if I don't get a certificate for https://example.com, it won't be classed as a duplicate by search engines will it?

A: To do a redirect between subdomains (* -> www), you need a certificate for each domain that runs https, or you need a wildcard certificate that handles them all.
The redirect is a completely separate issue.
Once you get a valid connection, you can redirect or not.
If the connection isn't valid (wrong/missing ssl cert), the redirect will never happen.


text:
Q: Confused about terminology and concepts used in IIS I am a little confused about some basic concepts about Microsoft IIS 7 (Internet Information Services). Could anyone give me concise definitions on the following terms:

*

*Host

*Site

*Web Application

*Virtual Directory

*Application Pool

Especially: what's the difference between Site, Web Application and Virtual Directory?
Update - 1 - 8:49 AM 12/20/2010
A related topic: Difference between web site and web application

A: Some "quick and dirty" answers:
Host: The machine that is hosting IIS (can be a physical machine or a virtual machine).
Site: A website that is not the child of another site.
Web Application: A website.  Usually if they are referred to as "web applications" then they are very data driven and it is not a static site.
Application Directory:  Essentially a child website.  It can have its own application pool, but settings can also be inherited from the parent website (HTTP handlers and HTTP modules for example).  You didn't specifically ask about this one, but I added it as it may have been what you meant by "Web Application".
Virtual Directory:  A directory of a website that has a physical location that is different than the website itself.  One common use for this is to have a web farm, but some of the content is located on a shared resource (such as a SAN or NAS).  This prevents the need of replicating files between all servers of a web farm.  There are other purposes of a virtual directory, but this is the main reason I've used them in the past.
Application Pool:  The process that a .NET application runs as.  This may be used by things over than .NET, but that's the only piece I know that currently uses application pools.  Essentially this holds the user and other information that the .NET application runs under.  For instance, if you are using a trusted connection to SQL Server (SSPI), then by default, the user it will connect to the database as the user that this process is running as (unless you have impersonation in the web application set).  This is also the user that will be used if the web application accesses system resources.


text:
Q: How to set custom loglevel in winston using typescript? i have declared LogLevel in enum, winston is throwing an error. so what should be the type of levels ?
logger.ts
enum LogLevel {
  trace,
  debug,
  info,
  warn,
  error
}

const logConfig = {
  format: _format.json(),
  levels: LogLevel,
  transports: [
    new _transports.Console()
  ]

const logger =  createLogger(logConfig);

error
Argument of type '{ format: Format; levels: typeof LogLevel; level: string; transports: _transports.ConsoleTransportInstance[]; }' is not assignable to parameter of type 'LoggerOptions'.
  Types of property 'levels' are incompatible.
    Type 'typeof LogLevel' is not assignable to type 'AbstractConfigSetLevels'.
      Index signatures are incompatible.
        Type 'string' is not assignable to type 'number'.ts(2345)

A: SOLUTION
Instead of passing enum directly to levels define a const in key-value pair as shown in _logLevel.
enum LogLevel {
  trace,
  debug,
  info,
  warn,
  error
}

const _logLevel = {
  error: LogLevel.Error,
  warn: LogLevel.Warn,
  info: LogLevel.Info,
  debug: LogLevel.Debug,
  trace: LogLevel.Trace
};

const logConfig = {
  format: _format.json(),
  levels: _logLevel,
  transports: [
    new _transports.Console()
  ]

const logger =  createLogger(logConfig);


text:
Q: Use cout or cerr to output to console after it has been redirected to file Redirecting cout or cerr to a file is easy enough. I can use this to redirect third party output to a file. However, after I have redirected the third party output to a file, how do I then use cout myself to output to the console?

A: You save the buffer and restore it later:
std::streambuf *buf = std::cout.rdbuf(); //save
// Do other stuff
std::cout.rdbuf(buf); // restore

A: I'm a great fan of RAII, so I once wrote this small helper class. It will redirect the stream until it goes out of scope, at which point it restores the original buffer. Quite handy. :)
class StreamRedirector {
public:
    explicit StreamRedirector(std::ios& stream, std::streambuf* newBuf) :
        savedBuf_(stream.rdbuf()), stream_(stream)
    {
        stream_.rdbuf(newBuf);
    }

    ~StreamRedirector() {
        stream_.rdbuf(savedBuf_);
    }

private:
    std::streambuf* savedBuf_;
    std::ios& stream_;
};

Can be used like this:
using namespace std;
cout << "Hello stdout" << endl;
{
    ofstream logFile("log.txt");
    StreamRedirector redirect(cout, logFile.rdbuf());
    cout << "In log file" << endl;
}
cout << "Back to stdout" << endl;


text:
Q: Android - ClassNotFoundException (TwitterAPI) Okay so I've been messing around with the Twitter API, and all of a sudden I've started to get the ClassNotFoundException error code when I try and enter the Activity which has my login box to sign into Twitter.
Here's the error code.
2398-2398/josh.com.twitterapi E/dalvikvm﹕ Could not find class 'josh.com.twitterapi.LoginActivity', referenced from method josh.com.twitterapi.NavigationDrawerFragment.selectItem
07-05 02:19:30.138    2398-2398/josh.com.twitterapi E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: josh.com.twitterapi.LoginActivity
        at josh.com.twitterapi.NavigationDrawerFragment.selectItem(NavigationDrawerFragment.java:204)
        at josh.com.twitterapi.NavigationDrawerFragment.access$000(NavigationDrawerFragment.java:32)
        at josh.com.twitterapi.NavigationDrawerFragment$1.onItemClick(NavigationDrawerFragment.java:99)
        at android.widget.AdapterView.performItemClick(AdapterView.java:301)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1280)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3071)
        at android.widget.AbsListView$1.run(AbsListView.java:3973)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4867)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
        at dalvik.system.NativeStart.main(Native Method)
07-05 02:21:03.973    3223-3223/josh.com.twitterapi E/dalvikvm﹕ Could not find class 'josh.com.twitterapi.LoginActivity', referenced from method josh.com.twitterapi.NavigationDrawerFragment.selectItem

This is my LoginActivity.java.
        package josh.com.socialme;

    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;

    import com.codepath.oauth.OAuthLoginActivity;

    public class LoginActivity extends OAuthLoginActivity<TwitterClient> {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
        }

        // Inflate the menu; this adds items to the action bar if it is present.
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.login, menu);
            return true;
        }

        // OAuth authenticated successfully, launch primary authenticated activity
        // i.e Display application "homepage"
        @Override
        public void onLoginSuccess() {
            // Intent i = new Intent(this, PhotosActivity.class);
            // startActivity(i);
        }

        // OAuth authentication flow failed, handle the error
        // i.e Display an error dialog or toast
        @Override
        public void onLoginFailure(Exception e) {
            e.printStackTrace();
        }

        // Click handler method for the button used to start OAuth flow
        // Uses the client to initiate OAuth authorization
        // This should be tied to a button used to login
        public void loginToRest(View view) {
            getClient().connect();
        }

    }

This is my AndroidManifest.

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="josh.com.socialme" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity
            android:name=".Hub"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Feed"
            android:label="@string/title_activity_feed" >
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name" >

            </activity>
    </application>

</manifest>

And this is my method I use to get to the activity.
    private void selectItem(int position) {
    // Handle Navigation Options
    Intent intent;
    switch (position) {
        case 1:
            intent = new Intent(getActivity(), Feed.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            getActivity().startActivity(intent);
            break;
        case 2:
            intent = new Intent(getActivity(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            getActivity().startActivity(intent);
            break;

    }

}

I would greatly appreciate it if someone could point me towards the right direction.
Kind regards,
Josh
(AndroidManifest.xml as requested)
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="josh.com.socialme" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity
            android:name=".Hub"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Feed"
            android:label="@string/title_activity_feed" >
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="@string/title_login_activity" >

            </activity>
    </application>

</manifest>


text:
Q: Using Natsort Correctly I made this small script to extract names of photos from a directory.
<?php
$dirname = "newspaper_articles/nameofperson/1951-1977/";
$articlepath = glob($dirname."*.jpg");
foreach ($articlepath as $article) {
echo basename($article,".jpg").'<br>';
}
?>

The photos in the directory are named like this;
1 articletitle.jpg
2 articletitle.jpg
11 articletitle.jpg
12 articletitle.jpg
21 articletitle.jpg
22 articletitle.jpg
(Notice the sequence. I wanted php to display it on the page like that)
However my code renders it like this;
1 articletitle.jpg
11 articletitle.jpg
12 articletitle.jpg
2 articletitle.jpg
21 articletitle.jpg
22 articletitle.jpg
What I understand from PHP Manual is that I should use natsort. I'm doing it like this:
foreach ($articlepath as natsort($article))

I get an error (Warning: natsort() expects parameter 1 to be array)
What would be your take on why this doesn't work

A: If $articlepath is array, do this way:
natsort($articlepath)
foreach ($articlepath as $article) {

Your problems is that you are trying to sort single element of array represented as a string but natsort only works with arrays.

A: Are you sure you want to perform natsort on every element of array?
You mean:
natsort($articlepath)
foreach ($articlepath as $article)


text:
Q: I am trying to execute this code in console - it was throwing this error message "expecting a semi-colon, found 'newAlloc.add" String strReleaseId = 'a0CR0000003Ayaa';
String approvedUltId = 'a0JR0000004bWUK'; //supposed to be rejected.
String titleId = 'a0HR0000006YLaj'; //Title ID

//Fetch RecordType
RecordType rt = [Select SobjectType, Name, Id From RecordType WHERE SobjectType = 'Ultimate__c' and Name = '2) Budget'];

//Get Release Information
Release__c r = [Select release_date_reached__c,Id,Name,OwnerId,Territory__c,
                Territory__r.Region__c,Stage_GreenLight__c,Stage_Budget__c,Stage_Pre_Release__c,
                Stage_Post_Release__c, Ultimate_Due_Date__c
                from Release__c
                where Id = :strReleaseId];

//Create Ultimate
Ultimate__c ult = new Ultimate__c();
ult.Ultimate_Date__c=System.today();
ult.OwnerId=r.OwnerId;
ult.Title_Id__c=titleId;
ult.Status__c='Draft';
ult.Release__c=r.Id;
ult.Territory__c=r.Territory__c;
ult.RecordTypeId = rt.Id;
insert ult;

//Clone Allocations and Insert
list<Allocation__c> newAlloc = new list<Allocation__c>();
list<Allocation__c> lstAlloc = [Select Type__c, Type__r.Name, Title__c, Territory__c, Stage__c, Release__c,
                                        Amount__c, Amount_Low__c, Amount_High__c, Amount_Cons__c
                                From Allocation__c WHERE Ultimate__c = :approvedUltId];
for(Allocation__c alloc : lstAlloc) {
    Allocation__c cloneAlloc = new Allocation__c();
    cloneAlloc.Type__c = alloc.Type__c;
    cloneAlloc.Title__c = alloc.Title__c;
    cloneAlloc.Release__c = alloc.Release__c;
    cloneAlloc.Amount__c = alloc.Amount__c;
    cloneAlloc.Amount_Low__c = alloc.Amount_Low__c;
    cloneAlloc.Amount_High__c = alloc.Amount_High__c;
    cloneAlloc.Ultimate__c = ult.Id;
    cloneAlloc.Stage__c = alloc.Stage__c
    newAlloc.add(cloneAlloc);
}

if(newAlloc.size() > 0) {
    insert newAlloc;
}

A: So the message implies that a semi-colon is missing just before newAlloc.add(cloneAlloc); i.e. on the end of the cloneAlloc.Stage__c = alloc.Stage__c statement which a visual inspection shows it is.


text:
Q: About a metric's symmetric properties... Hello fellow mathematicians!
I was wondering why most metrics I have seen in Relativity are symmetric, also a property I have started to notice in my differential geometry book.
I guess the definition through the "dot-product" may be the reason why...
$$ g_{\alpha \beta}=\vec{x}_\alpha\cdot \vec{x}_\beta  $$
But:

*

*Are there non-symmetric metrics?

*What can be said about them?

*Also, how do we call those metrics which only have non-zero components in the main diagonal?

*And perhaps the question that has been bothering me a lot: What can be said about a metric having non-zero components out off the main diagonal?
I have been having thoughts on physical implications but since I'm not that far into Relativity nor Diff. Geometry, I can't really come up with something yet.
My main book has been Kreysizg's Differential Geometry, which may not be suited for some questions I have been thinking off, yet it has been an awesome book to start with! Any further recommendations?

A: You usually want a metric to "measure" distance in some way.  One property we want to be preserved is that the distance from A to B is the same as the distance from B to A.  This property is exactly what symmetry in the form means.  So if a metric is not symmetric then it doesn't really do anything useful.


text:
Q: Unable to get File Name from Content-Disposition I am working on 'REST Client' which calls a REST webservices and get file name in Content-Disposition header as attachment; filename*=utf-8''20200217_152840.jpg
I have written following code but its not returning the filename
 using System.Net.Mime;
 using System.Web;

 HttpWebResponse response = (HttpWebResponse) Req.GetResponse();
 string filenameheader = (response.Headers["Content-Disposition"]);
 ContentDisposition contentDisposition = new ContentDisposition(filenameheader);
 string filename = contentDisposition.FileName;

This code was working previously when response header was like attachment; filename='20200217_152840.jpg

A: If you are using .Net Core REST API for file upload, you can use this code:
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.ToString();
}

Another way to do this:
[HttpPost]
public async Task<IActionResult> UploadFile()
{
    var files = Request.Form.Files;

    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.ToString();
}

You can refer this for more details on different ways of file uploading:
Upload files in ASP.NET Core


text:
Q: Find String in Multidimensional ArrayList Scenario
I've got an ArrayList<[String, String, String, String]> to store data.
Now I'm trying to check if the ArrayList contains String.
for(String i : checkArtefakts){
            System.out.println(i);
            if(headerAndBodyTestSuites.toString().contains(i)){
                System.out.println(i + "  " + headerAndBodyTestSuites.indexOf(headerAndBodyTestSuites.contains(i)));
            }
        }

I've implemented a toString() Method but it also didn't solve my problem.
Question
How can I check each Element of ArrayList ([String,String,String,String])
if it contains my search String.
And why wouldn't it even find it in my toString() method?
public String toString() {
    return "[XQ: " + xqueryFileName + "] [Path: " + testDir + "] [INP: " + firstInputFile
        + "] [INP: " + secondInputFile + "] [EXP: " + expectedFile + "]";

}

Example
ArrayList<HeaderAndBodyTestcase> where HeaderAndBodyTestcase =
public HeaderAndBodyTestcase(final String xqueryFileName, final String testDir,
        final String firstInputFile, final String secondInputFile, final String expectedFile)

A: If you were using List<String[]> you can use Arrays.asList(), to check if the String[] contains your string with .contains() method.
But in your case it's a List of HeaderAndBodyTestcase, so you need to implement a contains method in your HeaderAndBodyTestcase class to check if any of the class members is equal to the searched String.
This is how should be your code:
public boolean contains(String search){
    return this.xqueryFileName.equals(search) || this.testDir.equals(serach) || this.firstInputFile.equals(search) || this.secondInputFile.equals(search) || this.expectedFile.equals(search);
}

A: You need to implement a method in the class which will look if the search String is one of the attribute :
public boolean objectContainString(String search) {
     return Arrays.asList(xqueryFileName, testDir, firstInputFile, secondInputFile, expectedFile)
                  .contains(search);
}

And use like this :  boolean bool = list.stream().anyMatch(e -> e.objectContainString(search));

A: You can do something simple as this:
    String searchedString = "SomeString";
    boolean found = false;
    for(String string : arrayList) {
          if (searchedString.equals(string)){
              found = true;
          }
    }

Or you could use the java stream API. (Requires Java 8)
    List<String> list = new ArrayList<>();
    list.add("SOME_STRING_1");
    list.add("SOME_STRING_2");
    list.add("SOME_STRING_3");
    String searchString = "SOME_STRING...";
    if(list.stream().anyMatch((string)->string.equals(searchString))) {
        // The string was in the list
    } else {
        // The string was not in the list
    }

Where arrayList contains your strings. Im not sure what you meant by ArrayList<[String, String, String, String]>, but this might be what you are looking for.