text:
Q: How to Call to a UI variable of JavaFX from javascript in WebEngine? I'm working on an application that needs to read a local file and display it in WebView, based on user input (in ComboBox).
I'm trying to call to a variable in the JavaFX UI from JavaScript and it doesn't work.
I created a function called getMonthIndex() in the Java code that returns the input of the ComboBox and that the file should be received with the appropriate name.
I'm trying to import this function into the JavaScript code, and it doesn't seem to be included in the JavaScript code.
If you can explain to me how to get a parameter from the JavaFX UI and use it within the JavaScript code.
Thanks so much in advance for any help you can.
My Controller.java:
public class Controller {

    ObservableList<String> months = FXCollections.observableArrayList
                    ("Tishrei", "Cheshvan", "Kislev", "Tevet", "Shevat", "Adar",
                    "Nisan", "Iyar", "Sivan", "Tammuz", "Av", "Elul");

    public ComboBox<String> month;
    public WebView webView;

    public String getMonthIndex() {
        ReadOnlyIntegerProperty listIndex = month.getSelectionModel().selectedIndexProperty();
        return String.format("%02d", listIndex.getValue());
    }

    public long linesCount(String scanFile) {
        if (scanFile.length() < 80) {
            return scanFile.length() / 15;
        } else {
            return scanFile.length() / 24;
        }
    }

    @FXML
    public void initialize() {
        month.setItems(months);

        webView.setContextMenuEnabled(false);

        WebEngine webEngine = webView.getEngine();
        Controller controller = new Controller();
        JSObject win = (JSObject) webEngine.executeScript("window");
        win.setMember("app", controller);

        month.setOnAction(event -> {
            String loadFile = this.getClass().getResource("index.html").toString();
            webEngine.load(loadFile);
        });
    }
}

My index.html (uploaded by WebEngine):

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css">

A: You're creating a new instance of the Controller, which has no connection at all to the UI, and passing it to the web engine:
    Controller controller = new Controller();
     JSObject win = (JSObject) webEngine.executeScript("window");
    win.setMember("app", controller);

Instead, just pass the current instance:
    // Controller controller = new Controller();
    JSObject win = (JSObject) webEngine.executeScript("window");
    win.setMember("app", this);


text:
Q: how to use key that is stored in localstorage of addon/extension in firefox/chrome browser for web apps My question might be bit consfusing but ill try to explain as simple as i can
lets say my Addon is having a particular key value pair
where i can use that key and its value in my addon/chrome itself no doubt about it
but is there any way where i can get  the localstorage key value pairs of my addon and use them in my
browser
in simpler terms if i have a key/value pair in addon and i want to use the same key value pair in my angular application
lets say
localstorage.getitem('key')
in my angular application should yield the value of that particular key stored in my addon

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constructing new lists using Table I tried to modify an old notebook to show a spreadsheet style output in a table.  I am not getting any errors when it runs, so I think the data I am gathering and the new variables I added, t and y, are there correctly.  I removed the colored aspect to try and simplify things.  I get lost when I try to add data to the list2 variable.  Can anyone help me get this to work properly?
stock = {"AAPL", "FB", "BAC", "TWTR", "IBM"};
stocks = {"AAPL", "FB", "BAC", "TWTR", "IBM"};
fields = {"Close", "5ema", "5ema[1]"};
tablefillnew[stock_] :=
 (list = {data =
       FinancialData[#, "Close", {{DatePlus[-60], DatePlus[-1]}}];
      FinancialData[#, "Close"],
      ema = FinancialIndicator["ExponentialMovingAverage", 5] #;
      t = Take[ema, {1}]; y = Take[ema {2}];} & /@ stock;
  list2 = Table[{colored[[ii]], list[[ii, 2]]}, {ii, 1, Length[list]}];
  TableForm[list2, TableHeadings -> {stocks, fields}
   ])
tablefillnew[stock]

A: There are a lot of syntax errors and general messiness in this code. My proxy server won't let me download FinancialData at the moment, so I can't test this completely, but several things you should note:

*

*intermediate variables should localised using Module.

*syntax error: y = Take[ema {2}] should be y = Take[ema, {2}]  or just ema[[2]].

*FinancialIndicator["ExponentialMovingAverage", 5] #; doesn't work that way - it works inside things like TradingChart. You are better off just using the built-in ExponentialMovingAverage, after stripping off the dates.

*it's no wonder you are confused with all the definitions inside definitions. Try making your code a bit less nested.

*there seems to have been unnecessarily doubled braces in the definition of data

*without knowing what coloured did, it is hard to work out what to replace it with.

Here is a simplified version that should work. Notice that I have made fields a parameter so you can change your preferred functions. I have used pattern matching to check that the data you pass to the function are what you expect (lists of strings). I have used Part ([[]]) instead of Take to simplify getting the bits of the exponential moving average.  And instead of building up the table row by row using Table, I just use Transpose.
tablefillnew[stocklist:{__String}, fields:{__String}] :=
 Module[{data, ema, closeprices},
  data = FinancialData[#, "Close", {DatePlus[-60], DatePlus[-1]}] & /@ stocklist;
  closeprices = FinancialData[#, "Close"] & /@ stocklist;
(* latest close not close for previous day:  they could be different *)
  ema = ExponentialMovingAverage[#[[All, 2]], 5] & /@ data;
  TableForm[Transpose[{closeprices, ema[[All, 1]], ema[[All, 2]]}],
   TableHeadings -> {stocklist, fields}]]


text:
Q: Adobe Air/Flex + SQLite database problem I'm still a newbie to Adobe Air/Flex, and still fairly new with SQL.
I've downloaded this (http://coenraets.org/blog/2008/11/using-the-sqlite-database-access-api-in-air…-part-1/) code and have been looking over it and I'm trying to implement the same idea.
I think it's just something stupid. I'm using Flex Builder. I made a new desktop application project, didn't import anything.
I added a DataGrid object and bound it to an ArrayCollection:
I'm trying to make it so when the program initializes it will load data from a database if it exists, otherwise it'll create a new one.
The problem is, when the application runs, the datagrid is empty. No column headers, no data, nothing. I've tried changing a whole bunch of stuff, I've used the debugger to make sure all the functions are being called like they're supposed to. I don't know what I'm doing wrong. I've compared my code to the before mentioned code, I've looked for tutorials on Google. Anyone know what I'm doing wrong?
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="672" height="446"
    applicationComplete="onFormLoaded()"
    title="iRecipes">

    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;

            private var sqlConnection:SQLConnection;
            [Bindable] private var recipeList:ArrayCollection;

            private function onFormLoaded():void
            {
                sqlConnection = new SQLConnection();
                openDataBase();
            }

            private function openDataBase():void
            {
                var file:File = File.userDirectory.resolvePath("recipes.db");

                sqlConnection.open(file, SQLMode.CREATE);

                if(!file.exists)
                {
                    createDatabase();
                }

                populateRecipeList()
            }

            private function createDatabase():void
            {
                var statement:SQLStatement = new SQLStatement();
                statement.sqlConnection = sqlConnection;
                statement.text = "CREATE TABLE Recipes (recipeId INTEGER PRIMARY KEY AUTOINCREMENT, recipeName TEXT, authorName TEXT)";
                statement.execute();

                statement.text = "INSERT INTO Recipes (recipeName, authorName) VALUES (:recipeName, :authorName)";

                statement.parameters[":recipeName"] = "Soup";
                statement.parameters[":authorName"] = "Joel Johnson";
                statement.execute();

                statement.parameters[":recipeName"] = "Garbage";
                statement.parameters[":authorName"] = "Bob Vila";
                statement.execute();
            }

            private function populateRecipeList():void
            {
                var statement:SQLStatement = new SQLStatement();
                statement.sqlConnection = sqlConnection;

                statement.text = "SELECT * FROM Recipes";
                statement.execute();
                recipeList = new ArrayCollection(statement.getResult().data);
            }
        ]]>
    </mx:Script>

    <mx:DataGrid dataProvider="{recipeList}">

    </mx:DataGrid>
</mx:WindowedApplication>

A: I just tried this out using your code. I made a change and removed the condition as I was getting errors about the table not existing.
 //if(!file.exists)
 //{
   createDatabase();
 //}

This got the datagrid showing the correct info. I think that there is something wrong with the way you are initialising the database file. I'm having a look into it at the moment.
Try using
sqlConnection.open(file, SQLMode.CREATE);

instead, for opening the database.

A: Thanks Feet. With your suggestion, I believe I have figured it out. I changed the if statement to this:
            if(!file.exists)
            {
                sqlConnection.open(file, SQLMode.CREATE);
                createDatabase();
            }
            else
            {
                sqlConnection.open(file, SQLMode.UPDATE);
            }

And it works great. Thanks for your help.


text: Q: ¿Como puedo relacionar 2 tablas que son (Artist y Genre) en MERN Stack desde backend? //lo que quiero hacer es que desde el formulario pueda ingresar el Name del Artist y su Genre, que genre con un list group desplegue el nombre de los Genres no sus _id y al selecionar un Genre que guarde su _id respectivo en la base de datos MongoDB junto con el name del Artits


text:
Q: I am trying to implement refreshCountryList , which should return countryList(array of objects) variable which contains all countries Country.component.ts
 countryList :any;
  searchvalue : string = "" ;

  constructor( private service : SharedService) { }

  ngOnInit(): void {
    this.refreshCountryList();
  }

  refreshCountryList(){
    this.service.getCountryList().subscribe(data=>{ this.countryList = data
      console.log("countryList inside subscribe :",this.countryList ) ;
    });
    console.log( "list outside subscribe :" , this.countryList);
  }

shared.service.ts
export class SharedService {

  readonly APIUrl = "https://localhost:44383/api/CountryApi/";

  constructor(private http: HttpClient) { }

  getCountryList(){
    return this.http.get(this.APIUrl + 'listcountry');
  }

}

I couldn't get countryList value outside the subscribe, the scope resides only inside subscribe.
What can I do for getting the Value outside subscribe?

A: Angular synchronously executes the code. subscribe() actually gets executed at the last after the execution of all synchronous codes. So this line gets executed first before subscribe is called.
console.log( "list outside subscribe :" , this.countryList);

However, if you just want to see the output you can put a JSON pipe on the HTML side and see it in the view.
<pre> <div [innerHTML]="this.countryList | json"></div> >/pre>

Another method is to store the data and call a method to check if data is available which in turn can be used to put logic in it.
countryList :any;
searchvalue : string = "" ;

constructor( private service : SharedService) { }

ngOnInit(): void {
  this.refreshCountryList();
}

mapData(){
  console.log(this.countryList);
}

refreshCountryList(){
  this.service.getCountryList().subscribe((data)=>{
    if(!data) return;
    this.countryList = data;
    console.log("countryList inside subscribe :",this.countryList ) ;
    this.mapData();
  });
  console.log( "list outside subscribe :" , this.countryList);
}


text:
Q: propiedad de objeto indefinida en angular 8 tengo el siguiente problema y no hallo la forma de resolverlo. Tengo una interfaz, luego la importo e inicializo en un componente , pero cuándo intento asignar un valor a una de sus propiedades me dice que no está definida, cuál es el error? gracias de antemano al que me pueda ayudar con este problema.
dejo el código:
este es el componente padre

  //para los textos
  textsPag1= {} as Texts;
  textsPag2= {} as Text;

  @ViewChild(PortadaComponent) coverPage: PortadaComponent;
  @ViewChild(Pag1Component) page1: Pag1Component;

  //Se subscribe a las imagenes de todas las paginas

  constructor(
    private uploadImgsService: UploadImagesService,
    private usuarioService: UsuarioService,
    private productosService: ProductosService,
    private ngZone: NgZone, private router: Router,
    private dialog:MatDialog,
    private snackBar: SnackBar

   ){
    // this.textsPag1.pag1Texts.text1= 'b'
    // this.textsPag1.pag1Texts.text2= 'b'
    // this.textsPag1.pag1Texts.text3= 'b'
    // this.textsPag1.pag1Texts.text4= 'b'
    // this.textsPag1.pag1Texts.text5= 'b'

acá llamo al hijo y le paso la variable textsPag1:

        <app-portada [coverImages]="coverImages" [formData]="formData" [textsPag1]="textsPag1" *ngIf="cont == 1" [disabledClick]="disabledClick"> </app-portada>
        <app-pag1 [imagesPag2]="imagesPag2" [formData]="formData" [textsPag2]="textsPag2" [disabledClick]="disabledClick" *ngIf="cont == 2"> </app-pag1>

este es el componente hijo:

@Component({
  selector: 'app-portada',
  templateUrl: './portada.component.html',
  styleUrls: ['./portada.component.css']
})
export class PortadaComponent implements OnInit, OnChanges {

disabled: boolean= true;
@Input() coverImages: Images;
@Input() formData: any;
@Input() coverTexts: Text;
@Input() textsPag1: Texts;
@Input() disabledClick: boolean;

  @ViewChild("fileInput1") el1: ElementRef;

  // coverImages= {} as Images;
  // data= {} as Text;
  test= {} as Texts;
  text1: string;
  disabledCl: any=null; // deshabilitar click
  form: any='';

  constructor(public dialog: MatDialog, private usuarioService: UsuarioService, private uploadImgService: UploadImagesService) {
    console.log('\n\nConstructor de PortadaComponent...')
    // this.textsPag1.pag1Texts.text1= 'ZZZZZZZZZZZZZ';
  }

la plantilla del componente hijo:

            <input #fileInput1 type="file" id="imageUpload1" accept=".png, .jpg, jpeg" name="file" (click)="Click($event)" (change)="uploadImg($event)">

            <textarea class="text-left textoNegro" [(ngModel)]="test.pag1Texts.text1"  ></textarea>

            <textarea class="text-left textoNegro" [(ngModel)]="test.pag1Texts.text2"  ></textarea>

            <textarea class="text-left textoBlanco" [(ngModel)]="test.pag1Texts.text3"  ></textarea>

            <textarea class="text-center textoBlanco" [(ngModel)]="test.pag1Texts.text4" ></textarea>

              <textarea class="text-center textoBlanco" [(ngModel)]="test.pag1Texts.text5" ></textarea>

esta es la interfaz:

export interface Texts {
    pag1Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag2Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag3Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag4Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag5Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag6Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag7Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag8Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag9Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag10Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag11Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag12Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag13Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  },
    pag14Texts: {text1?: string, text2?: string, text3?: string, text4?: string, text5?: string  }

}

acá dejo una captura del error en el componente portada (componente hijo):

se que es un problema de inicialización, pero no hallo como resolverlo, si ven en el componente padre hay unas lineas comentadas donde intente inicializar los valores antes de pasarlos al componente hijo pero no funcionó, como puedo arreglar esto?

A: Valla te explico que estas haciendo, en la vista de hijo tienes lo siguiente a la altura de la linea 10.

    <textarea class="text-left textoNegro" [(ngModel)]="test.pag1Texts.text1"  ></textarea>

Acá estas diciendole al textarea que observe el valor de la variable test.pag1Texts.text1, entonces vamos a ver que tienes en el componente en la variable test
  // coverImages= {} as Images;
  // data= {} as Text;
  test= {} as Texts;  // <----- tienes test como un objeto que luego casteas Texts, jamás se implementa, intestas transformarlo
  text1: string;
  disabledCl: any=null; // deshabilitar click
  form: any='';

Tú al instanciar la variable test como = {} (implícitamente del tipo any y luego casteada a Text creas el objeto sin atributos ni nada, completamente en blanco y al castearlo a Text sigue en blanco, typescript no puede transformar ni va poder entender tu tipo any a Text) entonces cuando realizas la llamada al atributo pag1Texts de un tipo incorrecto que jamás fue instanciado.
ósea tu variable test se ve como la haz declarado {}, un objeto en blanco y al llamar al atributo pag1Texts obviamente te va dar undefined entonces:
test.pag1Texts = undefined

y ya sabes el resto, al llamar un atributo de un undefined obtienes un error, que es el que te muestra la consola.
Para solucionarlo tienes dos opciones:

*

*Cambia de interface a class el tipo Text, y crea un constructor adecuado que pueda inicializar tus atributos. Creo que no es necesario un ejemplo, esto es bastante sencillo y te puede ahorrar muchos problemas.

*Al objeto test asígnale el atributo pag1Texts en el constructor del componente, y este a su vez asígnale un valor tipo string al atributo text1 ósea algo como esto.

// coverImages= {} as Images;
// data= {} as Text;
test= {} as Texts; // No necesitas hacer esto, me parece suficiente con que lo dejes como un any
text1: string;
disabledCl: any=null; // deshabilitar click
form: any='';

constructor(
 public dialog: MatDialog,
 private usuarioService: UsuarioService,
 private uploadImgService: UploadImagesService) {
   console.log('\n\nConstructor de PortadaComponent...');
   // this.textsPag1.pag1Texts.text1= 'ZZZZZZZZZZZZZ';

   // Inicialización de lo que requiere tu vista componente PortadaComponent
   this.test.pag1Texts = {};
   this.test.pag1Texts.text1 = '';
}

Pienso que puedes optimizar tu código se ve un poco forzado, intenta siempre reutilizar en vez de declarar declarar y declarar.

A: Los problemas que veo son los siguientes

*

*En tu componente principal el código comentado

Declaraste: textsPag1= {} as Texts;   - puedes declararlo así también textsPag1: Texts= {}
En tu constructor:  // this.textsPag1.pag1Texts.text1= 'b'
Hasta this.textsPag1.pag1Texts esta bien porque angular automáticamente te va a crear el
valor pero quieres inicializar en un nulo // this.textsPag1.(aun no existe).text1= 'b'
Las correcciones serian las siguientes en tu constructor:
this.textsPag1.pag1Texts = {text1: "b", text2:"b", text3:"b"}


text:
Q: Pattern with $\sec(x)$ partial sums I calculated with Wolfram|Alpha the partial sums of $S(x) = \sum^{x}_{n=0} \sec(n)$ and when I plot them I get a repeating pattern:

Which I thought would not happen given the fact that $\sec(x)$'s period is an irrational number ($\tau$). Any explanation for this wave's existance in this equation?


text:
Q: Limit default stack size in GHCi In a recent question about stack overflows in Haskell kosmikus said the default stack size of GHCi is 512 MB. I would much rather have a smaller stack size, like 2 MB or something, because if I go beyond that, in almost all cases, it will be because of an error on my part. My system doesn't have very much RAM, so a stack size of 512 MB sometimes causes some crazy swapping and slowness when I make a mistake in the code.
Is there a way to limit the default stack size of GHCi, in the .ghci file or somewhere else?
I'm aware that I should be able to create an
alias ghci='ghci +RTS -K2M -RTS'

as a last resort, but I'd like to avoid that if possible.


text:
Q: How to replace IP address with another one? How to replace IP address with another one ?

without adding a new lines

A: Go to where the ip is hardcoded in binary (make sure to analize the code using AnaliseThis! plugin)
the ip probably is in some address on the pushes after the function (i think you are looking on the wrong place)
I just hope that Steamcl module dont means Steam Cloud (im pretty sure that is) you may get sued for reversing steam softwares
and by the way, next time make a more specified question, and don't act like a ironic guy on commentaries, no one is obligated to answer you.
see ya.


text:
Q: App Store Connect: ITMS-90492: Invalid WatchKit Support I tried updating a stand alone WatchOS app to the App Store and got this message from iTunes after uploading it:
ITMS-90492: Invalid WatchKit Support - The file WK doesn't have the correct code signature. Make sure you're using the correct signature, rebuild your app using the current public (GM) version of Xcode, and resubmit it. Don't just modify the code signature of WK.
I have uploaded previous version without a problem, so I think it might have something to do with using WKInterfaceDevice().play(.click) in my code which is new to the version uploaded, but I  am not entirely sure, has anyone ran into a similar problem and how did you fix it?

A: This appears if you have XCode beta installed on your Mac. It doesn't have to run just its simple presence results in this artefact.


text:
Q: How to explain funny behavior of call/cc in Racket? combine must map reduce a list with the binary operator bin but must return exc if it finds any value that fails the predicate pred?, and if it finds any such value it must not perform any calculation on the list.
This is a simple continuation problem.
#lang racket

(define (id x)
  x)

(define (const x)
  (lambda (_) x))

(define (combine pred? bin zero exc)
  (call/cc
   (lambda (exit)
     (letrec
         ((f (lambda (xs)
               (if (empty? xs)
                   zero
                   (if (pred? (first xs))
                       (exit exc)
                       (bin (first xs) (f (rest xs))))))))
       f))))

(define product
  (combine zero?
           *
           1
           0))

(product '(1 2 3 0 4))

The code almost works, but it has a very subtle error.
It raises the following exception:
define-values: assignment disallowed;
 cannot re-define a constant
  constant: product

It is easy to make it work. Only a small change is needed:
(define (combine pred? bin un zero exc)
  (lambda (ys)
    (call/cc
     (lambda (exit)
       (letrec
           ((f (lambda (xs)
                 (if (empty? xs)
                     zero
                     (if (pred? (first xs))
                         (exit exc)
                         (bin (first xs) (f (rest xs))))))))
         (f ys))))))

I see that the problem is that Racket the continuation of define is to define  a function, but can anyone give more details? What syntatic transformations involved, for example?

A: Think of the order you have to have here:
(define product (combine ....))

Here you first evaluate (combine ...) and the continuation is the rest of the program starting with storing the computed value as the name product. Calling the continuation from withing  f jumps right back to storing product all over again.
By calling (product '(1 2 3 0 4)) you are redefining product since it is the continuation of the program and call/cc captures the continuation.
In your second attempt you do a true refactoring of wrapping it in a lambda and call f with the same argument. It's just delaying when the call/cc happens and thus what is included in the continuation. In this version the continuation is whatever comes after the (product ...) and not the setting pf product in (define product ...)


text:
Q: Accessing MultiIndex in a specific format I have the following dataframe,
df = pd.DataFrame(np.random.randint(0,1000, (5,6)), \
                  columns = pd.MultiIndex.from_product([['CPC', 'Conversions'], ['April', 'June', 'May']])).rename_axis(index = {None : 'idx'})

df

      CPC                 Conversions
      April June  May     April June  May
idx
 0     663  964  971      663   76  927
 1     405  217  754      370  306   34
 2     474  229  664      354   66  885
 3      73  538  139      417  876  855
 4     619  618  618      455  134  805

I wanted to access the months column level in right format so I did this
df.loc[:, (slice(None), ['April', 'May', 'June'])]

        CPC Conversions   CPC Conversions   CPC Conversions
      April       April   May         May  June        June
idx
 0      806         202   963         975   110          55
 1      263         884   442         563   216         694
 2      462         361   780         412   858         670
 3      742         756   525          33   477         826
 4      579         332    91         802   829         231

It's weird how the result comes while it works perfectly fine when I use two months instead of three (see below)
df.loc[:, (slice(None), ['April', 'May'])]

              CPC      Conversions
       April  May       April  May
idx
 0       856  619         180  593
 1        64  403         929   80
 2       973  285         803  967
 3       769  405         701  267
 4       940  368         863  717

Can anyone tell me what's wrong, it seems buggy to me.
Currently what I'm doing is creating a MultiIndex.from_product (just as I used for creating this example) with ordered months and replace the existing column with it. However, I don't want to do that since the other column levels might change over time.

A: You can order your columns by using df.reindex():
cols = ['April', 'May', 'June']
new_cols = df.columns.reindex(cols, level=1)
df.reindex(columns=new_cols[0])

Without creating new variables:
df.reindex(columns=['April', 'May', 'June'], level=1)

A: It's not buggy, it's just unexpected:
>>> df.columns.levels
FrozenList([['CPC', 'Conversions'], ['April', 'June', 'May']])

>>> df.columns.codes
FrozenList([[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

>>> df.columns.is_monotonic
True

We can see 'April' has the code 0, 'June' the code 1 and 'May' the code 2.
Now you slice your dataframe by second level:
# Your code (unordered codes)
>>> df.loc[:, (slice(None), ['April', 'May', 'June'])]

  CPC Conversions  CPC Conversions  CPC Conversions
April       April  May         May June        June
...

but if your slice your dataframe according the ordered codes, it works as expected:
>>> df.loc[:, (slice(None), ['April', 'June', 'May'])]
  CPC           Conversions
April June  May       April June  May
...

Check some properties:
>>> df.loc[:, (slice(None), ['April', 'May', 'June'])].columns.is_monotonic
False

>>> df.loc[:, (slice(None), ['April', 'June', 'May'])].columns.is_monotonic
True

>>> df.loc[:, (slice(None), ['April', 'May', 'June'])].columns.codes
FrozenList([[0, 1, 0, 1, 0, 1], [0, 0, 2, 2, 1, 1]])

>>> df.loc[:, (slice(None), ['April', 'June', 'May'])].columns.codes
FrozenList([[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

If you use sort_index after your slice, the dataframe is sorted as its creation:
>>> df.loc[:, (slice(None), ['April', 'May', 'June'])].sort_index(axis=1)
  CPC           Conversions
April June  May       April June  May
...

Sorting MultiIndex is based on codes.


text:
Q: program generates random recipes in python I am writing a code that generates a random recipes. It should be structured like this .
*** <main_ingredient> <baking> Recipe ***
Ingredients:
<quantity> <measure> <main_ingredient>
<quantity> <measure> <ingredient>
<quantity> <measure> <ingredient>
<quantity> <measure> <ingredient>
<quantity> <measure> <ingredient>
<quantity> <measure> <ingredient>
Method:
Mix the <ingredient>, <ingredient>, <ingredient>, <ingredient> and <ingredient> together.
Gently fold in the <main_ingredient>.
Place mixture in <baking> tin and bake at <temperature> degrees Celsius for <time> minutes.
***

and I have this code at the moment
import random
main_ingredient = ['chocolate', 'banana', 'salted caramel', 'carrot', 'bran']
baking = ['cake', 'brownie', 'cupcake', 'muffin']
measure = ['tbsp', 'tsp', 'cup']
ingredient = [ 'flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']

m_ingredient = random.choice(main_ingredient)
baking_ = random.choice(baking)
ingredients = [random.choice(ingredient), random.choice(ingredient)]

print ("***", m_ingredient.title(), baking_.title() , "Recipe ***")
print ("Ingredients:")

for i in ingredient:
    print (random.randint(1,3), random.choice(measure), i)

Is there another way to write up this code? can someone give me an idea on what to use and how to do it?

A: You could print the line with your main ingredient before your loop, and put the whole thing in a function so it can print multiple recipes in a loop like this
import random

main_ingredient = ['chocolate', 'banana', 'salted caramel', 'carrot', 'bran']
baking = ['cake', 'brownie', 'cupcake', 'muffin']
measure = ['tbsp', 'tsp', 'cup']
ingredient = [ 'flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']

def create_recipe(main_ingredient, baking, measure, ingredient):
    "Create a random recipe and print it."""
    m_ingredient = random.choice(main_ingredient)
    baking_ = random.choice(baking)
    ingredients = [random.choice(ingredient), random.choice(ingredient)]

    print("***", m_ingredient.title(), baking_.title() , "Recipe ***")
    print("Ingredients:")
    print(random.randint(1,3), random.choice(measure), m_ingredient)
    for i in ingredient:
        print(random.randint(1,3), random.choice(measure), i)

# create multiple random recipes
for i in range(3):
    create_recipe(main_ingredient, baking, measure, ingredient)


text:
Q: Serverless notifications with Cloud Functions for Firebase I have used firebase chat notification cloud function but when
notification triggered I am getting this error in firebase function
console

Cannot read property 'current' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:8:35)

Here is my function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}').onWrite(event => {
    console.log('Push notification event triggered for testing');
    console.log(event);
    const message = event.data.current.val();
    const senderUid = message.from;
    const receiverUid = message.to;
    console.log(receiverUid);
    const promises = [];

    if (senderUid === receiverUid) {
        //if sender is receiver, don't send notification
        promises.push(event.data.current.ref.remove());
        return Promise.all(promises);
    }

    const getInstanceIdPromise = admin.database().ref(`/usersnew/${receiverUid}`).once('value');
    const getSenderUidPromise = admin.auth().getUser(senderUid);

    return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results => {
        const instanceId = results[0].val();
        const sender = results[1];
        console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);

        const payload = {
            notification: {
                title: sender.displayName,
                body: message.body,
                icon: sender.photoURL
            }
        };

         admin.messaging().sendToDevice(instanceId, payload)
            .then(function (response) {
                return console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });

            return console.log('This is the notify feature');
    });
});

Does anyone know how to solve this?
When I log event it shows like below in console
{ before:
   DataSnapshot {
 app:
  FirebaseApp {
    firebaseInternals_: [Object],
    services_: {},
    isDeleted_: false,
    name_: '__admin__',
    options_: [Object],
    INTERNAL: [Object] },
 instance: 'https://teleport-24f52.firebaseio.com',
 _path: '/notifications/messages/-LIlFNd2spo_V1rM-G-f',
 _data: null },
  after:
   DataSnapshot {
 app:
  FirebaseApp {
    firebaseInternals_: [Object],
    services_: {},
    isDeleted_: false,
    name_: '__admin__',
    options_: [Object],
    INTERNAL: [Object] },
 instance: 'https://teleport-24f52.firebaseio.com',
 _path: '/notifications/messages/-LIlFNd2spo_V1rM-G-f',
 _data:
  { body: 'abc',
    dayTimestamp: 1532975400000,
    from: 'q8gtwtwXqbV2DtpsrbYajFsWzSr2',
    negatedTimestamp: -1533056068309,
    timestamp: 1533056068309,
    to: 'Cmpu7mbIENTYyoHZjCjZnbnBMbl2' } } }
10:22:44.625 PM

A: In your code, event.data.current should be event.after.val() , event.after.ref, etc...
There was a change of API in cloud functions 1.0.
Read:
https://firebase.google.com/docs/functions/database-events#reading_the_previous_value
https://firebase.google.com/docs/functions/beta-v1-diff

A: Maybe the problem is in the SDK version. From v1.0 things change a bit. Try updating SDK and follow these instructions for miragation:
https://firebase.google.com/docs/functions/beta-v1-diff


text:
Q: How to pass variable into SqlCommand statement and insert into database table I'm writing a small program in C# that uses SQL to store values into a database at runtime based on input by the user.
The only problem is I can't figure out the correct Sql syntax to pass variables into my database.
private void button1_Click(object sender, EventArgs e)
    {
        int num = 2;

        using (SqlCeConnection c = new SqlCeConnection(
            Properties.Settings.Default.rentalDataConnectionString))
        {
            c.Open();
            string insertString = @"insert into Buildings(name, street, city, state, zip, numUnits) values('name', 'street', 'city', 'state', @num, 332323)";
            SqlCeCommand cmd = new SqlCeCommand(insertString, c);
            cmd.ExecuteNonQuery();
            c.Close();
        }

        this.DialogResult = DialogResult.OK;
    }

In this code snippet I'm using all static values except for the num variable which I'm trying to pass to the database.
At runtime I get this error:
A parameter is missing. [ Parameter ordinal = 1 ]

Thanks

A: Add a parameter to the command before executing it:
cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;

A: You didn't provide a value for the @ parameter in the SQL statement. The @ symbol indicates a kind of placeholder where you will pass a value through.
Use an SqlParameter object like is seen in this example to pass a value to that placeholder/parameter.
There are many ways to build a parameter object (different overloads).  One way, if you follow the same kind of example, is to paste the following code after where your command object is declared:
        // Define a parameter object and its attributes.
        var numParam = new SqlParameter();
        numParam.ParameterName = " @num";
        numParam.SqlDbType = SqlDbType.Int;
        numParam.Value = num; //   <<< THIS IS WHERE YOUR NUMERIC VALUE GOES.

        // Provide the parameter object to your command to use:
        cmd.Parameters.Add( numParam );


text:
Q: Ampersand and hash crash my MYSQL Query I'm using this code to obtain data from a mysql query.
    if ($filter == "All" && $filter != "") {date_default_timezone_set('America/Denver');
$todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."'";
}else{ $todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE  events.name LIKE '%".$search."%'   AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.description LIKE '%".$search."%'    AND events.price = '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."' OR events.user = '".$_SESSION['username']."' AND events.address LIKE '%".$search."%'   AND events.price = '".$filter."' AND events.end > '".$todays123."'  ";
}

Here's my javascript code
function user_display() {

var search = document.getElementById("search").value;

if (search == "" || search == null) {
    search="";
}

var filter = document.getElementById("filter").value;

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("table-content").innerHTML=xmlhttp.responseText;
    }
}
    xmlhttp.open("GET","./xxx.php?action=display&search="+search+"&filter="+filter, true);
xmlhttp.send();

}
It matches correctly when the search value does not contain  "&" and a "#." When I enter a ampersand or hash symbol the query crashes and does not display anything.
Any suggestions on why it is doing this? Thanks in advance

A: You probably should be using encodeURIComponent() in your JavaScript. It's likely that you're not getting results because it's not passing anything in the search variable (or cutting it off short). Consider if the search is "a&foo=c&". The URL you are requesting is now xxx.php?action=display&search=a&foo=c&filter=... so you end up with another GET variable named foo
var search = encodeURIComponent(document.getElementById("search").value);

Do the same for filter if it's something the user will supply.

A: change your code to atleast look like this
 $search = mysql_real_escape_string($search);
 $filter = mysql_real_escape_string($filter);
 // hopefully username in $_SESSION is clean else repeat above for that and rerun your query
 if ($filter == "All" && $filter != "") {date_default_timezone_set('America/Denver');
 $todays123 = date("Y-m-d H:i");
 $query = "SELECT * FROM events WHERE events.name LIKE '%".$search."%' AND events.user = '".$_SESSION['username']."' AND events.end > '".$todays123."'";
 }else{ $todays123 = date("Y-m-d H:i");
$query = "SELECT * FROM events WHERE  events.name LIKE '%".$search."%'   AND events.price =   '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end >   '".$todays123."' OR events.description LIKE '%".$search."%'    AND events.price =  '".$filter."' AND events.user = '".$_SESSION['username']."' AND events.end >  '".$todays123."' OR events.user = '".$_SESSION['username']."' AND events.address LIKE  '%".$search."%'   AND events.price = '".$filter."' AND events.end > '".$todays123."'  ";
  }

The above change will atleast make sure that SQL injections can be avoided.


text:
Q: Trying to make a simple app with addition of variables, having some problems I have a timePicker with a 24h format and I want to take the results, put them into variables, using the variables in addition and then display them in a textView. Eclipse isn't giving me and syntax errors but when I run the app, it crashes when I start "DisplayMessageActivity.java".
Here is the code:
package com.example.sleepytime;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

@SuppressLint("NewApi")
public class DisplayMessageActivity extends Activity {

 TimePicker timepicker;
 public int hour1 = timepicker.getCurrentHour();
 public int min1 = timepicker.getCurrentMinute();

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);

    timepicker = (TimePicker) findViewById(R.id.timePicker1);
    timepicker.setIs24HourView(true);

    Button mButton = (Button) findViewById(R.id.button1);
    mButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View printIt) {
        final TextView mTextView = (TextView) findViewById(R.id.print);
        mTextView.setText(hour1 + min1);
}

});

}
}

A: Here
public int hour1 = timepicker.getCurrentHour();
public int min1 = timepicker.getCurrentMinute();

timepicker is null. You need to put it in onCreate() like here
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);

timepicker = (TimePicker) findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
hour1 = timepicker.getCurrentHour();
min1 = timepicker.getCurrentMinute();

and change
public int hour1 = timepicker.getCurrentHour();
public int min1 = timepicker.getCurrentMinute();

to
public int hour1;
public int min1;

that is the first problem I see. There could be more but that will keep you from going any further.
 mButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View printIt) {
    final TextView mTextView = (TextView) findViewById(R.id.print);
    String hourString = String.valueOf(hour);
    String minString = String.valueOf(minute);
    mTextView.setText(hourString + minString);

A: TimePicker timepicker;
 public int hour1 = timepicker.getCurrentHour();
 public int min1 = timepicker.getCurrentMinute();

You can not do this, it will give you null pointer exception, do it like this
timepicker = (TimePicker) findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
hour1 = timepicker.getCurrentHour();
min1 = timepicker.getCurrentMinute();

Plus your current code will break when run on api lower than 3.0.place a check on
 getActionBar().setDisplayHomeAsUpEnabled(true);
or change the minimum sdk to 3.0 if you don't want to support versions prior to honeycomb


text:
Q: Moodle: since Update to 2.9.1, User can't change their password
recently I updated a moodle site from 2.6.7 to 2.9.1.
The moodle itself runs quit fine, but user can't change their passwords anymore.
I checked the roles settings: ("moodle/user:changeownpassword = Allow") its like it should be.

Where can I check else?

A: See https://docs.moodle.org/29/en/Preferences
Now you have a specific page to change password
access: yourmoodle/user/preferences.php
chmagepassword
User account
Links here allow users to edit their profile information and change their password, specify how they wish to receive forum and other notifications, choose a text editor (if allowed) and view/reset their RSS token.

A: Issue was that the old theme hide the new profile window.
My workaround is to create a simple link, to /login/change_userpassword.php inside menu.

A: You can download a local plugin called "local_resetpasswordmoodleversion...zip" install it. Make sure you enabled the plugin in its settings. After all when you go to user preferences you will find the change password activities as shown in the imageenter image description here


text:
Q: Runtime.InvalidEntrypoint error on AWS Lambda Custom Runtime I have created an AWS Lambda function using Lambda Custom Runtime on Amazon Linux 2 which generates an example that, if I execute the example, it fails with permission denied error:
Response
{
  "errorMessage": "RequestId: f6adb86a-7fbd-4ed5-85d8-2e07edda78e6 Error: fork/exec /var/task/bootstrap: permission denied",
  "errorType": "Runtime.InvalidEntrypoint"
}

I am trying to use custom runtime to run a bash script in Lambda. Anyone know how I can fix this permission issue?

A: This is rather frustrating as the example custom bootstrap from AWS themselves provides files with incorrect permissions. In order to fix you need to download the files, update permissions and re upload the same files for the example to even work


text:
Q: How to save values from a table into another table delphi I am using delphi rad studio and i am a beginner in this. I am trying to insert values into a table from another table which contains just IDs. I have some comboboxes filled with ID's from a table and then i want to insert these values into another table. To be more specific i have a table that contains the specifications about cars and i want to save those into a table which contains information of rental this cars. I have tried much but i didn't get the answer. Here is the code for combobox :
    procedure TForm13.DBLookupComboBox1Click(Sender: TObject);
    begin
    adomarca.SQL.Text :=    ' SELECT tabel_Marca.Marca from Tabel_Masini ' +
     'join tabel_Marca on tabel_masini.id_Marca=tabel_marca.id_Marca ' ;

     SELF.ADOmarca.ExecSQL;
     SELF.ADOmarca.Open;
     ADOmarca.Prepared := TRUE;
     end;

And this is the code for the save button:
     procedure TForm13.button2click(Sender: TObject);

      begin
      Comanda := 'Insert into Tabel_Inchirieri (id_Client, id_Marca,
                id_Model, id_Transmisie, id_Caroserie, id_Culoare,
                   id_Combustibil, Ziua_Inchirierii, Ziua_Restituirii,
            Nr_zile_inchiriate) ' +
        // 'select * from tabel_masini ' +
         'Values (' + inttostr(DBLOOKUPCOMBOBOX8.keyvalue) + ','
         +inttostr(DBLOOKUPCOMBOBOX1.keyvalue) + ',' +
          inttostr(DBLOOKUPCOMBOBOX2.keyvalue) + ',' +
          inttostr(DBLOOKUPCOMBOBOX3.keyvalue) + ',' +
          inttostr(DBLOOKUPCOMBOBOX4.keyvalue)+ ',' +
           inttostr(DBLOOKUPCOMBOBOX5.keyvalue) + ',' +
          inttostr(DBLOOKUPCOMBOBOX6.keyvalue)+ ',' +
           quotedstr(formatdatetime('yyyy-mm-dd',DateTimePicker1.Date))+
          ','+ quotedstr(formatdatetime('yyyy-mm-
           dd',DateTimePicker2.Date))+',' +
          inttostr(daysbetween(DateTimePicker2.Date,
        DateTimePicker1.Date))+')';
         Qcomanda.SQL.Add(Comanda);

         try
           Qcomanda.ExecSQL ;
         finally
            ShowMessage('Comanda a fost salvata cu succes ! ');

          end;

           end;

Thank you very much.

A: You don't say what RDMS you are using, but there are ways to do this entirely in SQL
that should work with at least MS Sql Server and MS Access, which are probably
the mostly commonly used RDMSs with ADO.
If you are intending your copying operation to populate a new table on the server
you can use SQL like this
   SELECT
     [FieldList]
   INTO
     MyNewTable
   FROM
     [tables and join condition]

You can easily google an example of this, see f.i.
http://www.vb-helper.com/howto_ado_select_into.html
If you want to copy rows into an existing table you can use the
   INSERT INTO
     [tablename]
   SELECT
     [fieldlist]
   FROM
     [tables and join condition]

see f.i. https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/insert-into-statement-microsoft-access-sql
You can execute these SQL statements either in a Delphi app or, if using MS SQL Server,
using the SQL Server Management Studio.
Either method, unlike your proposed code, would copy the selected records all in one go, without any need for a record-by-record, column-by-column copying operation, and you should find either method extremely fast compared to client-side record-by-record copying.  However, you need to be careful if a very large number of records is involved: doing them all in one go means that they are potentially wrapped up in a huge server-side transaction which could exhaust the server's resources, so in that situation it would probably be better to split the copying up into a series of smaller batches, if that's practicable.


text:
Q: difference in the format of output between datetime and datetime2(3) data types when converted to varchar with style 114 There is a difference between the format of DateTime and DateTime2(3) when they are converted to varchar with style 114. The example is as follows:
DECLARE @date1 datetime=GETDATE()
DECLARE @date2 DATETIME2(3)=GETDATE()

SELECT CONVERT(VARCHAR,@date1, 114),CONVERT(VARCHAR,@date2,114)

The output of the above SQL statements is:
14:47:33:820   14:47:33.820

db<>fiddle.uk
So, we can see the difference in the output is ":" in the case of DateTime whereas "." in the case of DateTime2(3).
Is there any solution to get the ":" in the output in the case of datetime2(3)?

A: The behavior is unexplainable; as a workaround, you can use the FORMAT function to format the date:
DECLARE @date1 DATETIME     = SYSDATETIME()
DECLARE @date2 DATETIME2(3) = SYSDATETIME()

SELECT
    @date1,
    @date2,
    FORMAT(@date1, 'HH:mm:ss:fff'),
    FORMAT(@date2, 'HH:mm:ss:fff')

A: I think you can CAST @date2 AS DATETIME before convert to varchar if you want to get the ":" in the output in the case of datetime2(3)
SELECT CONVERT(VARCHAR,@date1, 114),CONVERT(VARCHAR,CAST(@date2 AS DATETIME),114)

A: In the meantime, format 113 seems to use the colon correctly, so you can use:
RIGHT(CONVERT(VARCHAR(255), @date2, 113), 12)

Note the use of a length with VARCHAR().  My advice is to never use string types in SQL Server without a length.  The default length varies by context and not including an explicit length can introduce a hard-to-debug error.


text:
Q: SimpleMembership - WebSecurity GetConfirmationToken Problems I'm building an application which is close to completion, I'm adding in the final layers of security and functionality for emailing new user's a confirmation token when they register. Getting the initial registration confirmation token was easy enough. The token is passed to the view and an email is sent out. However, there are two scenarios where I need to resend that token, these being:

*

*When the user is redirected to a view called 'Registration Step Two'.

*When a user tries logging in before they have confirmed their account.

The first scenario has a button on the page which could easily have the token embedded, making this a simple task. However, the login page will not have this functionality, the server will only know the user's email address. Keeping to the DRY principle I am merging this into one method, however whilst I can get the email address the user registered with I can't find an appropriate WebSecurity or Membership call which gets the confirmation token.
I've tried requesting this from the membership table using the below Expression, however an exception is thrown stating the LastPasswordFailureDate is null (which is to be expected), so this wasn't possible.
Expression<Func<MembershipModel, bool>> query = q => q.UserId == userId;

I've looked at blogs similar to Kevin Junghans (below), however WebSecurity.GetConfirmationToken doesn't seem to be supported anymore as I cannot locate it anywhere.
Retrieving Confirmation Token
I've even seen the next link, which points at a question on StackOverflow and to be honest I don't want to be implementing it in this manor as I've spent a vast amount of time incorporating an EntityFramework repository pattern to do all this for me.
Resend Confirmation Email with WebSecurity
I'm wondering if anyone has any recommendations on getting the confirmation token without writing the SQL within the application itself.

A: Whilst thinking on it a little more this morning, I finally realised why the LastPasswordFailureDate was returning the mentioned Exception. Essentially I believe I am an idiot and have forgotten to add a nullable reference to the DateTime fields within my Model. I can't test this for fix for several hours, but will update this answer/question in either event.


text:
Q: Checking variable colors How can I get the following function to return multiple color types (not just red, but also orange, yellow, etc.) without using multiple if/else statements?
function isRainbowColor(color){
  if (color === "red"){
  return true;
  }else{
    return false;
  }
}
console.log(isRainbowColor("red"));
 //This returns true, but only for one color at a time.  How can I add onto ?

A: Create an array of acceptable colors, and check the color with the Array.includes() function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

function isRainbowColor(color){
  let acceptableColors = ["red","orange","yellow","blue","green"]
  if (acceptableColors.includes(color)){
  return true;
  }else{
    return false;
  }
}
console.log(isRainbowColor("red"));
console.log(isRainbowColor("green"));
console.log(isRainbowColor("purple"));
 //This returns true, but only for one color at a time.  How can I add onto ?


text:
Q: How can I generate text file with all the prime numbers in progress 4gl In the below code i am importing a text file with numbers 3 to 99 .
i have partially written code to find out the prime numbers from the given numbers.
 define variable a as integer.

 define variable b as integer.

 define variable i as integer initial 0.

    INPUT FROM Value ( "C:\src\New folder\bingo.txt").
    repeat :

      IMPORT a.
      b = a mod i.
      if b=0 then
      do:
        if a=i then
        do:
          message " prime number"a view-as alert-box.
        end.
        else if a<>i then
        do:
          i=i + 1.
          message " not prime number"a view-as alert-box.

        end.

        else if a < i then
        do:
          message "not prime number"a view-as alert-box.
        end.
      end.
      END.
      if b<>0 then
      do:
        i=i + 1.
        message "b<>0"b view-as alert-box.
      end.
      end.
   Output To Value( "C:\src\New folder\even.txt")append.
   export a space.
   output close.
   end.
   end.

help me with .
to program

A: I think it will make more sense to store the prime check in a function or a procedure. This prime check isn't necessary perfect but it will work for these conditions.
Also it's best to define and use streams when working with both in- and output.
DEFINE VARIABLE a AS INTEGER     NO-UNDO.

DEFINE VARIABLE b AS INTEGER     NO-UNDO.
DEFINE STREAM strIn.
DEFINE STREAM strOut.

FUNCTION isPrime RETURNS LOGICAL (INPUT iNum AS INTEGER ):

    DEFINE VARIABLE iDiv   AS INTEGER     NO-UNDO.

    DO iDiv = 2 TO INTEGER(SQRT(iNum)):
        IF iNum MOD iDiv = 0 THEN
            RETURN FALSE.
    END.

    RETURN TRUE.
END.

OUTPUT STREAM strOut TO VALUE ("c:\temp\primes.txt").
INPUT STREAM strIn FROM Value ( "C:\temp\bingo.txt").
repeat :

    IMPORT STREAM strIn a.

    IF isPrime(a) THEN DO:
        /*MESSAGE "prime number" a view-as alert-box. */
        PUT STREAM strOut UNFORMATTED a SKIP.
    END.
    ELSE DO:
        /*MESSAGE "not prime number" a view-as alert-box. */
    END.

END.
INPUT STREAM strIn CLOSE.
OUTPUT STREAM strOut CLOSE.


text:
Q: Android-what to do with chosen image? I have the following code on my button, which allows me to click a button and choose a PDF file. How do I get the path of the PDF file, and actually do something with the file (because right now I can only click on the file and nothing happens). I want the image to be put in an API do to something to the image.
            final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("*/*");
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);

A: You must override the onActivityResult in order to get what you need.
You will be able to get what you want (the file path) with the resulting intent. Like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    if(resultCode == RESULT_OK) {
        Uri fileUri = intent.getData();
    }
}


text:
Q: Using replace string method inside forEach I have an array full of strings which I'd like to loop over and replace any occurrences of '123' with ''.
The desired result would be: ['hello', 'cats', 'world', 'dogs']
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach(x => {
  x.replace('123', '');
});

A: Use .map instead, if you can - return the .replace call in the callback:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

const result = arr.map(x => x.replace('123', ''));
console.log(result);

If you have to mutate the array in-place, then take the index as well, and assign the .replace call back to that index in the array:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach((x, i) => arr[i] = x.replace('123', ''));
console.log(arr);


text:
Q: Does request.getSession() set cookie into the browser? I was learning session in Servlets and doing some code stuff. I saw this:
I invoked Servlet using the URL mapping. That is:
http://localhost:8080/ServletSessionProject/SessionLearningPath

The servlet code is very simple:
HttpSession session = request.getSession();

Now, with this simple code (I used doGet()), I then opened the cookies in chrome, like this:
chrome://settings/cookies

There was I was able to see a cookie set.
I am confused. In my code I simply called request.getSession(). Why is this simple statement setting a cookie in the browser? I am sure that the cookie was not there before.
How is this possible?

A: Yes. Session is set in the cookie. JSESSIONID
Web Application do trace user session using cookie but this is not the only method.
When a user does not have a session with a web application and request.getSessin(); is called, Servlet api create a new session and a session id. This session id is used to uniquely represent and trace the user session. This session id is sent in the response as a set cookie request. That is why you are seeing the cookie after one request cycle.

A: See: request.getSession()

Returns the current session associated with this request, or if the
  request does not have a session, creates one.

Session creation will set session cookie on HTTP response message. This is the "magic" that creates cookie and transfers it to the browser.


text:
Q: How to authorise (with OAuth 2.0) in JMeter having sharepoint online app? I have recorded scripts for all test cases, and run all test cases due to the OAuth  2.0 it is failing all of the test cases.
Now I have to authenticate OAuth 2.0 in JMeter, I have following information:
client_id, response_mode, protectedtokena, response_type, resources, scope, nonce,redirect_uri,wsucxt, cobrandid, client-request-id.

A: *

*Add (or parametrize) parameter Authorization in your HTTP Header Manager. Add Bearer ${AuthToken} value. You should parse that token from previouse request.

*Check this guide about How to parse auth token


text:
Q: Zclip not working Hi friends I am trying to implement click to copy using zclip.
I am having different ids for same class so initially i am finding the id of the element on which i clicked and applying zclip to that element.
 $(".coupon_code_text").on('click', function (e) {
  pos = "#" + $(this).attr("id");
    e.preventDefault();
    clktocpy();
    function clktocpy(){

    $(pos).zclip({
            path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
            copy: function () {
                return $(pos).text();
    }
});
            }
})

The following is the php part where I am generating different ids for the same class.
  <?php
    $count = 0;
    foreach($coupons as $value)
    {
    $count = $count +1;

          <a class="coupon_code_text" id ="copypath-<?php echo $count;?>">
                <?php echo $array['coupon_code'];?>

    <?php}?>

A: Remember that in order to get by id using jQuery you need to append a # to the string.
Like the following #myId, your variable pos only contains the id without the #.
Line 2, fixed
pos = "#" + $(this).attr("id");


text:
Q: The "no known conversion" from const char* to an iterator error - another take I'm doing the following:
using namespace boost;
const char* line = // ...
size_t line_length = // ...
// ...
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line, line + line_length,
    escaped_list_separator<char>('\\', ',', '\"'));

Expecting to use the boost::tokenizer constructor
tokenizer(Iterator first, Iterator last,
          const TokenizerFunc& f = TokenizerFunc())
  : first_(first), last_(last), f_(f) { }

but GCC 4.9.3 gives me:
no known conversion for argument 1 from 'const char*' to '__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >'

Now, I've seen a couple of related questions in which the answer was forgetting to #include <algorithm> -  but I have included it. Is there some other missing include, or is it another issue?

A: As compiler error says, there is no way to build iterator from const char*. You can fix it by use of std::string:
std::string line = "some string";
// ...
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line.begin(), line.end(),
    escaped_list_separator<char>('\\', ',', '\"'));

A: you have to build the token iterators manually if you don't want to use a container as the search space
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

int main()
{
    const char xx[] = "a,b,c,d,e,f,g";
    auto line = xx;
    size_t line_length = strlen(line);

    using namespace boost;

    auto f = escaped_list_separator<char>('\\', ',', '\"');
    auto beg = make_token_iterator<char>(line ,line + line_length,f);
    auto end = make_token_iterator<char>(line + line_length,line + line_length,f);
    // The above statement could also have been what is below
    // Iter end;
    for(;beg!=end;++beg){
        std::cout << *beg << "\n";
    }
    return 0;
}

A: Since you're using boost, you can do:
#include <boost/utility/string_ref.hpp>
// ...
const boost::string_ref line_(line, line_length);
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line_, escaped_list_separator<char>('\\', ',', '\"'));

and that seems to work. Read more about string_ref and the other utilities here.
Of course, if you have an implementation of the Guidelines Support Library, use string_span (a.k.a. string_view) from there (here's one implementation). It's even making it into the standard library probably.
Update: string_view is in the C++ standard in C++17. Now you can write:
#include <string_view>
// ...
std::string_view line_ { line, line_length };
tokenizer<escaped_list_separator<char> > line_tokenizer(
    line_, escaped_list_separator<char>('\\', ',', '\"'));


text:
Q: Width, Height, and Margin doesn't work in QT Style Sheet in PySide6 So I have a Qt StyleSheet called main.qss in the style sheet I am trying to set width and height it doesn't work it just remains the same. This same thing happens for Margins aswell.
Here is the QSS:
QFrame#mainFrame {
    background-color: #282C34;
}

QFrame#menuFrame {
    background-color: #21252B;
}

QPushButton.menuButton {
    background-color: #21252B;

    padding-left: 12px;
    padding-top: 1px;
    padding-bottom: 1px;

    border: 0;
    font-family: "Times New Roman";
    font-size: 20pt;

    color: #FFFFFF;

    width: 300pt; <-- Problem here
    height: 15px; <-- Problem here
}

QPushButton.menuButton:hover {
    background-color: #282C34;
}

QPushButton.menuButton:pressed {
    background-color: #BD93F9;
}

and here is my QPushButton:
self.menu_toggle_button = QtWidgets.QPushButton(self.menu_frame)
self.menu_toggle_button.setIcon(QtGui.QPixmap("menu_icons/menu.png"))
self.menu_toggle_button.setText("  Hide")
self.menu_toggle_button.setObjectName("menuToggleButton")
self.menu_toggle_button.setProperty("class", "menuButton")
self.menu_toggle_button.setIconSize(QtCore.QSize(20, 20))

So what am I doing wrong?
I know this works because in the Qt Style Sheet Reference, which can be found here: https://doc.qt.io/qtforpython-6/overviews/stylesheet-reference.html?highlight=stylesheet, It says that width, height, and margins are supported for QPushButtton.

A: Your stylesheet doesn't work for two reasons:

*

*the width (and height) properties generally don't apply to widgets, but only to subcontrols, as explained in the docs:

Warning: Unless otherwise specified, this property has no effect when set on widgets. If you want a widget with a fixed width, set the min-width and max-width to the same value.

*the "dot" separator doesn't work as it does in python, but as it does in css: it's a class selector:

.QPushButton
Matches instances of QPushButton, but not of its subclasses.

If you want to match the objectName property, you need the ID selector:
    QPushButton#menuButton {...}

Consider that while Qt stylesheets support those properties, it's generally better to leave those kind of settings to the layout manager and directly use the widget functions (setFixedSize(), setFixedWidth(), setFixedHeight()).
Finally, the margins don't work because you're using the padding. Qt uses the same concept as CSS also for the Box Model:

So, the padding you're setting is between the border of the button and the content (icon and/or text, which is the QStyle SE_PushButtonContents sub element). What you're looking for is the margin.


text:
Q: Solving a two cubic equations system I have this system of two equations I'm trying to solve:
$$-(1+\alpha) x^3 + (\alpha y +1) x^2 - (1+\alpha) \beta^2 x + \alpha\beta ^2 y = 0$$
$$-(1+\alpha) y^3 + (\alpha x +\epsilon) y^2 - (1+\alpha) \beta^2 y + \alpha\beta ^2 x = 0$$
It is easy to see that (0,0) is one solution of this problem, but I'm having trouble in finding the others.
Any ideas?


text:
Q: Shared Hosting, UID, GUID set as Apache I'm on shared hosting and today i discovered there are some backdoor script.. in .htaccess and a php file.
So i went to check via FTP, cannot edit nor delete.
So i checked with direct admin.. the file permission(GUID, UID) is set by APACHE
while rest of file is set by my username,
So my question now is.. the trojan did this is originated from my computer or host side?

A: When the web server writes out a file, it has the UID and primary GID that the web server is running under. As for whose fault this is... it's hard to tell. If the permissions of anything was set to 0777 then it's quite possible that a hole in a script was exploited to write it out.
As for getting rid of it, if you're the owner of the directory it's in then you can rm it, otherwise you'll have to ask the hosting company to get rid of it.


text:
Q: Swift Package Manager with resources compile errors I am trying to use resources inside my Package.swift file:
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "MyPackage",
    products: [
        .library(
            name: "MyPackage",
            targets: ["MyPackage"])
    ],
     targets: [
        .target(
            name: "MyPackage",
            resources: [
               .process("Resources/one.xml"),
               .process("Resources/two.json"),
               .process("Resources/three.json"),
             ]
        )
        .testTarget(
            name: "MyPackageTests",
            dependencies: ["MyPackage"]
        )
    ]
)

When I import and compile the package in another project, I am getting lots of errors, such as:
Cannot infer contextual base in reference to member 'target'

or:
Reference to member 'process' cannot be resolved without a contextual type

The files are located in my package project in Sources -> MyPackage -> Resources
I also tried .copy("Resources/one.xml"), etc
What am I missing?

A: You missed a , after the target close parentheses:
        .target(
            name: "BioSwift",
            resources: [
               .process("Resources/unimod.xml"),
               .process("Resources/aminoacids.json"),
               .process("Resources/elements.json"),
               .process("Resources/enzymes.json"),
               .process("Resources/functionalgroups.json"),
               .process("Resources/hydropathy.json")
            ]
        ), // Here is the missed `,`

Also, you don't need to add files one by one! Instead, you can add a directory:
.process("Resources")


text:
Q: AJAX request with event delegation on parent Hey I'm generating some dynamic HTML form with javscript and to listen event on it I'm using event delegation in the parent element.And it works so far properly.But now when I want to submit a form with ajax I'm not getting a way to get out of it.
HTML - updateForm is parent here
<form id="updateForm" class="py-3" enctype="multipart/form-data">
          <button id="swipe" class="bg-btn hidden-lg-up swipe_btn" style="font-size:1em; float:left;"></button>

                    <input type="file" name="profilePic" class="upload" value="">

                    Ashish Mehra
                    @

                    <input type="text" name="fullname" value="Ashish Mehra" class="form-control">

                    <input type="text" name="username" value="" class="form-control">

                    <textarea name="bio" class="form-control" maxlength="120"></textarea>

                    <button type="button" class="bg-btn btn-save" name="button">Save</button>

        </form>

Javascript
 swipeForm.addEventListener('click',(e)=>{
  if(e.target.classList.contains('btn-update')) showDialog();
  if(e.target.classList.contains('btn-save'))  swipeForm.submit();
  if(!e.target.classList.contains('swipe_btn')) return;
  e.preventDefault();
  swipeForm.classList.toggle('swipe');
  swipe_panel.classList.toggle('index');
});

So when the click on form is on element with btn-save class at that time I want to fire submit event and want to make AJAX request as well.


text:
Q: Ubuntu 20.04 can't detect my Bluetooth headset microphone Microphone of my Bluetooth headset (boat rockerz 255) is not detected by Ubuntu 20.04 in the sound settings, there is only one option i.e. Internal microphone.
EDIT - Bluetooth headset is connected and paired and it is detected as a sound device(I can listen songs with it) but microphone of my headset is not detected by ubuntu in the settings.
Is there any solution for this.


text:
Q: Installed Ubuntu 14.04.1, Keyboard and mouse don't work anymore I had Ubuntu 13.10 which worked just fine. I've decided to try 14.04. I've done an upgrade
and when it finished, it booted to desktop but my keyboard and mouse didn't work at all.
So I've decided to try a clean install instead. I've downloaded the iso for 14.04.1 (64 bit), checked it's md5 checksum and made a live usb drive from it. It booted just fine and finished the installation without issues. When finished, it booted to the desktop but again, the mouse and keyboard don't work at all.
I've tried the advanced options, managed to boot using the failsafeX option and the mouse and the keyboard both worked. They also show up with lsusb.
The mouse and the keyboard are wireless, made by logitech.
What can I do now? I suspect this is a driver issue but I don't know linux well enough to tell compare configurations during regular boot which doesn't work and the live version which does.

A: I too had this problem not 10 minutes ago. The way I solved it is by rebooting into an older version of the GNU/Linux kernel (It should have an option for that in grub). Then running sudo apt-get dist-upgrade.


text:
Q: What is the default encoding when saving a text file When saving a text file client gets 'Â' character infront of every currency sign.
I tried the following but still getting strange characters
using (StreamWriter sr = new StreamWriter(path, false, System.Text.Encoding.UTF8))
{
    sr.Write(text);
}
using (StreamWriter sr = File.CreateText(path))
{
    sr.Write(text);
}

any suggestions on how to save a file without any encoding?

A: StreamWriter with a stream as input would default to UTF-8 according to the documentation.

This constructor creates a StreamWriter with UTF-8 encoding without a Byte-Order Mark (BOM), so its GetPreamble method returns an empty byte array.

A: This depends on your computer's local settings. If you want to be sure everything is saved as you intended, you should specify the encoding yourself.
See: http://msdn.microsoft.com/en-us/library/system.text.encoding.default.aspx

A:
any suggestions on how to save a file without any encoding?

That question is meaningless; the "encoding" is the process of translating string characters to bytes to store/transfer (for example on disk). Any text content has to have an encoding. If you have saved it as UTF8, then the person reading it must also be reading it as UTF8. You could try including a BOM:
... new StreamWriter(path, false, new UTF8Encoding(true))

Alternatively, find out what encoding/code-page YOUR MACHINE is configured to use by default, and use that (it is Encoding.Default); for example:
... new StreamWriter(path, false, Encoding.Default)

If your user indicates that they need it in code-page 874 (aka "Thai"), then you would use:
... new StreamWriter(path, false, Encoding.GetEncoding(874))


text:
Q: HighCharts Column Chart Spacing Between Columns I am creating a column chart using highcharts, I need to specify the width of the column and I am able to achieve that using the plotOptions.column.pointWidth property, after that I need to specify the distance between the columns in pixels, and I don't find anything in the API about it, I tried using plotOptions.column.groupPadding and plotOptions.column.pointPadding but they don't work if the column width is fixed. Please let me know how to achive that.
In addition to specifying the space between columns, I would like to give the columns a background color that spans the entire y-axis.
Do you mean something like in this:

A: Unfortunately you can set or fixed width for columns (as you are using) or floating width using groupPadding and pointPadding. Highcharts doesn't provide option to set fixed width for bars and between them. You can create an idea here: http://highcharts.uservoice.com/forums/55896-general


text:
Q: Memory leak in SBCL's REPL I'm somewhat baffled by the following behaviour of SBCL garbage collector in REPL. Define two functions:
(defun test-gc ()
  (let ((x (make-array 50000000)))
    (elt x 0)))

(defun add-one (x) (+ 1 x))

Then run
(add-one (test-gc))

I would expect that nothing references the original array anymore. Yet, as (room) reports, the memory is not freed. I would understand, if I ran (test-gc) directly, then some reference could have been stuck somewhere in SLIME or in
(list * ** ***)

But was is the case here? Thanks, Andrei.
Update Some time ago I filed a bug. It was recently confirmed. See:
https://bugs.launchpad.net/sbcl/+bug/936304

A: Just because nothing references the objects anymore doesn't mean that the memory will be reclaimed. The garbage collector will be run some time in the future, and often the only guarantee that you get is that it will be run before you get an out of memory error.
Another thing that may happen here is that you are looking at the Lisp process memory usage. When memory is CG'ed it is generally not returned to the operating system. Instead, the memory is simply marked as free on the heap, and can be used in future memory allocations.

A: SBCL only...
(gc :full t)
This will forcibly kick off a garbage collection across all generations. I noticed SBCL was holding onto a ton of memory a few days ago and used this to drop the memory down to the "true" usage.
I then wrote an ensure-gc macro to wrap my garbagey computation & experimentation stuff in. I'll paste it in when I get home if I remember... it's nothing fancy.


text:
Q: Apple Mach-0 linker error duplicate I have written a straight forward program, but getting duplicate symbol linker error (error below) There is nothing additional in the .h file excepting for the @interface Fraction : NSObject @end
I am rather new to xcode.
//SAMPLE CODE

#import "JTViewController.h"

@interface Fraction ()

-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;

@end

@implementation Fraction

{
    int numerator;
    int denominator;
}

-(void) print
{
    NSLog (@"%i/%i", numerator, denominator);
}

-(void) setNumerator:(int)n
{
    numerator = n;
}

-(void) setDenominator:(int)d
{
    denominator = d;
}

@end

int main (int argc, char * argv[])
{
    @autoreleasepool {

        // Create an instance of Fraction and initialise it

        Fraction *myFraction = [[Fraction alloc] init];

        //Set Fraction to 1/3

           [myFraction setNumerator: 1];
            [myFraction setDenominator: 3];

            //Display the fraction using the print method

            [myFraction print];
        }

        return 0;
    }

This is the error
Ld /Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Products/Debug-iphonesimulator/BrandNew.app/BrandNew normal i386
    cd /Users/jamesmurray/AppsDev/BrandNew
    setenv IPHONEOS_DEPLOYMENT_TARGET 6.1
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk -L/Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Products/Debug-iphonesimulator -F/Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Products/Debug-iphonesimulator -filelist /Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Intermediates/BrandNew.build/Debug-iphonesimulator/BrandNew.build/Objects-normal/i386/BrandNew.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=6.1 -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Products/Debug-iphonesimulator/BrandNew.app/BrandNew

duplicate symbol _main in:
    /Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Intermediates/BrandNew.build/Debug-iphonesimulator/BrandNew.build/Objects-normal/i386/main.o
    /Users/jamesmurray/Library/Developer/Xcode/DerivedData/BrandNew-akqlirretjwoeuaqkrwlbqmlqxlc/Build/Intermediates/BrandNew.build/Debug-iphonesimulator/BrandNew.build/Objects-normal/i386/JTViewController.o
ld: 1 duplicate symbol for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have no idea where it came from. Any assistance would be appreciated.

A: Like the linker error says, you have two main() functions; one in main.m and one in JTViewController.m.
Remove the one in JTViewController.m (move the functionality into main.m).

A: There is nothing special about main here. You can only have one globally visible non-common symbol in your object files. Non-static functions are globally visible and non-common symbols, hence you can only have a function with a specific name defined only once. For example:
a.c:
int func() { ... }

b.c:
void func(int arg) { ... }

When both files are compiled, it creates two globally visible symbols with the name of func (with whatever decoration the compiler might apply to the symbol), despite the difference in the argument lists and the return types. As the linker tries to resolve all symbol references in order to produce the final executable, it faces the hard choice of selecting the right version of func, so it takes the most direct approach - simply gives you an error about duplicate symbol definition and bails out.
This is not a requirement unique to the C language (and Objective-C is basically a runtime extension of C) as it is imposed by the system linker. It also translates to many other languages like Objective-C, C++, Fortran, Pascal, etc. In C++ function symbols are decorated according to the namespace they live in and the list of their arguments (the former enables function overloading), but again one cannot have two functions with the same list of arguments in the same namespace defined in different source files.
Usually C and C++ functions are compiled to globally visible symbols unless the static modifier is applied:
a.c:
static int func() { ... }

b.c:
void func(int arg) { ... }

This would not result in a global symbol func in a.o clashing with the one in b.o and the linker would not complain. It would also work if rather func in b.c is given the static treatment or if both functions are static.


text:
Q: Why do I get an error when deleting entries from Bash history? I have some commands in my Bash history that I want to remove.
I can find them with history | grep "command with password" then remove them with history -d <line-number>
However, when I try to delete them in bulk by piping them to xargs like this I get an error:
history | grep "command with password" | awk '{print $1}' | sort -r | xargs history -d
xargs: history: No such file or directory

I thought that xargs would go through the list of line numbers and send it one by one to the history -d command.
What is causing this error?
NB: I know there are other ways to delete the history, the question is purely to improve my understanding of how xargs works and what I am doing wrong that is causing the error.

A: The error is raised because xargs cannot find a history command. It is a shell builtin, as you can confirm with type history, thus not visible to xargs. Try
echo 1 | xargs history -d; echo $?

The return value is 127. In man xargs, EXIT STATUS section:
0 if it succeeds
123 if any invocation of the command exited with status 1-125
124 if the command exited with status 255
125 if the command is killed by a signal
126 if the command cannot be run
127 if the command is not found
1 if some other error occurred.

Expanding on ilkkachu's comment, in principle you could invoke Bash and call history from the spawned shell.
echo 1 | xargs -I {} bash -c 'echo $HISTFILE; history' bash {}

The above command does not raise an error, after all the builtin history is available to the Bash shell. However, from that same command one also finds that HISTFILE is unset and history outputs nothing: The history is not enabled on a non-interactive shell. Again, you could activate it with the set builtin, export HISTFILE and HISTFILESIZE... But we don't want a headache. Editing .bash_history directly is the straightforward way to go.


text:
Q: How to add content to Wordpress page? When I create a new page.... I want to write some text on it in a box... But when I will fill in the box on the Add new page tab it doesn't show up. Where has it gone and how to I get it to appear?

This must be so stupidly easy, but I can't understand why it doesn't appear. Any ideas?

A: You have selected the page template - Blog modern layout. Try set the template to default because it might be a problem with the blog template.

A: To show up the page content
After writing it
Just press on update button in the left

A: Some themes will only display posts set in a certain category on certain pages (such as the homepage). From the description on themeforest.net (see How can I create the portfolio navigation (filtering) ?), I think the theme you're using needs specific categories for portfolio browsing to work.


text:
Q: Proving that a determinant is non zero Show that the following determinant is non-zero:
$$\overbrace{ \begin{vmatrix}
1 & 1 & \dots & 1\\
2^{m+1}-1^{m+1} & 2^m-1^m & \dots & 2^1-1\\
3^{m+1}-2^{m+1} & 3^m-2^m & \dots & 3^1-2^1\\
\vdots & \vdots & \ddots &\vdots \\
(m+1)^{m+1}-m^{m+1} & (m+1)^m-m^m & \dots & 1 \\
\end{vmatrix}}^{m+1 \text{ times}} \neq 0$$
I tried to proceed by induction but I couldn't find a way to reduce it to a smaller determinant of the same  type.
I don't know any other ways to proceed(maybe show it is invertible by construction of its inverse?)
Any help would be appreciated. Thank you.


text:
Q: How to split up authors (lists) into columns? I would like to have the authors split up into columns of multicols.
The problem is I don't get the \value{listtotal} to define the count of columns dynamically.
So, for one author there should be only one column, for two authors two columns and so on.
\documentclass{scrartcl}
\usepackage{filecontents}
\usepackage{multicol}
\setlength{\columnseprule}{3pt}
\usepackage{biblatex}
\begin{filecontents}{\jobname.bib}
@book{example1,
author = {Author, A.}}

@book{example2,
author = {Author, A. and Buther, B.}}

@book{example3,
author = {Author, A. and Buther, B. and Cuthor, C.}}
\end{filecontents}
\addbibresource{\jobname.bib}

\renewcommand*{\multinamedelim}{
  %\hfil.    %this is working but not wanted
  \par\columnbreak}
\let\finalnamedelim\multinamedelim

\newcommand\name{}
\newcommand\getname[2][\name]{%
    \begin{multicols}{3} %\value{listtotal} ???
    \citename{#1}{#2}%
    \end{multicols}}

\begin{document}
% one multicol-environment
\def\name{example1}
\getname{author}

% two multicol-environment
\def\name{example2}
\getname{author}

% three multicol-environment
\def\name{example3}
\getname{author}

\end{document}

A: As explained in the comments the counter listtotal is only populated with the value you need in the specific context of biblatex list printing. In particular it is not available outside of list printing in biblatex, much less outside of biblatex itself. You need to get hold of the value before you start your multicolumn. That could be done using a fake citation command.
I must say that I find the interface/argument structure of the macro \getname really confusing, but I assume that it is useful for the purpose you designed it for.
Note that multicols still provides two columns even if the argument is 1. You have to treat that case separately.
\multicolumnauthor is the solution I would use, but it has the drawback of adding additional space between several multicols because of \leavevmode, so that might not be applicable to you.
\documentclass{scrartcl}
\usepackage{filecontents}
\usepackage{multicol}
\setlength{\columnseprule}{3pt}
\usepackage{biblatex}
\begin{filecontents}{\jobname.bib}
@book{example1,
author = {Author, A.}}

@book{example2,
author = {Author, A. and Buther, B.}}

@book{example3,
author = {Author, A. and Buther, B. and Cuthor, C.}}
\end{filecontents}
\addbibresource{\jobname.bib}

\DeclareDelimFormat{multinamedelim}{\endgraf\columnbreak}
\DeclareDelimAlias{finalnamedelim}{multinamedelim}

\DeclareCiteCommand{\getnumberofauthors}
  {}
  {\xdef\numofnames{\the\value{author}}}
  {}
  {}

\newcommand\name{}
\newsavebox{\discardbox}
\newcommand\getname[2][\name]{%
  \def\numofnames{1}%
  \sbox{\discardbox}{\getnumberofauthors{#1}}%
  \begin{multicols}{\numofnames}
  \citename{#1}{#2}%
  \end{multicols}}

\DeclareCiteCommand{\multicolumnauthor}
  {}
  {\ifnumgreater{\value{author}}{1}
     {\begin{multicols}{\value{author}}
      \printnames{author}%
      \end{multicols}}
     {\printnames{author}}}
  {}
  {}

\begin{document}
% one multicol-environment
\def\name{example1}
\getname{author}

% two multicol-environment
\def\name{example2}
\getname{author}

% three multicol-environment
\def\name{example3}
\getname{author}

\multicolumnauthor{example1}
\multicolumnauthor{example2}
\multicolumnauthor{example3}
\end{document}


text:
Q: Issue with two versions of python Problem having two versions of python on my Mac and them interacting. I have the following python locations
python is /anaconda3/envs/fenicsproject/bin/python
python is /usr/bin/python
and when I try to run a script. I get the following error:

Fatal Python error: PyThreadState_Get: no current thread
Abort trap: 6

I have googled some solutions and have found some posts saying I should try
env PYTHON_CONFIGURE_OPTS="--enable-framework"  #or
env PYTHON_CONFIGURE_OPTS="--enable-shared"

This is they type of code I try to run
#Import packages
import dolfin as dl

I installed the env fenics by following the directions here

A: The google search possibly found Homebrew + Python on mac os x 10.8: Fatal Python error: PyThreadState_Get: no current thread importing mapnik however I was unable to find the library that links to a wrong version of python using otool.
I also found https://github.com/enthought/mayavi/issues/552 which suggests pinning to a different version of python.
Based on the install notes for hippy, https://hippylib.readthedocs.io/en/latest/installation.html then where they say conda create -n fenicproject ... you need to substitute the following:
conda create -n fenicsproject python==3.5.1
conda install -n fenicsproject -c conda-forge fenics==2017.2.0 \
               mpi4py matplotlib scipy sympy==1.1.1 jupyter

After this, python -c 'import dolfin' no longer fails. It might also be possible to use a later version of python (I only tried 3.5.1).

A: What OS are you using? That will largely determine the specifics of how to go about correcting this issue, but the key here is which Python version the system path points to and what Python version your IDE is pointing to.
What you largely want to avoid is a situation where you are running Python scripts via your native system Python (2, likely).
Check which version of Python your IDE is using (from: How do I check what version of Python is running my script?):
import sys
print(sys.version)

Is the first number a 2? Did you want to use Python 2?
Next, let's check what version your system currently defaults to. If Ubuntu/Linux, use:
python -V

Is this expected? If not, you may need to change your system environmental variables to point to the correct Python version. The solution to this is OS dependent. If Windows, search "Edit Environmental Variables for Your Account" -> "Environmental Variables" -> "Path" , be sure it either points to Anaconda or the correct Python version; if Ubuntu/Linux, check your .bashrc file:
gedit ~/.bashrc

to see if the system points to the correct Python variable. If using a Mac, I formally apologize.


text:
Q: Access to head tag in content pages (ASP.NET MVC) I want to access to <head> tag section in my content pages (ASP.NET MVC).
For example, I want to put a CSS file link in the <head> tag in only a few content pages. How do I do this?

A: You want to use sections.
In your shared layout, usually _Layout.cshtml, add an RenderSection like this
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
     @RenderSection("css", required: false)
</head>

Then in the content page you want to apply your css to, add the following
@section css{
    <!-- whatever stylesheets you want to link to your content page-->
    <link rel="stylesheet" href="/SomeStyles.css">
}

Now when your content page is rendered your page specific css will be added.


text:
Q: Extract string after the last slash in perl i am using perl regular expression to match everything after the last slash. after reading the perl doc, i realised that following can be the code.
use strict;
use warnings;
my $a = "E:/one/two/abc.dll";
if ($a =~ m/([^/]+$)/)
{
 print " the value is: $a  \n";
}

but i am getting last string as : abc.dll. what could be the issue ? Thanks.

A: Your code will give syntax error Because of the unescaped  /. First you should escape the \/ or use other delimiters.
Then in your print statement you are printing the $a so you will get the full  data.
You should use $& to print the matched pattern or $1 to print the first grouped element.
In my below code I used $1.
use strict;
use warnings;
my $data = "E:/one/two/abc.dll";

if ($data =~ m/([^\/]+)$/)
{
   print " the value is: $1  \n";
}

And then please avoid using $a and $b as a variable name this won't give the syntax error or warning. But these are reserved keywords for sort.

A: This is a good job for split. The below example splits the line on a slash character into a list, then simply extracts the last entry (in this case, abc.dll):
my $file = (split '/', $data)[-1];

A: The thing you have looks like a path. If that's true, you'd be better off using a module that's designed to parse paths in a portable way.
All examples below assume use of strict and warnings.
File::Spec
use File::Spec;
my ($volume, $dirs, $file) = File::Spec->splitpath('E:/one/two/abc.dll');

File::Basename
use File::Basename;
my ($file, $dirs) = fileparse('E:/one/two/abc.dll');

Path::Tiny
use Path::Tiny;
my $path = path('E:/one/two/abc.dll');
my $file = $path->basename;
my $dirs = $path->parent->stringify;


text:
Q: Resetting databases with having OneToOneField crossing different applications in Django I'm getting the following error when I run ./manage.py reset app1:
Error: Error: app1 couldn't be reset. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlreset app2'. That's the SQL this command     wasn't able to run.
The full error: (1217, 'Cannot delete or update a parent row: a foreign key constraint fails')

with a model which has OneToOneField with another model in a different app (let's say app2). I'm using MySQL InnoDB. More accurately, OneToOneField is declared in app2's model.
How do I get rid of this error?
Update:
The output of sqlreset command is:
(app1)
BEGIN;
DROP TABLE `app1_instance`;
DROP TABLE `app1_instancegroup`;
CREATE TABLE `app1_instancegroup` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    -- some more fields
)
;
CREATE TABLE `app1_instance` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `belongs_to_id` integer NOT NULL,
    -- some more fields
)
;
ALTER TABLE `app1_instance` ADD CONSTRAINT `belongs_to_id_refs_id_455b868f` FOREIGN KEY (`belongs_to_id`) REFERENCES `app1_instancegroup` (`id`);
CREATE INDEX `app1_instance_belongs_to_id` ON `app1_instance` (`belongs_to_id`);
COMMIT;

(app2)
BEGIN;
DROP TABLE `app2_team`;
CREATE TABLE `app2_team` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `instance_group_id` integer NOT NULL UNIQUE,
    -- some more fields
)
;
ALTER TABLE `app2_team` ADD CONSTRAINT `instance_group_id_refs_id_39493b52` FOREIGN KEY (`instance_group_id`) REFERENCES `app1_instancegroup` (`id`);
COMMIT;

A: One step that can make manually resetting easier is (and avoid the dread ERROR 1217):
SET foreign_key_checks = 0

From http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html:

InnoDB does not allow you to drop a
  table that is referenced by a FOREIGN
  KEY constraint, unless you do SET
  foreign_key_checks = 0. When you drop
  a table, the constraints that were
  defined in its create statement are
  also dropped.


text:
Q: When calling a object function without the parenthesis, how could it display a custom message instead of returning entire function? I am creating a uniquely designed Javascript API called Javascript-X. Instead of using the conventional method to make an API, I am creating the whole API Inside of a single variable using an object tree.
This may look fine, "$jx.ex()" returns 'Hello World', However if you type "$jx.ex" it returns the entire function. Run the code snippet to see.
The question is, can you customize the message that displays when you type "$jx.ex"?

$jx = {
  ex: function() {
    return ('Hello World.')
  }
};
console.log($jx.ex());
console.log($jx.ex.toString())

A:
When calling a object function without the parenthesis, how could it display a custom message instead of returning entire function?

When referencing an object function without parentheses, unless you're using new, you're not calling it, you're just referencing it. E.g.:
// There are no function calls here
var x = $jx.ex;

If users of your API do the above, x will be a reference to the function, not a string.

The question is, can you customize the message that displays when you type "$jx.ex"?

If you're doing this in the console and seeing the entire function, it may be that the console coerced to string (which calls toString), or it may be that the console did something at a lower level. If the former, we can override that by giving the function a new toString:

$jx = {
  ex: function() {
    return ('Hello World.')
  }
};
$jx.ex.toString = function() {
    return "This is the custom 'message'.";
};
console.log($jx.ex());           // A call
console.log($jx.ex);             // Not a call, results will
                                 // vary from console to console
console.log($jx.ex.toString());  // toString directly
console.log(String($jx.ex));     // toString indirectly

A: Consider below example :
function Multiply(operator, operand) {
    return operator * operand;
}

This could equally be written:

Multiply = function(operator, operand) {
    return operator * operand;
}

While in the first example, the implication may not be obvious, the second example shows more clearly that we're assigning a function which has 2 parameters to a variable called Multiply, and this concept of functions as assignments is common throughout javascript. This is a small demonstration of the fact that functions are "first class citizens", that is, they can be passed around exactly as if we were passing around values.
So now to the difference of assignment:
var operator = 3;
var operand = 4;
var ret = Multiply(operator, operand);

At the point of defining the ret variable, Multiply is executed and the return value is assigned - ret becomes equal to 12.
Lets try that again a different way:
var operator = 3;
var operand = 4;
var ret = Multiply;

Now, at the point of defining ret, ret becomes your Multiply function as opposed to being the result obtained from your Multiply function. Calls to ret() will cause your Multiply function to be executed, and you can call it exactly as if you'd called Multiply(operator, operand):
var out = ret(3, 4);

is the same as
var out = Multiply(3, 4);