text:
Q: Why doesn't == work on String? I just started Java programming. I love it so far, but I have been stuck on this problem for a while.
When I run this code, whenever I type in "boy" it will just respond with GIRL:
import java.util.Scanner;

public class ifstatementgirlorboy {
    public static void main(String args[]) {
        System.out.println("Are you a boy or a girl?");
        Scanner input = new Scanner(System.in);
        String gender = input.nextLine();

        if(gender=="boy") {
            System.out.println("BOY");
        }
        else {
            System.out.println("GIRL");
        }
    }
}

Why?

A: When comparing objects of type String, you should use the equals method instead of operator ==.  equals will compare the values of String objects while == checks to see if they are the same object in memory.
So instead of:
if(gender=="boy")

use
if(gender.equals("boy"))

A: Use the String.equals(String otherString) function to compare strings, not the == operator.
This is because the == operator only compares object references, while
the String.equals() method compares both String's values i.e. the sequence of characters that make up each String.
equals() method from Source code of String:
        public boolean equals(Object anObject) {
1013        if (this == anObject) {
1014            return true;
1015        }
1016        if (anObject instanceof String) {
1017            String anotherString = (String)anObject;
1018            int n = count;
1019            if (n == anotherString.count) {
1020                char v1[] = value;
1021                char v2[] = anotherString.value;
1022                int i = offset;
1023                int j = anotherString.offset;
1024                while (n-- != 0) {
1025                    if (v1[i++] != v2[j++])
1026                        return false;
1027                }
1028                return true;
1029            }
1030        }
1031        return false;
1032    }

So you should write
if(gender.equals("boy")){

}

or to comapre with regardless of case
if(gender.equalsIgnoreCase("boy")){

}

and for null safety
if("boy".equals(gender)){

}

Future reference:
String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

Here   s1 == s2 == s3 but s4 != s5
Where as
anyOfAbove.equals(anyOtherOfAbove); //true

A: Use equals instead of ==
if("boy".equals(gender)){

}

use equals To compare the value. while == is compare object reference.

A: String a,b;

a==b;

here references(addresses) of both string objects are compared
a.equals(b);

here contents of both strings are compared

A: In Java, strings are objects (String). Variables which contain objects are references. If you compare two objects with == operator, true is returned only if they are the same objects (in memory). But in your code they aren't ("boys" is an instantialized String on the fly).
There is, however, a method String.equals(), which compares two strings and returns true if they have the same characters in the same order, not if they are the same objects.
Correct code here:
import java.util.Scanner;

public class ifstatementgirlorboy {
    public static void main(String args[]) {
        System.out.println("Are you a boy or a girl?");
        Scanner input = new Scanner(System.in);
        String gender = input.nextLine();

        if (gender.equals("boy")) {
            System.out.println("BOY");
        }

        else {
            System.out.println("GIRL");
        }
    }
}

You can also swap the two strings (the advantage is that it prevents NullPointerException from being thrown if gender == null):
"boy".equals(gender)

To ignore the case of letters in comparison, use equalsIgnoreCase() instead.

A: you cant compare strings like that in java, You need to use
if (gender.equals("boy"))

for it to work. Your way is comparing the object rather than the content

A: You're using reference equality there. The == is literally comparing the 2 references. i.e. are they the same object.
You need to use the equals() method, which (in this case) will compare the contents of the two strings. See here for more info.


text:
Q: Flutter: Specify and use an asset within a package What's the general approach specifying and referencing an asset within a Flutter/Dart package?
I have tried various approaches and I always get the error Unable to load asset: path/to/image when trying to create an image widget: Image(image: AssetImage('path/to/image')).
My goal is to create custom buttons library and some of them should come with custom icons (images).
I would like to use the images within my own package, not outside in an app and expose complete button widgets instead.
For example, let's say I'm creating a package called wolf:

*

*wolf/

*wolf/lib/wolf.dart

*wolf/lib/src/Wolf.dart

*wolf/pubspec.yaml
Where in the above directory structure do you put an asset, how do you define it in pubspec.yaml (if necessary) and how do you use it in wolf/lib/src/Wolf.dart?

A: In your pubsec.yaml, you need to include the assets, like this-
flutter:
  assets:
    - assets/logos/google_light.png
    - assets/logos/google_dark.png

Create a Widget in your package and use it. Use the name of your package (assuming name of your package is flutter_mypackage_button) in the package attribute of AssetImage, like this-
Image(
    image: AssetImage(
        button == Buttons.Google
            ? 'assets/logos/google_light.png'
            : 'assets/logos/google_dark.png',
        package: 'flutter_mypackage_button',
    ),
    height: 36.0,
)

I hope this should do it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Webpack style-loader insert SCSS into shadow-dom I am trying to configure webpack to insert my custom SCSS styles into a shadow DOM node instead of at the head of the document. The location of the shadow DOM node will not always be consistent, so the ability to pass an element to insert the styles into dynamically is key.
The documentation references a function that can be used in style-loader configuration called insert that allows a function to be created in order to specify where the styles are to be added. Importing the styles and calling the use function with a target parameter is how the example specifies the other element for the styles to be added to.
The issue I am having is the second parameter called options in the insert function is always undefined. The element argument is present and contains the correct custom styles tag contents, but the options object that specifies where to add these styles to is never defined so the styles end up getting added to the document head which is not the desired outcome.
Here is my relevant webpack code:
    module: {
    rules: [
        {
            test: /\.css$/i,
            exclude: /\.lazy\.css$/i,
            use: ['style-loader', 'css-loader'],
        },
        {
            test: /\.scss$/,
            exclude: /\.lazy\.scss$/i,
            use: ['style-loader', 'css-loader', 'sass-loader'],
        },
        {
            test: /\.lazy\.scss$/i,
            use: [
                {
                    loader: 'style-loader',
                    options: {
                        injectType: 'lazyStyleTag',
                        insert: function insertIntoTarget(element, options) {
                            var parent = null;
                            if (!options) {
                                parent = document.head;
                            } else {
                                parent = options.target;
                            }
                            parent.appendChild(element);
                        },
                    },
                },
                'css-loader',
                'sass-loader',
            ],
        },
       ]
      }

Here is the relevant react code:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './styles/Component.lazy.scss';

const Component = () => {
    return (

Component in shadow DOM

    );
};

if (document.querySelector('div.ComponentClass') === null) {
    const container = document.createElement('div');
    container.className = 'ComponentClass';
    document.body.appendChild(container);

    const shadow = document.querySelector('div.ComponentClass').attachShadow({ mode: 'open' });
    const target = document.querySelector('div.ComponentClass').shadowRoot;

    styles.use({ target });

    ReactDOM.render(<Component />, target);
}

Is there anything I am doing wrong here that is causing the options parameter to always be undefined?
I have also tried a few variations of passing different things into the styles.use functions as well, such as { options: { target: ... } } and it seems that only the element parameter is passed in no matter what

A: Have you tried upgrading your style-loader version? Here's the PR which added this feature:
https://github.com/webpack-contrib/style-loader/pull/535
Version 3.0.0 doesn't have it. Version 3.3.1 definitely does support passing arguments to use.


text:
Q: Unable to add to header of linkedlist I've got a LinkedList node struct defined as such:
struct intnode {
    int item;
    struct intnode *next;
};
typedef struct intnode IntNode;

Which I am using to do some simple sorting. However, in creating this linked list, I am having difficulty with scope. In my main function I've got a Null header IntNode object to serve as the first element in the list, however I can't modify it within my insert function, despite the fact that I'm passing a pointer to it. The code never reaches the print statement saying the list is no longer empty, which I am confused by. Does this have something to do with defining a new IntNode element to add within the insert function which is then thrown away after the function is done?
int main() {

  IntNode *header = NULL;

  printf("Enter some numbers, ending with -1: ");
  int a;

  while(a != -1) {
    scanf("%d",&a);
    if(a != -1) {
      insert(header, a);
    }
  }
  return 0;
}

IntNode *createNode(int val) {
  IntNode *new_node;
  new_node = malloc(sizeof(IntNode));
  new_node->item = val;
  return new_node;
}

void insert(IntNode *header, int val) {

  IntNode *newNode = createNode(val);

  if(header == NULL) { //list is empty, so insert at front
    printf("list still empty\n");
    newNode->next = header;
    header = newNode;
    printf("%d",header->item);
  } else {
    printf("the list is no longer empty...");
    //do more stuff here
    }
}

A: If you want to modify a pointer, you need to pass a pointer of that pointer. Therefore
insert(header, a);

should be
insert (&header, a);

and adjust your insert() function accordingly.


text:
Q: IS there any way i can make this shorter I am learning how to use untiy in my spare time by reading a beginners book and looking up stuff online in the book there is a exercise that asks me

to create a script that outputs the numbers from 1 to 10 in to the console but dose not output any multiple of 3 and 5 instead outputting the phrase "programming is awesome "

while i have achieved this task by using this code
using UnityEngine;
using System.Collections;

public class Loops : MonoBehaviour {

// Use this for initialization
void Start () {

    for(int i = 1; i <= 10; i++)
    {
        if(i == 3 )
            print ("Programming is Awesome!");
        else if (i == 5)
            print ("Programming is Awesome!");
        else if (i == 6)
            print ("Programming is Awesome!");
        else if (i == 9)
            print ("Programming is Awesome!");
        else if (i == 10)
            print ("Programming is Awesome!");
        else
            print (i);
    }
}

}

i was wondering if there was any way to achieve the same result only by using less lines of code

A: You want to use the modulus (aka modulo) operator (%) for this task. It returns the remainder of a division, so when the result of a modulus operation is 0 you know you have a multiple of the divisor.
for (int i = 1; i <= 10; i++)
{
    if(i % 3 == 0 || i % 5 == 0)
        print("programming is awesome");
    else
        print(i);
}

A: The point of this exercise is that you should calculate the multiples, not just make one condition for every value that you know is a multiple.
Use the modulo operator to check it a number is an even multiple of another. This shows what the modulo operator returns for some values:
 i    i % 3
------------
 1      1
 2      2
 3      0
 4      1
 5      2
 6      0
 7      1

As you see, i % 3 evaluates to 0 when i is a multiple of three. You can use that to check if the number is a multiple of three:
if (i % 3 == 0) {
  print ("Programming is Awesome!");
}

Now you should be able to do the same for five also, and incorporate it in your code.

A:   for (int i = 1; i <= 10; i++)
        {
            print((i % 3 == 0 || i % 5 == 0)? "programming is awesome" : i));
        }

check out also using ternary operator.

A: Ways of doing this
if(i == 3 || i == 5 || i == 6 || i == 9 || i == 10){
    print ("Programming is Awesome!");
}
else {
    print (i);
}

Better way By Using the modulo operator
if( i % 3 == 0 || i % 5 == 0){
    print ("Programming is Awesome!");
}
else {
    print (i);
}

Use can also try
print((i % 3 == 0 || i % 5 == 0)? "Programming is Awesome!" : i));


text:
Q: Give a two-point form for the line through $P(1, 3)$ and parallel to $v = (5, 4)$ My assignment is asking me to give a two-point form for the line through $P(1, 3)$ and parallel to $v = (5, 4)$.
I'm aware that the two-point form is $x(t)=(1-t)p+tq$, and the question has given me one point $P(1, 3)$. Thus, so far I have $x(t)=(1-t)(1, 3)+tq$.
But how can I find the second point $q$ if they haven't given it to me?

A: The line is
$$(x, y)=(1, 3)+t(5, 4)$$
with $t\in\mathbb{R}$
If $p=(x_1, y_1)$ and $q=(x_2, y_2)$, then $(x_1, y_1)=(1, 3)+t_1(5, 4)$ and $(x_2, y_2)=(1, 3)+t_2(5, 4)$.
Then
\begin{align*}
x(t) &= (1-t)(x_1, y_1)+t(x_2, y_2)\\
     &=(1-t)((1, 3)+t_1(5, 4))+t((1, 3)+t_2(5, 4))\\
     &=(1, 3)+t_1(5, 4)-t((1, 3)+t_1(5, 4))+t((1, 3)+t_2(5, 4))\\
     &=(1, 3)+t_1(5, 4)-tt_1(5, 4)+tt_2(5, 4)\\
     &=(1, 3)+((1-t)t_1+tt_2)(5, 4)
\end{align*}


text:
Q: Export result R data frame into an Excel file can anyone help me with how to export the result of comparedf() from the arsenal package to an Excel file?
Here is my script:
diff <- diffs(comparedf(mtcars[1:10, ], mtcars[2:11,]))
openxlsx::write.xlsx(diff, "diff.xlsx")

The error message is Error in is.nan(tmp) : default method not implemented for type 'list'

A: diffs function returns certain columns of class 'AsIs' which is of type list.
unlist those columns into a vector before writing them to Excel.
diff[] <- lapply(diff, function(x) if(class(x) == 'AsIs') unlist(x) else x)
openxlsx::write.xlsx(diff, "diff.xlsx")


text:
Q: "Three-hundred forty-two" or "three-hundred and forty-two"? So on this answer here: https://stackoverflow.com/questions/12699791/finding-the-word-version-of-a-number/12700097#comment17146082_12700097
We were having the argument whether it is "three hundred and forty two" or "three hundred forty two".
I am going by British and New Zealand grammar and I believe it has the and in there. I have never in my life heard anyone say "three hundred forty two", only "three hundred and forty two".
So when it comes to numbers, what's the rule?

A: It seems that is the correct usage in British English:
http://www.usingenglish.com/files/pdf/big-numbers-american-and-british-english.pdf
In American English, the use of the and is uncommon for use in the integer portion of the number (I was specifically taught not to use it):
http://www.eslcafe.com/grammar/saying_large_numbers01.html
I was also taught to use and between the integer part and the portion to the right of the decimal point which is spoken as a fraction (two tenths, forty-five hundredths, etc.):
http://www.basic-mathematics.com/writing-decimals-in-words.html


text:
Q: PowerShell System.Windows.Forms disable a certain items in ListBox Is there a way to disable a few items in the System.Windows.Forms.ListBox in PowerShell?
i.e.  ListBox contains:
item-a
item-b
item-c
item-d
item-e

and I like to make for example, item-c and item-e not selectable. Thanks!

A: Short answer: There is no native Disable/Enable items in the ListBox control.
I see two ways to do it:

*

*Have an array of items that you don't want selectable. When handling your click event, check to see if the item  is one that you don't want selected, and do nothing.

*The easier method: Create a custom control. See: How to Disable Selected Item in List Box

A: # Events
$listBox.add_selectedindexchanged({
    foreach ($item in $listbox.SelectedItems) {
        if (***condition for being unselectable***) {
            $listbox.SelectedItems.Remove($item)
            break
        }
    }
}

Every time the user selects an item, this event checks the select items list for "unselectable" items (which you specify with the condition). if found, they are removed from the list. The "break" is included to avoid the non-terminating error when the foreach loop runs on a list that has been changed. This solution may not work for Shift-click multi-selection if multiple unselectable items are selected at once, but could be modified (probably).


text:
Q: What config do I have to change in my Eclipse Web project, so that Tomcat redirect URLs without any path to the project URL In Eclipse Oxygen I have set up a Web project (facets Dynamic Web Module, Java & JavaScript) with the name MyProject.
When I start up Eclipse's Tomcat (Version 8.5) I can view the site under the project URL http://localhost:8080/MyProject/. So far so good. But how can I configure the Eclipse project that the server's base URL http://localhost:8080 redirects to the project URL?
Bonus question: Is there a way to change the path in the URL without changeing the project name, so that the project URL is, say, http://localhost:8080/FancyOtherName/ instead of  http://localhost:8080/MyProject/?

A: So there are a few options here. You could deploy the application in the root context of the server to get rid of the MyProject in the URL altogether. There are a few ways to do this, but the easiest is to have the .war file from your build be name ROOT.war. This will deploy the application in the server's root context and will get rid of MyProject from the URL. To change the context of the application in your projects URL, you could do so through some configuration of the application (which I don't have enough details to comment on), or through the Tomcat configuration. By deploying the application with the ROOT.war MyProject
will be removed from the URL, but you could add <Context path="" docBase="FancyOtherName"></Context> to the $CATALINA_HOME\conf file in the <Host> tag as well as adding to autoDeploy="false" and deployOnStartup="false" to the host tag so it looks something like this <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="false" deployOnStartup="false">. This will stop the application from deploying twice, once in the root context and once at http://localhost:8080/FancyOtherName/, and will only deploy the application at http://localhost:8080/FancyOtherName/. Good Luck!


text:
Q: File explorer, store path I want to use a file explorer in order to get the path of the element I'll select in this explorer.
Could I use something like this :

<input type="file"  webkitdirectory />

The problematic is :
I would ideally like to limit the selection to folders only, not files.
I want to retrieve the path of the selected folder in order to store it. (I'm using angularjs, so I was thinking of binding it through a model)
Is this possible or is there an alternative suiting my needs ?

A: You can't do it unless you use Java applet or Flash.
Please see this answer for details.

Selecting a file for upload is the best you can do, and even then you
  won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g.
  using SWFUpload as a basis), but it's a lot of work and brings
  additional compatibility issues.


text:
Q: Placeholders are not showing variable values in ValidationMessages.properties file in Hibernate validation I am using Hibernate validation in Spring Boot project. Though I am able to read messages from ValidationMessage.properties file and also arguments in curly braces as {min}, {max}:
Size.accountRequestBean.firmName=size should  be between {min} and {max}

ValidationMessages.properties
Size.accountRequestBean.firmName={0} should  be between {1} and {2}

But when i use Size.accountRequestBean.firmName={0} should  be between {1} and {2} the message displayed is {0} should be between {1} and {2}:

expected :size should  be between 2 and 30.

DemoApplication.java
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter{

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Bean.java
public class Bean {

    @Size(min=2, max=30,message="{Size.accountRequestBean.firmName}")
    private String firmName;
}

Validation dependencies I am Using:
<!-- Hibernate Validator -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.0.0.GA</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.3.1.Final</version>
</dependency>

So please suggest where I am doing wrong?

A: Rename your ValidationMessage.properties file to messages.properties (by default Spring expects to find it under the resources folder) and put the following properties inside it:
bean.hasErrors=Please fix the following errors
bean.firmName=Firm Name
Size.bean.firmName={0} should  be between {2} and {1}

Note the order of precedence here is: code.objectName.fieldName. And objectName must be the same as your class name, so instead accountRequestBean put just bean (as your object Bean.java).

Then, you can omit the message key in @Size annotation. When you use messages.properties file Spring Boot automatically get its messages:
public class Bean {
    @Size(min = 2, max = 30)
    private String firmName;

    // getter, setter
}

Make sure you use @Valid annotation in your controller to use Bean validation, for example:
@RequestMapping(value = "/doBean", method = RequestMethod.POST)
public String doBean (@Valid Bean checkoutCommand, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form";
    }
    return "success";
}

Please look for the complete code example.
You should get something like this:

A: On my project the problem was in this setting:
var messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setUseCodeAsDefaultMessage(true);

after
setUseCodeAsDefaultMessage(false)

all worked


text:
Q: Firebase login throws Error: spawn cmd ENOENT in NodeJS I am trying to set up my Firebase TypeScript application on another system. When I execute firebase login, it throws the following exception:
[debug] [2020-07-10T12:35:28.031Z] ----------------------------------------------------------------------
[debug] [2020-07-10T12:35:28.034Z] Command:       C:\Program Files\nodejs\node.exe C:\Users\gp\AppData\Roaming\npm\node_modules\firebase-tools\lib\bin\firebase.js login
[debug] [2020-07-10T12:35:28.034Z] CLI Version:   8.5.0
[debug] [2020-07-10T12:35:28.034Z] Platform:      win32
[debug] [2020-07-10T12:35:28.035Z] Node Version:  v12.18.2
[debug] [2020-07-10T12:35:28.036Z] Time:          Fri Jul 10 2020 18:05:28 GMT+0530 (India Standard Time)
[debug] [2020-07-10T12:35:28.036Z] ----------------------------------------------------------------------
[debug] [2020-07-10T12:35:28.037Z]
[info] i  Firebase optionally collects CLI usage and error reporting information to help improve our products. Data is collected in accordance with Google's privacy policy (https://policies.google.com/privacy) and is not used to identify you.

[info] i  To change your data collection preference at any time, run `firebase logout` and log in again.
[info]
[info] Visit this URL on this device to log in:
[info] https://accounts.google.com/o/oauth2/auth?client_id=563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com&scope=email%20openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloudplatformprojects.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ffirebase%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&response_type=code&state=3839&redirect_uri=http%3A%2F%2Flocalhost%3A
[info]
    [info] Waiting for authentication...
    [debug] [2020-07-10T12:57:25.170Z] Error: spawn cmd ENOENT
        at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
        at onErrorNT (internal/child_process.js:469:16)
        at processTicksAndRejections (internal/process/task_queues.js:84:21)
    [error]
    [error] Error: An unexpected error has occurred.

On the new system, I am using the following software:

*

*node v12.18.2

*npm v6.14.5

On the old system, I was using the following software:

*

*node v10.16.3

*npm v6.12.0

I have also tried the following:

*

*executing npm install -g firebase-tools@latest

*executing all steps in a separate cmd running as admin.

Everything was working perfectly in my old workspace.

A: Fixed the issue by adding 'C:\Windows\System32' in my environment variable.


text:
Q: Electron - restart app / refresh environment variables I'm currently working on an Electron app which uses a third party software. At some point I'm checking if that software is installed on the user's computer (it has to be in PATH), and if it's not there I just run the installation. As I said, the installation will append a directory to the PATH variable. After this happens, I need to restart the app in order to have access to the updated variables.
I already tried to use relaunch, just as in the docs, but it doesn't refresh the variables:
app.relaunch()
app.exit(0)

If I restart the app manually, then everything works ok.
Does anyone have some ideas ? Thanks.

A: My solution just works for production:
In production, your application could not get your PC's environment variable. So, when you create mainWindow in main.js, you should read environment variables and pass it to process.env variable. After you relaunch the application, it will reload env again as you expected.
Library in use:
https://github.com/sindresorhus/shell-env
https://github.com/sindresorhus/shell-path
import shellEnv from 'shell-env';
import os from 'os';
import shellPath from 'shell-path';

const isDevelopment = process.env.NODE_ENV === 'development';

function createMainWindow() {
  mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    },
    width: 800,
    height: 1000,
  });

  // ...

  if (!isDevelopment) {
    // TODO: if we're running from the app package, we won't have access to env vars
    // normally loaded in a shell, so work around with the shell-env module
    // TODO: get current os shell
    const { shell } = os.userInfo();

    const decoratedEnv = shellEnv.sync(shell);

    process.env = { ...process.env, ...decoratedEnv };

    console.log('DEBUG process.env', process.env);

    // TODO: If we're running from the app package, we won't have access to env variable or PATH
    // TODO: So we need to add shell-path to resolve problem
    shellPath.sync();
  }

  // ...
}

After relaunching the application, the environment variables will be updated.
app.relaunch()
app.exit(0)

Notice: Without check !isDevelopment, after relaunching, the application won't be displayed. I have no idea.


text:
Q: MySQL show all columns while using WHERE clause Sorry if this is a silly question but did not use much SQL lately and can't find much help on this either.
I need to get all rows to show in a result even if the result is 0 or null. The problem I have is because of the WHERE clause (without the WHERE the rows are all displayed but the data is not).
SELECT SUM(c.amount) AS 'total_income', p.ref_id AS 'property'
FROM property p
LEFT JOIN contract c
ON p.id = c.property_ref_id
LEFT JOIN contract_payment cp
ON c.id = cp.contract_id
WHERE cp.paid = 1 AND year(cp.date_paid) = :year
GROUP BY p.id

Displaying the result set without the Where and Bad Data would be like this
array
  0 =>
    array
      'total_income' => null
      'property' => string 'test/0001' (length=9)
  1 =>
    array
      'total_income' => null
      'property' => string 'test/0002' (length=9)
  2 =>
    array
      'total_income' => string '200' (length=3)
      'property' => string 'test/0003' (length=9)
  3 =>
    array
      'total_income' => string '16100' (length=5)
      'property' => string 'test/0004' (length=9)

While this is the result set with the WHERE clause and Good Data but not all rows
array
  0 =>
    array
      'total_income' => string '4200' (length=4)
      'property' => string 'test/0004' (length=9)

Could someone please enlighten me to what modifications could be made to the SQL so as to retrieve my desired data ?

A: The problem is that you're filtering out all the rows with no match in the cp table, because cp.paid can't be 1 when there's no match there.
Change the WHERE clause to:
WHERE cp.contract_id IS NULL OR (cp.paid = 1 AND year(cp.date_paid) = :year)

or move that condition into the ON clause of the LEFT JOIN with cp:
ON c.id = cp.contract_id AND cp.paid = 1 AND year(cp.date_paid) = :year


text:
Q: Can't convert ByteArray from Camera2 to Base64 I can't convert picture taken to readable base64, while starts the same as online converters, it's shorter and about half-way through becomes different.
Code
imageReader = ImageReader.newInstance(600,600, ImageFormat.JPEG, 1)
        //Was switched to lambda
        //imageReader.setOnImageAvailableListener(object: ImageReader.OnImageAvailableListener{
        //            override fun onImageAvailable(reader: ImageReader?) {
        imageReader.setOnImageAvailableListener({ reader ->
            val image = reader?.acquireLatestImage()

            val buffer = image!!.planes[0].buffer
            val bytes = ByteArray(buffer.remaining())
            buffer.get(bytes)

            var file = File(requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES),"img.jpeg")
            var output = FileOutputStream(file)
            output.write(bytes)
            output.close()
            image.close()
            val encodedString: String = Base64.encodeToString(bytes, Base64.DEFAULT);
            println(encodedString)

            pictures.add(encodedString)

            val sound = MediaActionSound()
            sound.play(MediaActionSound.SHUTTER_CLICK)
        }, handler)


text:
Q: Need to replace datetime field in SQL query when it equals 9999-12-31 00:00:00 I have a datetime field called ACTUALCLOSEDATE and this field is equal to 9999-12-31 00:00:00 when a corresponding field called STATUSNUM = 0.  When STATUSNUM is changed to 1 (when the record is closed) the value of ACTUALCLOSEDATE is changed to current datetime.
In my query, I want to replace the value of ACTUALCLOSEDATE when it = 9999-12-31 00:00:00 with 'Still Open' when it dosen't I just want the date.
I have tried code below with errors.  Ideas?  I don't IIF is available SQL 2008 r2, is it? and if so can I use it?
/* This is what I need but it dosen't work in SQL 2008 R2 */
SELECT
IIF (YEAR(ACTUALCLOSEDATE)=9999, "Still Open", ACTUALCLOSEDATE) AS ActCloseDate,
FROM OPPORTUNITY

/* This dosen't work either */
SELECT
CAST YEAR(ACTUALCLOSEDATE)
    WHEN 9999 THEN 'Still Open'
    ELSE ACTUALCLOSEDATE
    END AS Act_Close,
FROM OPPORTUNITY

A: Your column must be of a consistent data type; in your instance, you are trying to conditionally show a date or a varchar.
You can do:
SELECT
    CASE YEAR(ACTUALCLOSEDATE)
    WHEN 9999 THEN 'Still Open'
    ELSE CAST(ACTUALCLOSEDATE AS nvarchar(25))
    END AS Act_Close
FROM OPPORTUNITY

You'll want to possibly use CONVERT to format the date in the ELSE expression into a preferred format.

A: This is the syntax:
SELECT
    CASE WHEN YEAR(ACTUALCLOSEDATE) = 9999
      THEN 'Still Open'
      ELSE CONVERT(VARCHAR, createDate, 120) --Format: yyyy-mm-dd hh:mi:ss(24h)
    END AS Act_Close,
FROM OPPORTUNITY

You need to convert the date column into a varchar so that it is the same type as 'Still Open'

A: IIF is available starting from SQL Server 2012.
You can use the CASE statement in 2008 R2. Note that it's CASE, not CAST.


text:
Q: How can I tell if my program is the one that's focused? I can't find a good answer to this...
What I'm asking specifically is, how can I tell if my program (winforms) is visible to the user, and it's focused? For example, when you use Skype, it can tell whether it is the one focused and visible or not. If you receive a Skype IM and the program is either not visible (hidden behind other windows)/minimized it will make the notification sound. If Skype knows that it's the one with the focus, the top most application, it won't bother to make the notification because it assumes you're using it.
Now, I've tried if (this.Focused == true), but it doesn't seem to work at all. It can't tell that I'm giving focus to Windows Explorer and that my own program is at the back of it, not focused and greyed out at the top.

A: I've just tested it out and it works just the way I wanted it! I can check if Form.ActiveForm is null: if it's null, then it doesn't have focus; if it's not null, it has focus!

A: An easier way of doing what you want is by using events.
Here is an excellent post about that https://stackoverflow.com/a/1786376/2692994
Inside the event, you put whatever you want to do with your form.
^
I added the above since that is probably what Skype uses. If you want to check at any time if it's focused or not, just make a "public bool focused = true;" and set it inside of the events to true or false.


text:
Q: Firestore error within React: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid') The following is my function in which I am trying to filter notes from my Firestore collection by user.uid:
const fetchPost = async () => {
    const queryConstraints = []
    if (user.uid != null) queryConstraints.push(where('userID', '==', user.uid))
    if (user.email != null) queryConstraints.push(where('userEmail', '==',

user.email))
        const q = query(collection(db, 'notes'), ...queryConstraints)
        await getDocs(collection(q))
            .then((querySnapshot)=>{
                const newData = querySnapshot.docs
                    .map((doc) => ({...doc.data(), id:doc.id }));
                setNotes(newData);
                console.log(notes, newData);
            })
    }

Yet, when I try and run this code in the browser, regardless if it is Chrome, Safari, Firefox, I am getting the following error:

Uncaught (in promise) TypeError: Cannot read properties of null
(reading 'uid')
at fetchPost (NoteList.js:66:1)

I am not sure how to fix this error, or really the right question to ask over how ask over why this this is happening.
Previously, I was using the following function:
const fetchPost = async () => {
        await getDocs(collection(db, "notes"))
            .where('userEmail', '==', user.email)
            .then((querySnapshot)=>{
                const newData = querySnapshot.docs
                    .map((doc) => ({...doc.data(), id:doc.id }));
                setNotes(newData);
                console.log(notes, newData);
            })
    }

I was getting the same error previously stated, but at least with this function, if I made any change to user.uid, React's hot reload would refresh the page, and it would bring in the queried data in the console, yet when I F5 the page, the data was not showing with the error message listed above.
Also, when I use the query builder in Firestore with the same parameters, I am able to pull the data I want to display, it is just not pulling/displaying as wanted in my react app.
Any help would be appreciated.

A: You are getting this error because your user is null.

*

*Try to print value of user before accessing id.  You'll know the value of user

*Try to wrap your user.id with if(user) user.id.  This should remove your erros


text:
Q: Date range query with mondrian and olap4j I am using olap4j to query a mondrian cube. I have defined a standard TimeDimension in my schema xml:
    <Dimension name="DateTime" type="TimeDimension">
    <Hierarchy hasAll="true" primaryKey="DateId">
        <Table name="event_date" />
        <Level name="Year" column="Year" type="Numeric" uniqueMembers="true" levelType="TimeYears" />
        <Level name="Quarter" column="Quarter" captionColumn="QuarterLabel" uniqueMembers="false" levelType="TimeQuarters" />
        <Level name="Month" column="Month" captionColumn="MonthLabel" uniqueMembers="false" type="Numeric" levelType="TimeMonths" />
        <Level name="Week" column="Week" uniqueMembers="false" levelType="TimeWeeks" />
        <Level name="Day" column="Day" uniqueMembers="false" type="Numeric" levelType="TimeDays">
            <Property name="DayISO" column="DateIso" dependsOnLevelValue="true" />
            <Property name="DayOfWeek" column="DayOfWeek" dependsOnLevelValue="true" />
        </Level>
    </Hierarchy>
</Dimension>

What I cannot understand is how can I use olap4j to query a range of dates on cubes that have DateTime as a shared dimension.
Does anyone have any examples that can be shared?
Yosi

A: In MDX, you can slice the results by a range of dates like so:
select
    (...)
where
    ([DateTime].[Month].[2] : [DateTime].[Month].[6])


text:
Q: VB.Net: Can't find control type from a collection of controls I'm still new to VB.NET, and trying to find the correct way to simplify some code (with the understanding that it will add to the runtime complexity).
I've defined a Windows Form with a number of fields. The user enters data into those textboxes, checkboxes, etc., then hits the form's "Search" button. My existing (working) code looks at the first input field and passes 4 (or optionally 5) parameters to my BuildSearch function, which returns an SQL Where clause segment based on that first input field. It then repeats the procedure for the remaining input fields, concatenating all of the SQL segments with " AND ", before submitting the request to the server.
My existing code looks like this:
If TxtSort_Key.Text <> "" Or LblSort_KeyOp.Text <> "" Then g$ = g$ & BuildSearch("Sort_Key", "", LblSort_KeyOp.Text, TxtSort_Key)   ' Sort_Key

If TxtFullName.Text <> "" Or LblFullNameOp.Text <> "" Then g$ = g$ & BuildSearch("LastName", "", LblFullNameOp.Text, TxtFullName)   ' LastName

There are 19 of these IF statements, one for each of the input fields on the form. The first two fields passed to BuildSearch provide text for the SQL statement. The remaining 2 parameters get text from the various controls to be used in the SQL statement.
Similar code will be used in other forms, using different field names. So rather than coding several more bunches of these IF statements for each form (and as a learning exercise), I'd like to build a Collection in each form containing the 4 (or 5) pieces of data for each input field, then generate the IF statements dynamically. Here's what I've done in the first module:
Public Class FormFld
    Public Property ScrField As Control
    Public Property ScrLabel As Control
    Public Property DbField As String
    Public Property DbNumeric As Boolean
End Class

Public Class FrmSearch
    Private ReadOnly FormFlds As New List(Of FormFld) From
        {
    New FormFld With {.ScrField = TxtSort_Key, .ScrLabel = LblSort_KeyOp, .DbField = "Sort_Key", .DbNumeric = False}} ',
    New FormFld With {.ScrField = TxtFullName, .ScrLabel = LblFullNameOp.Text, .DbField = "LastName", .DbNumeric = False},
    ...

I was expecting to be able to do:
For Each formfld In FormFlds
    With formfld

        ' Examine .ScrField to determine the type of control, then extract the proper field and determine the
        ' proper condition to generate, e.g., TxtSort_Key.Text <> "", or ChkVolunteer.Checked…, etc.
    End With
Next

But when setting a breakpoint there and looking at ScrLabel in the Locals watch, I don't see anything that tells me the name of the control or what type of control it is:
Locals window
Is what I'm trying to do possible? If so, could someone give me a hint as to find the type of control? I appreciate any help you can provide.

A: I would suggest that you just create a single query that incorporates all possible filters and pass nulls to effectively ignore certain parameters. This may slow the query down a bit but, unless there's a lot of data, it shouldn't be significant. Here's a simple example with two filter fields:
SELECT *
FROM SomeTable
WHERE (@Column1 IS NULL OR Column1 = @Column1)
AND (@Column2 IS NULL OR Column2 = @Column2)

You can then pass DBNull.Value for both parameters to get all records, pass DBNull.Value for one of the parameters to filter only by the other or pass values for both parameters to filter by both, e.g.
With myCommand.Parameters
    .Add("@Column1", SqlDbType.VarChar, 50).Value = If(TextBox1.TextLength = 0, CObj(DBNull.Value), TextBox1.Text)
    .Add("@Column2", SqlDbType.VarChar, 50).Value = If(TextBox2.TextLength = 0, CObj(DBNull.Value), TextBox2.Text)
End With

Note that the If operator used here requires both potential return values to be the same type or assignable to the same type. That is not the case for DBNull and String so one or the other must be cast as type Object.


text:
Q: Elasticsearch How to use specific analyzer and append filter I would like to use nori analyzer and synonym filter
I'm not sure if type parameter is what I need as below..
{                                                                                "location_analyzer": {
    'type': 'nori',
    'filter': ['location_synonym_filter'],
  },

  "location_synonym_filter": {
    "type": "synonym",
    "expand": True,
    "synonyms_path": "data/synonyms_location",
  }
}

A: You need to create a new custom analyzer since you're adding a new filter. Check out at the definition of that analyzer and then create a new one of type "custom".
Some doc:
https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-nori-analyzer.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-custom-analyzer.html


text:
Q: Docker compose up keep replace existing container I got the code from two branches with following config:
docker-compose.yml:
version: '3'
services:
  server:
    build: .
    restart: always
    image: XXXXX
    entrypoint: ["./run.sh"]
    container_name: XXXX
    ports:
      - 127.0.0.1:8000:8000
    volumes:
      - .:/app

    depends_on:
      - redis
  redis:
    container_name: XXXXX
    image: redis:4-alpine

When I docker compose first branch, it works well, but when I compose up the second branch, the original container become the new branch container, which I want the two branches containers exist at the same time.
When I compose up the second branch code, the following message shows:
Recreating XXXXX_branch2 ... done
Attaching to XXXXX_branch1

A: Docker compose associates the container with the project name (default directory name) and the service name or container_name if specified. Thus in case both branches have the compose file under the same directory name, and thus the compose files will be interpreted as refering to the same container, which will lead to the container being recreated.
To avoid this situation, you can the --project-name option to override the default one (directory name).
docker-compose --project-name branch1 up -d
docker-compose --project-name branch2 up -d

In this case both containers will be created.
But note that if both compose files have the same container_name set, there will be a conflict and the second container creation will fail. To avoid that, either use different container names, or remove the container_name property,  to get the default container name which is <project_name>_<service_name>_1


text:
Q: Updating Datagrid datacontext eats memory I have a WPF datagrid and I need to update it every minute. I have added a DispatchTimer to get the data and update the data Context of my datagrid. The problem is that it seems like data is sticking around. First I was thinking it was my lists but I just had the lists running with out updated my dataContext and I don't see the megs of memory being used.
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

I have it set to 1 second for testing.
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        ObservableCollection<Technician> techData = LoadData();
        DG1.DataContext = null;
        DG1.DataContext = techData;
    }

...
    private ObservableCollection<Technician> LoadData()
    {
        ObservableCollection<Technician> techData = new ObservableCollection<Technician>();

        Uri uriGreenImage = new Uri("pack://application:,,,/Images/green.png");
        Uri uriRedImage = new Uri("pack://application:,,,/Images/red.png");

        // Connect to Database.
        Database db = new Database();

        string query = "SELECT * FROM dbo.StatusBoard ORDER BY dbo.StatusBoard.LastName";

        SqlDataReader reader = db.Query(query);

        while (reader.Read())
        {
            BitmapImage statusImage;

            switch(reader["Status"].ToString())
            {
                case "0":
                    statusImage = new BitmapImage(uriGreenImage);
                    break;
                case "1":
                    statusImage = new BitmapImage(uriRedImage);
                    break;
                default:
                    statusImage = new BitmapImage(uriRedImage);
                    break;
            }

            techData.Add(new Technician
            {
                FullName = reader["FirstName"].ToString() + " " + reader["LastName"].ToString(),
                Comments = reader["Comments"].ToString(),
                Status = statusImage,
                WatchingServiceDesk = (reader["WatchingServiceDesk"].ToString() == "1" ? true : false),
                Phone = reader["Phone"].ToString()
            });
        }

        return techData;
    }


text:
Q: Access webpage's localStorage from a Chrome extension i'm developing a chrome extension which requires to get the values(to plugin) from local storage where values are stored by some other webpages that were created by me
In short: Access a webpage's localStorage from a Chrome extension script

A: I just tested it, and if you access localStorage from the context of a content script, you get the webpage's localStorage. So, nothing special is required besides injecting a content script into the webpage you need.
To communicate the value from the content script you can use Messaging API, and you can use chrome.storage.local API to save data in a way that's accessible from both the content script and the background page.


text:
Q: summation of polynomial products I need help in understanding how the summation of the product of two polynomials is written.
$(a_{0} +a_{1}x +a_{2}x^{2})(b_{0} +b_{1}x + b_{2}x^{2}) =\\ (a_{0}b_{0})x^{0} + (a_{1}b_{0} + b_{1}a_{0})x + (a_{2}b_{0} +a_{1}b_{1} + a_{0}b_{2})x^{2} + (a_{1}b_{2} + a_{2}b_{1})x^{3} + (a_{2}b_{2})x^{4}$
I can not figure out how to write this as a general summation.
Thanks

A: Hint
Distribute the product $$(a_{0} +a_{1}x +a_{2}x^{2})(b_{0} +b_{1}x + b_{2}x^{2}) =$$ $$(a_{0} +a_{1}x +a_{2}x^{2}) b_0 +(a_{0} +a_{1}x +a_{2}x^{2}) b_{1}x+(a_{0} +a_{1}x +a_{2}x^{2})  b_{2}x^{2}$$ Expand now what is inside the brackets and group together the terms showing the same power of $x$. Remember that $x^0=1$

A: Let $C_m$, coefficients be
$$sum   a_j*b_k$$ where j+k = m
So the resulting polynomial is

Sum m=0 to 4 of $C_m$ * $x^m$

Please fix my MathJax/ LaTeX, simply figuring out the answer and how to notate it took significant effort.  I invite you or encourage you to check this by writing out a few terms of the sum.


text:
Q: Long tap recognizer in Sprite Kit with swift Hello I'm planning a game and an essential part of the game is to move left and right by pressing the right side of the screen or the left side.
But how can I detect a long press?
Many Thanks! :)

A: It is not called long tap. A tap can't be long. It is called UILongPressGestureRecognizer. You can take a look at the documents here

A: if you want to do something while the user is holding down on the screen, you could use the touchesBegan and touchesEnded methods to detect the hold.
var touching = false

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

touching = true

}

func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

touching = false

}


text:
Q: Mysql select count У меня есть таблица users там я храню информация о клиентах и дилерах отличаются они столбцом StatusID
0 это дилер, 1 это клиент в столбце 'dealer_id' id дилера для каждого клиента. Например если в клиенте 'dealer_id' стоить 3 значить этот клиент принадлежит дилеру с id 3, мне нужно посчитать количество клиентов для каждого дилера

SELECT a.id, a.login, a.active, a.LastDate, count(a.id) as 'количество клиентов'
FROM users AS a
left join `balance` as b on `owner_id`=a.`id`
left join `operatsion` as c on b.`type`=c.`id`
WHERE a.StatusID = '0'
GROUP BY a.`login`
ORDER BY LastDate DESC

использую COUNT(a.id) почему то количество клиентов для каждого дилера цифры не совпадают
проверяю отдельно дилера с id 3 для подсчёта клиентов делаю count(id) здесь все верно помогите с запросом пожалуйста

A: COUNT считает в группе, а группировка у вас сейчас по id:
GROUP BY a.`login`

Для статистики по дилеру группировать надо по соответствующему полю:
GROUP BY a.`dealer_id`

Ну и ненужные JOIN удалить бы :)


text:
Q: L2 Vs. L3 CPU cache speed and performance  In the past few years, looking at Intel CPUs, there has been a move from large size L2 cache to large size L3 cache.
A lot of this is due to having more cores on the CPU and wanting to share the cache between them (an L3 advantage).
But supposing I have a single threaded application and I want to compare the speed I get running it on 2 different CPUS that share the same clock speed :

*

*a CPU with 6MB L2 cache @3.1Ghz  (e.g., Core 2 Duo E8500)

*a CPU with 6MB L3 cache @3.1Ghz (e.g., Core i5 2400)
Disregarding turbo boost effects and faster DDR factors,
It seems the first (older) CPU should perform much faster (as it is closer to the core level), no ?
Another question that interests me, In old times, back in the first days of L2 cache in CPUs I seem to recall that L2 cache is accessed at half the CPU clock speed, is that still true today ? and what about L3 speed ?

A: It depends. If the inner loop of your program fits into the L1 cache of both CPUs and memory speeds are the same, you won't see much difference.
If the inner loop fits into the 6MB L2 cache, but does not fit into the L2 cache of the CPU with 6MB L3 cache, then the program will be faster on the older CPU with the larger L2 cache.
But in general, the inner loop part of a program is very small.

A: Intel uses a new cache technology called "Smart Cache" so I doubt any comparisons between current models now and CPUs from years ago are on a level playing field. Keep in mind that I think "Smart Cache" is an Intel technology only; AMD uses something called "Balanced Smart Cache".
Wikipedia info:

Smart Cache is a level 2 or level 3 cache method for multiple
  execution cores invented by Intel. It shares the cache among cores
  (CPU Core or GPU). In comparison to a dedicated cache per core the
  overall cache miss rate decreases in times where not all cores need
  equally much cache space. Consequently a single core can use the full
  level 2 cache or level 3 cache, if the other cores are inactive.
  Furthermore the shared cache makes it faster to share memory among
  different execution cores.

A: Concerning the second part of the question, yes it's still true to some degree.
L1 is faster than L2, and L3 is slower than L2. But I would not it call it "half frequency" since CPU design varies greatly.
Also I guess Core i5 will be faster almost always, because cache size is important, but also important is cache speed and miss rate, as well as overall CPU design.


text:
Q: NullPointerException error while implementing Hash Table in java I am implementing Hash Table through java. When I implement the following code, I get a NullPointer Exception error but if I replace the else statement in void put(int key, int value) in class HashTable with the statement kv[key]=new KeyValue(key,value); It works! Can someone explain why is this happening? Please help!
public class KeyValue {
    int key;
    int value;

    KeyValue(int k, int v)
    {
        key = k;
        value = v;
    }
    public int getKey(){
        return key;
    }

    public int getValue()
    {
        return value;
    }

    public void put(int k, int v)
    {
        key = k;
        value = v;
    }

}

public class HashTable{

    KeyValue[] kv;

        HashTable(){
            kv = new KeyValue[4];
            for (int i=0; i<4 ; i++)
            {    kv[i]=null;

            }
        }

    void put(int key, int value)
        {
            if((kv[key]!=null) || (key<0 && key>=4))
            {
                ;
            }
            else
            {
                kv[key].put(key,value);
            }
        }

        int get(int key)
        {
            int value;

            value=kv[key].getValue();

            return value;
        }

    public static void main(String[] a){

            HashTable h = new HashTable();
            h.put(1,2);

            System.out.println(h.get(1));

        }

}

A: You are initializing kv[key] with null. So if you do kv[key].callSomeMethod you got an NullPointerException because there is no object to call a method of.
You can initialize your KeyValues like Peter Radar said or do it in the constructor of your HashTable using the default constructor of KeyValue.
    HashTable(){
        kv = new KeyValue[4];
        for (int i=0; i<4 ; i++)
        {
            kv[i]=new KeyValue();
        }
    }

Now an Object of type KeyValue is stored in kv[i] and you can use its methods.

A: To answer your question I believe kai and Peter Rader found the issue. But there are other things in your code that I recommend to change.
The KeyValue.put method should be renamed to set or completely dropped. The basic question is here if KeyValue should be a mutable data object or not.
In HashTable.put the your code if((kv[key]!=null) || (key<0 && key>=4)) should read if ((kv[key]!=null) || key<0 || key>=4) (besides you should of course replace 4 with a variable so you can have larger HashTables too).
Since you are trying to learn something from this I'd also recommend that you try to replace KeyValue[] kv; with a Collection.


text:
Q: AS3 Dynamic Movie Clip name as variable In Animate CC I can add MovieClips from the library dynamically using the following code:
var MovieClipName_mc:MovieClipFromLibrary = new MovieClipFromLibrary();
stage.addChild(MovieClipName_mc);

I want to change the MovieClip I am adding on the fly so I need to have "MovieClipFromLibrary" as a variable. However, I can't seem to get anything to work.
I hope I've explained that correctly? Help greatly appreciated. Thanks!

A: Something like getDefinitionByName(...) method should work.
//# setup the vars
var myVar :String = "MovieClipFromLibrary";
var MovieClipName_mc :Class;

//# apply the vars and add to screen
MovieClipName_mc = getDefinitionByName( myVar ) as Class;
stage.addChild(MovieClipName_mc);

You could also make a function createInstance to take care of adding multiple vars like below:
Implementation:
import flash.utils.getDefinitionByName;

function createInstance(avalue:*):*
{
    var C:Class;

    if (avalue is Class)
    {
        C = avalue as Class;
    }
    else if (avalue is String)
    {
        // If there is actually a class in library
        // with the provided class name, then
        // C will be filled with a valid class.
        C = getDefinitionByName(aname) as Class;
    }

    if (C != null)
    {
        return new C;
    }
    else
    {
        return null;
    }
}

Usage:
var M:DisplayObject;

// Pass class name as String.
M = createInstance("MovieClipFromLibrary");

if (M != null)
{
    stage.addChild(M);
}

// Pass class reference as is.
M = createInstance(MovieClipFromLibrary);

if (M != null)
{
    stage.addChild(M);
}

Please keep in mind that you can access only the classes of the current SWF this way. If you want it to obtain things from loaded SWFs, you will need to set up some kind of library manager and get things via Loader.contentLoaderInfo.applicationDomain.getDefinition(...) method.

A: That exact code didn't work for me. It gave me an implicit coercion error. However, it was super helpful because this did work...
    //Get Item from library
    var MCName:Class = getDefinitionByName('TEST') as Class;

    var MovieClip_mc:MovieClip = new MCName();
    stage.addChild(MovieClip_mc);

So thanks a lot!!


text:
Q: Clarification on SQL Server connection string I am using Visual Studio 2013 to write my web app using SQL Server 2012 backend. This is my connection string which works fine.
<connectionStrings>
    <add
        name="UserDetails"
        connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UserDetails.mdf;Integrated Security=True;Connection Timeout=30;"
        providerName="System.Data.SqlClient"/>
</connectionStrings>

But while deploying as Web deploy package, I could generate .zip and deploy.cmd and setparameters.xml/SourceManifest.xml file gets generated successfully. As guided in deploy-readme.txt, I executed the below command which was successful.
App.deploy.cmd /T /L -allowUntrusted /M:http://localhost/MSDeployAgentService

I tried to replace /T with /Y and here is where I get the error as below.
ERROR

Error Code: ERROR_EXCEPTION_WHILE_CREATING_OBJECT
  More Information: Failed to create type 'Microsot.SqlServer.Dac.DacServices'.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_EXCEPTION_WHILE_CREATING_OBJECT.
  Error: Exception has been thrown by the target of an invocation. ---> System.Exception: The connection string argument AttachDBFilename is not supported

AttachDBFilename was proposed in MSDN. I exactly don't understand the reason for this error.
I tried not to include the database while publishing and the above command succeeded and I was able to launch the application hosted. However, SQL Server connection fails at later point. So, I could figure out that I have got some issue with my connection string but I am stuck here for a week. You suggestions will be really helpful and please assist me if I have missed anything.


text:
Q: Using regexes in Ruby I have a regex, that I'm trying to use in Ruby. Here is my Regex, and it works in Java when I add the double escape keys
\(\*(.*?)\*\)

I know this is a simple question, but how would I write this as a ruby expression and set it equal to a variable? I appreciate any help.

A: try this:
myregex = /\(\*(.*?)\*\)/

To be clear, this is just to save the regex to a variable. To use it:
"(**)" =~ myregex

A: try this:
if /\(\*(.*?)\*\)/ === "(*hello*)"
  content = $1 # => "hello"
end

http://rubular.com/r/7eCuPX3ri0

A: Regular expressions are a native type in Ruby (the actual class is "Pattern"). You can just write:
mypat = /\(\*(.*?)\*\)/

[Looks like anything between '(' / ')' pairs, yes?]
You can then do
m = mypat.match(str)
comment = m[1]

...or, more compactly
comment = mypat.match(str)[1]


text:
Q: get response json from serlvet How do I receive a JSON response from servlet to javascript ? I'm passing it to the servlet using AJAX post
 this my ajax code

 $.ajax({
            type: "POST",
            url: "formDelegationServlet",
            data: {
                jsonfield: JSON.stringify(dataString) // look here!
            },
            dataType: "json",
            //if received a response from the server
            success: function (response) {
                //our country code was correct so we have some information to display
                if (response.success === true) {
                    console.log("response" + response);
                    $("#kota_merchant").val(response.rows.kota_merchant_del);
                    $("#alamat_merchant").val(response.rows.alamat_merchant_del);
                    $("#province_merchant").append(response.rows.prov_merchant_del);

                }
                //display error message
                else {
                    $("#ajaxResponse").html("
Merchant Name in Invalid!
");
                }
            },
            //If there was no resonse from the server
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Something really bad happened " + textStatus);
                $("#ajaxResponse").html(jqXHR.responseText);
            }
        });

this my servlet code
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONArray array = new JSONArray();
                for (int i = 0; i < dataMerchant.size(); i++) {
                    JSONObject obj = new JSONObject();
                    EntityMerchant entityMerchant = dataMerchant.get(i);

                    if (entityMerchant.getNamaMerchant() == null) {
                        obj.put("nama_merchant_del", "");
                        obj.put("success", false);
                    } else {
                        obj.put("nama_merchant_del", entityMerchant.getNamaMerchant());
                        obj.put("success", true);
                    }
                    if (entityMerchant.getAlamatMerchant() == null) {
                        obj.put("alamat_merchant_del", "");
                    } else {
                        obj.put("alamat_merchant_del", entityMerchant.getAlamatMerchant());
                    }
                    if (entityMerchant.getKota() == null) {
                        obj.put("kota_merchant_del", "");
                    } else {
                        obj.put("kota_merchant_del", entityMerchant.getKota());
                    }
                    if (entityMerchant.getProvinsi() == null) {
                        obj.put("prov_merchant_del", "");
                    } else {
                        obj.put("prov_merchant_del", entityMerchant.getProvinsi());
                    }
                    if (entityMerchant.getPassword() == null) {
                        obj.put("pas_merchant_del", "");
                    } else {
                        obj.put("pas_merchant_del", entityMerchant.getPassword());
                    }
                    array.add(obj);

                }
                em.close();
                JSONObject jsonobj = new JSONObject();
                jsonobj.put("rows", array);
                out.print(jsonobj.toString());
}

this my response json
{"rows":[{"nama_merchant_del":"MAJU SUKSES OCEAN","success":true,"alamat_merchant_del":"JL. DIPONEGORO
 NO.  1B","kota_merchant_del":"JAKARTA PUSAT","prov_merchant_del":"DKI JAKARTA","pas_merchant_del":"0"
}]}

I have tried it many times but I've been unsuccessful. Please help!

A: First set content type and then Initialize your printwriter object as below:
PrintWriter out = null;
res.setContentType("application/json; charset=UTF-8");
out = res.getWriter();


text:
Q: %in% is not giving the right output I have written the following code in Rstudio editor, and the builtin function %in% is not working as desired. At the third last iteration there is a match but %in% is not returning TRUE. Kindly help.
longi=c(5.044747,5.054746,9)
longdummypos=longi
incrementinx=0.000001
for (incx in seq(from=0, to=0.01, by=incrementinx))
{
 longdummypos=longdummypos+incrementinx
 print(longdummypos)
 print(longi)
  a=longdummypos %in% longi
  print(a)
  t1=is.element(TRUE,a)

    if(t1==TRUE)
    {
      break()
    }

    incrementinxfinal=incx
}


text:
Q: How to validate certain input parameters through a Validation API? I have an API in which I am doing my own validation for certain input parameters. For example -
    public Builder(int clientId) {
        TestUtils.assertNonNegative(clientId, "ClientId");
        this.clientId = clientId;
    }

    public Builder setUserId(String userid) {
        TestUtils.assertNotNull(userid, "UserId");
        this.userid = userid;
        return this;
    }

And my assertNonNegative and assertNotNull method in TestUtils class is like this -
public static void assertNonNegative(int val, String attr) {
    if (val <= 0) {
        s_logger.logError("Attribute = ", attr, " Value = ", val, " error=", attr, " cannot be negative or zero");
        throw new IllegalArgumentException(attr + " cannot be negative or zero");
    }
}

public static void assertNotNull(String value, String key) {
    if (value == null || value.isEmpty()) {
        s_logger.logError("Key = ", key, " Value = ", value, " error=", key,
                " cannot be NULL or empty String");
        throw new IllegalArgumentException(key + " cannot be null OR empty");
    }
}

I am wondering is there any validation API available in any open source projects which I can use to substitute the above internal method I have? If yes, can anyone provide an example how would I achieve this? I still need to throw the same message back as an IllegalArgumentException

A: I dont understand why would you use an external API tu achieve a nullOrEmpty or a non-negative number validation but...
If you would like to verifiy an id of a user in a database directly in you Java app
This might interest you to learn:
http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
Use a bit of PHP and verify if the user is in the database.
if(isset($_GET['idcmd']))
{
    switch($_GET['idcmd'])
    {
        case 1:
                if(isset($_POST['iduser']))
                {
                    $sql= "SELECT idUser FROM users WHERE idUser=:iduser ";
                    $result = $db_conn->prepare($sql);
                    $result->bindParam(":iduser" ,$_POST['iduser']);
                    $result->execute();

                    $num=$result->fetchColumn();
                    if($num > 0){
                        echo "cool";
                    }else{
                        echo "nocool";
                    }
                }
        break;
    }
}

Now if you make a POST request to the url www.mydomain.com/myapi.php?idcmd=1 and get the response cool, it means that the user is in database.
I hope it helps.


text:
Q: Terraform list ECS cluster container instances Is there a way to get list of ids/arns of all EC2 container instances on ECS cluster, I tried with data source: aws_ecs_cluster but it only shows registered_container_instances_count - the number of registered container instances for the ECS Cluster without any information about them

A: If there is no data source provided by TF that suit your needs, you can provide your own using External Data Source. Using the external data source you can get any information that you want into your TF scripts for future use.

A: Try this :
Make sure to have boto3 module imported and the needed AWS permmisions
(not a Python or a Terraform expert)
terraform {}

data "external" "external_resource" {
  program = ["/usr/bin/python3", "${path.module}/list_instances.py"]

  query = {
    cluster_name = "CHANGE_ME"
  }
}
output "output" {
  value = data.external.external_resource.result
}

import boto3
import sys
import json

client = boto3.client('ecs')

def list_containers(cluster_name):
    # list all container instances id
    response = client.list_container_instances(
        cluster=cluster_name
    )
    return response['containerInstanceArns']

def describe_container():
    # get terraform query json and assign it to a dict
    query=sys.stdin.readlines()
    terraform_respone_dic=json.loads(query[0])
    cluster_name=terraform_respone_dic['cluster_name']

    # get the container instances
    response = client.describe_container_instances(
    cluster=cluster_name,
        containerInstances=list_containers(cluster_name)
    )

    # get the instance id's and assign to a variable
    instances=list(map(lambda x:x['ec2InstanceId'],response['containerInstances']))
    # assign them to our original query json (dict)
    terraform_respone_dic['instances_id\'s']=instances

    # return as stdout
    output = json.dumps({str(key): str(value) for key, value in terraform_respone_dic.items()})
    sys.stdout.write(output)

if __name__ == '__main__':
    describe_container()

expected outputs :
terraform apply
Outputs:

output = tomap({
  "cluster_name" = "production"
  "instances_id's" = "['i-xxxxxxxxxxxxxxxx', 'i-xxxxxxxxxxxxxxxx', 'i-xxxxxxxxxxxxxxxx']"
})


text:
Q: Drag and Drop in Android before 3.0? How can I do a drag and drop with Views in android without requiring Honeycomb or beyond OS?
The Views support drag and drop functionalities but requires API level 11.

A: The Android Drag&Drop built-in framework requires API 11
http://developer.android.com/guide/topics/ui/drag-drop.html
If you need this feature on previuous API level, you have to implement it manually. I learned it from this guide/example:
http://blahti.wordpress.com/2011/01/17/moving-views-part-2/
(Many thanks to the author: Blahti)


text:
Q: Pip install portfolioopt fatal error C1083 I'm trying to install portfolioopt (Win 8.1*64) lib using pip and get those errors:
     C:\Users\Alexey\AppData\Local\Programs\Common\Microsoft\Visual C++ for Pytho
n\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Anaconda\inc
lude -IC:\Anaconda\PC /Tcsrc/C/base.c /Fobuild\temp.win-amd64-2.7\Release\src/C/
base.obj
    base.c
    c:\users\alexey\appdata\local\temp\pip-build-30y6av\cvxopt\src\c\cvxopt.h(31
) : fatal error C1083: Cannot open include file: 'complex.h': No such file or di
rectory
    error: command 'C:\\Users\\Alexey\\AppData\\Local\\Programs\\Common\\Microso
ft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status
2

I already have Visual C++ 2008 and Compiler package for python 2.7. How to fix it?

A: It appears that your problem is with the requirements for portfolioopt, for some reason it doesn't seem to be properly installing the cvxopt package. What I did to fix this problem (I tried and had a similar problem to you) is to separately install the cvxopt package, which I did with this command:
    conda install -c https://conda.binstar.org/eswears cvxopt

after this package installed I used the pip install command for the portfolioopt package:
    pip install portfolioopt

and the installation worked.


text:
Q: mDNSResponder Errors on iOS I'm seeing some weird stuff happening in my app.  After coming back to the app from suspended state, at seemingly random times, network actions all hang.  They don't timeout or call back and error, they just hang.  I captured the log, and the last time it happened, these two lines were logged just after the first request was sent off.
mDNSResponder[45] <Error>:  14: Could not write data to client because of error - aborting connection
mDNSResponder[45] <Error>:  14: DNSServiceGetAddrInfo v4v660b818f4fdfde88126fa9675dc82b6ad252e09c3.sdk.testflightapp.com.

Looks like it could be something related to having TestFlight in my app, or maybe it's just issues with DNS.  Any ideas?

A: TestFlight 0.8.3 is buggy and I ended up fixing this by removing the TestFlight SDK.


text:
Q: A question about the inhomogeneous Cauchy-Riemann equations It's homework time again. Consider a function $f\in C^k_c(\mathbb{C})$, i.e. $C^k$ functions with compact support. Then the function
$$u(z) = -\frac{1}{2\pi i} \iint_{\mathbb{C}} \frac{f(\zeta)}{\zeta -z } d\zeta \wedge d\bar{\zeta}$$
is in $C^k(\mathbb{C})$ and solves $$\frac{\partial u}{\partial \bar{z}}=f$$
I want to show that $u(z)$ goes to $0$ as $|z| \rightarrow \infty$. I guess I have to use that $f$ has compact support somehow. But how to start? Do I have to use the Cauchy integral formula? What if I made a change of variables like
$$u(z) = -\frac{1}{2\pi i} \iint_{\mathbb{C}} \frac{f(\zeta+z)}{\zeta} d\zeta \wedge d\bar{\zeta}$$
Would that do anything?

A: Hint: Let $K$ be the support of $f.$ Set $R = \max \{|z|:z\in K\}.$ Use the fact that $f$ is bounded on $K$ to see that there is a constant $C$ such that for $|z|>R,$
$$|u(z)| \le C\int_K \frac{1}{|\zeta-z|}\, dA(z) \le C\int_K \frac{1}{|z|-R}\, dA(z).$$


text:
Q: WC_get_products Meta Query being ignored Im having problems with wc_get_products meta query. Im trying to exclude products that have clearance or express in the SKU and the SKUs are formatted like so; (not my choice something the company decided many moons ago!)
My Club - Express - Item
My Club - Clearance - Item
Another Club - Standard - Item
Below are my args, please could someone tell me what's wrong with them?
    'post_status' => array('publish', 'pending', 'draft', 'future', 'private'),
    'parent' => array( 13, 14, 15 ),
    'limit' => 1000,
    'orderby' => 'id',
    'order'   => 'asc',
    'type' => array( 'simple', 'variable' ),
    'meta_query' => array(
                    'relation' => 'and',
                        array(
                            'relation'  => 'or',
                                array(
                                'key' => '_sku',
                                'value' => 'clearance',
                                'compare' => 'NOT LIKE',
                                ),
                            ),
                        array(
                            'relation' => 'or',
                                array(
                                'key' => '_sku',
                                'value' => 'fxpe',
                                'compare' => 'NOT LIKE',
                                ),
                            ),
                        )
);

I have also completed the woocommerce steps (at bottom of page) Adding Custom Parameter Support which looks like this:
function handle_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['_sku'] ) ) {
        $query['meta_query'][] = array(
            'key' => '_sku',
            'value' => esc_attr( $query_vars['_sku'] ),
        );
    }

    return $query;
 }

 add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );

I've also tried reversing the meta query and changing the compare to like or != but nothing works or seems to affect the query.
Any help really appreciate.
Thanks
UPDATE-------------------------------
I made a major typo in the initial post, to confirm I am using wc_get_products no wp_query
I have been trying a few variations of the meta query but so far nothing is working...
Just using a single meta query doesn't seem to work either
'meta_query' => array(
                        'key' => '_sku',
                        'value' => 'express',
                        'compare' => '!=',  // also tried 'NOT LIKE'

                        ),

Becuase of the inital confusion with the query I will mark Howard E's question correct as it is for wp_query and repost witht he correct information.

A: Try updating your meta_query.  You're starting by saying "OR" for the relation of both clearance and express also.
'meta_query' => array(
    'relation' => 'AND',
    array(
        'relation'  => 'OR',
            array(
            'key' => '_sku',
            'value' => 'clearance',
            'compare' => 'NOT LIKE',
            ),
        ),
    array(
        'relation' => 'OR',
            array(
            'key' => '_sku',
            'value' => 'express',
            'compare' => 'NOT LIKE',
            ),
        ),
    )

* To deal with Updated Question *
function handle_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['_sku'] ) ) {
        $query['meta_query'][] =  array(
        array(
                'relation'  => 'or',
                    array(
                    'key' => '_sku',
                    'value' => 'fxpe',
                    'compare' => 'NOT LIKE',
                    ),
                ),
            array(
                'relation' => 'or',
                    array(
                    'key' => '_sku',
                    'value' => 'clearance',
                    'compare' => 'NOT LIKE',
                    ),
                ),
            );
    }

    return $query;
 }

Then just use _sku in the product query with a value...
$products = wc_get_products(array(
     'post_status' => array('publish', 'pending', 'draft', 'future', 'private'),
    'parent' => array( 13, 14, 15 ),
    'limit' => 1000,
    'orderby' => 'id',
    'order'   => 'asc',
    'type' => array( 'simple', 'variable' ),
    '_sku' => true,
));

adding this filter will however filter any instance of _sku in the WC query.  You may want to add additional conditionals if needed.


text:
Q: Splitting complicated strings with number, characters and special signs I have a dataframe with one variable which looks like this:
rownr country
22    Bolivia 0.16 0.16 4.63* 22.10* 450
23    Mozambique 1.11 19.22* 0.19 12.38* 486
24    Germany 0.77 6.06* 0.53 15.35* 630
25    Bosnia & Herzegovina 0.72 6.84* 1.03 21.60* 889

I would like to separate it into six separate variables like this:
rownr country              number 2      3     4      5
22    Bolivia              0.16   0.16   4.63* 22.10* 450
23    Mozambique           1.11   19.22* 0.19  12.38* 486
24    Germany              0.77   6.06*  0.53  15.35* 630
25    Bosnia & Herzegovina 0.72   6.84*  1.03  21.60* 889

This is what I tried:
names(df)[1] <- "Strng"
df <- setDT(df)[, paste0("RA", 1:8) := tstrsplit(Strng, " ", type.convert = TRUE, fixed = TRUE)]
df$country <- gsub("[[:digit:]]","",df$Strng)
df$country <- gsub("[[:punct:]]","",df$country)
df$numbers <- gsub("[[:alpha:]]"," ",df$Strng)

df <- select(df, RA1:RA5)
names(df)[1] <- "country"
names(df)[2] <- "number"

df$numberss <- strsplit(df$numbers, split=" ", fixed = FALSE, perl = FALSE, useBytes = FALSE)
df <- setDT(df)[, paste0("RA", 1:5) := tstrsplit(numbers, " ", type.convert = TRUE, fixed = TRUE)]

Which leads to:
rownr country              number  3           4     5
22    Bolivia              0.16    0.16        4.63* 22.10*
23    Mozambique           1.11    19.22*      0.19  12.38*
24    Germany              0.77    6.06*       0.53  15.35*
25    Bosnia               &       Herzegovina 0.72  6.84*

I can't figure out how to get it right. Any tips?

A: Using positive lookahead we can split only on space \\s followed immediately by a digit (?=\\d)
library(tidyr)
df%>% mutate_if(is.factor,as.character) %>%
      separate(country,sep = '\\s(?=\\d)', into = c('country','number','2','3','4','5' ))

               country number     2     3      4   5
1              Bolivia   0.16  0.16 4.63* 22.10* 450
2              Germany   0.77 6.06*  0.53 15.35* 630
3 Bosnia & Herzegovina   0.72 6.84*  1.03 21.60* 889


text:
Q: Can Pax Web Whiteboard ResourceMapping have path pointing outside the bundle? I've tried to register the following ResourceMapping as an OSGi service:
package ru.focusmedia.odp.server.poim.http;

import org.ops4j.pax.web.extender.whiteboard.ResourceMapping;

import ru.focusmedia.odp.server.poim.api.PoimConfig;

import aQute.bnd.annotation.component.Component;

@Component(immediate = true)
public class PoimResourceMapping implements ResourceMapping {
    private String httpContextId;
    private String alias = "...";
    private String someAbsolutePath = "...";

    @Override
    public String getHttpContextId() {
        return httpContextId;
    }

    @Override
    public String getAlias() {
        return "/resources";
    }

    @Override
    public String getPath() {
        return someAbsolutePath;
    }

}

but don't see the result in browser under http://127.0.0.1:8282/resources/aFileUnderMyPath. I can see that Pax Web is accessing my mapping in the log. Is this possible or do I need to write a servlet instead?

A: The short answer is no.
The path is resolved relative to the bundle and therefore your absolute path will turn in some url syntax error.
Why not loading your file in a bundle and serving it from there? We dynamically load bundles with resources that we need to serve following some versioning conventions.


text:
Q: Laravel database migrattion user could be from another type I'm currently facing an issue on the conception part of my project.
I read many posts and no one abort this problem.
I'm using Laravel 5.6 as API for my web App.
So I have two type of users :

*

*Simple user

*Professional user

The "Professional" one has a dashboard where he can do many stuffs, and the "Simple user" can contact the "Professional".
But the "Professional" could also be a "Simple user", he can contact other "Professional". And here is the problem I'm blocked on the conception of Model and Migration of the database. I don't know how to link them, and I don't want to duplicate all the "Simple user" vars in a "Professional" table and just add vars in this one. (Don't know if it's explicite)
So I started by create an User Model/Migration :

App/User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email', 'password', 'old_password', 'last_name', 'first_name', 'birthday', 'address',
        'postal_code', 'city', 'country', 'phone_number'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'id', 'password', 'old_password', 'remember_token'
    ];

    /**
     * The attributes that should be handled by Carbon
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
        'birthday'
    ];
}

database/migrations/..create_users_table.php

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('old_password');
            $table->string('phone_number', 50);
            $table->string('last_name');
            $table->string('first_name');
            $table->tinyInteger('sex');
            $table->date('birthday');
            $table->text('address');
            $table->string('postal_code', 10);
            $table->string('city', 50);
            $table->string('country', 50);
            $table->boolean('valid_email')->default(false);

            $table->timestamps();
            $table->rememberToken();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

The the Professional Model/Migration :

App/Professional.php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Professional extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'profession', 'organisation', 'subscription', 'activity_start_at', 'valid_num_organisation'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'user_id', 'num_organisation'
    ];

    /**
     * The attributes that should be handled by Carbon
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
        'activity_start_at'
    ];

}

database/migrations/..create_professionals_table.php

class CreateProfessionalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('professionals', function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->primary('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('profession');
            $table->string('organisation');
            $table->string('num_organisation');
            $table->string('subscription');
            $table->date('activity_start_at');
            $table->boolean('valid_num_organisation')->default(false);
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')->on('users')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('professionals', function (Blueprint $table) {
            $table->dropForeign('professionals_user_id_foreign');
            $table->dropColumn('user_id');
        });
        Schema::dropIfExists('professionals');
    }
}

And here is the real question what the best way to link User and the Professional ? Like a "user->isOneOf()" or something like that.
I was thinking about create a role on my user and if role is empty the user is "Simple user" and if not is a professional but I pretty sur is not the best way.
I also look at the polymorphic link but i don't think it's the one I need in this case.
If you have any ideas I'm listening.
Thanks.

A: First of all, thank you for the extensive description of your problem. Not everyone does that.
Of course, most of this answer is somewhat opinion based. There are many different ways to implement this kind of behaviour. But I think the 'correct' implementation for this problem should be discussed because there are a lot of developers who really don't know where to start on this topic. I am happy to accept any feedback or additions to my answer to make it more complete.
So. Most of the time when I have to deal with more than one type/variant of the same entity, I use just 1 table. Especially when dealing with authentication. Because that makes coding a Laravel application a lot easier.
In the case of just 2 different types of entities. (A normal user and a professional user in your case), I just ad a is_professional boolean flag on the users table. That would be sufficient.
https://laracasts.com/discuss/channels/general-discussion/laravel-auth-multi-user-type
When you want to use more different variants, I'd add a role column to the table. This could be a role_id integer to reference a seperate roles table if you need to store role specific data. But most of the time you can get away with just using a varchar role key. You can also use an enum for this but I never do. I always ran into problems when migrating the table later. Don't know for sure if they fixed those problems already.
There is no shame in storing extra data in your users table that only is filled for certain types of users. In your case that would be the profession and organisation columns for example. Denormalization is accepted in some of this cases. This totally depends on the size and use of your data.
http://www.vertabelo.com/blog/technical-articles/denormalization-when-why-and-how
If denormalization is not the way to go in your application. You could also create a seperate table for any additional information for the professional_users in your case. You should write some logic that makes sure you can load additional information for your model. Maybe in the boot method. Or maybe as a scope.
If you want. You can also create completely different authentication systems for both users. Separating logic when logging in. But when you do that, you have to choose which user can access a certain page. It would be hard to implement accessibility for both types of users I think.
https://scotch.io/@sukelali/how-to-create-multi-table-authentication-in-laravel
Like I said, there is no general ideal implementation for your problem. To answer your question in particular I would have to know your application from top to bottom. Only the developer, you ;), can form the most optimal tactics. Maybe that was not the answer you were looking for but it's the best answer I can give.


text:
Q: JS - fill an array via prototyping I just read the following JS code and I got 2 questions:

*

*Why isn't the container object declared as variable?

*What is"Array.prototype.push.apply" for?

Javascript
 Container = function(title, used) {
  this.title = title;
  this.used= !!used;
  this.callbacks = [];
 };

Container.prototype.push = function() {
    Array.prototype.push.apply(this.callbacks);
};

A: Apply sets the invoking object within the push function. But it doesn't seem to be used correctly here. More on the invoking object, constructor functions and prototype here: https://stackoverflow.com/a/16063711/1641941


text:
Q: python function return none while data is printed as desired I have a python script as below that gather some stores' informations using google API :
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT

def getPlaces(lat, lng, radius, keyword, token=None, places=None):

     # Building my API call
     params = {
        'location': str(lat) + ',' + str(lng),
        'radius': radius,
        'keyword': keyword,
        'key': API_KEY
    }
    if token is not None:
        params.update({'pagetoken': token})

    r = requests.get(PLACES_ENDPOINT, params=params)

    # If its the first time the function is called, then we create the list variable
    if places is None:
        places = []

    for item in r.json()['results']:
        # adding element to my list 'places'
        places.append(item['name'])

    # if there is more results to gather from the next page, call the func again
    if 'next_page_token' in r.json():
        token = r.json()['next_page_token']
        time.sleep(2)
        getPlaces(lat, lng, radius, keyword, token, places)
    else:
        print(json.dumps(places)) # print all the data collected
        return json.dumps(places) # return None

Why the returned json places is None whereas the data appears as it should be in the final print ?

A: To fix my issues I just had to get rid of the else statement.
As the function is recursive, it won't proceed to the return until it ends looping :
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT

def getPlaces(lat, lng, radius, keyword, token=None, places=None):
    params = {
        'location': str(lat) + ',' + str(lng),
        'radius': radius,
        'keyword': keyword,
        'key': API_KEY
    }
    if token is not None:
        params.update({'pagetoken': token})

    r = requests.get(PLACES_ENDPOINT, params=params)
    # parsing json

    if places is None:
        places = []

    for item in r.json()['results']:
        places.append(item['name'])

    if 'next_page_token' in r.json():
        token = r.json()['next_page_token']
        time.sleep(2)
        getPlaces(lat, lng, radius, keyword, token, places)

    return json.dumps(places)

Thanks Michael Butscher for the hint !


text:
Q: Delphi Fortes Report angleLabel on top, across a report I am making the invoice part of an application, and at this moment I am done with the invoice generation (adding products and stuff).
The next step is to have a report displaying the invoice data, ready to print.
That works too. I used Fortes Reports because it is free, easy to work with, and has a free PDF export filter, and a Preview component, so it has everything I need.
Now, my problem is that I must allow my users to Annull an invoice. So when an invoice was emitted, if there was a problem with it, I cannot just delete it later, I must Annull it (I'm not sure that is how you call it - maybe make it void), but basically the invoice stays the same (in printed form) EXCEPT we must write/draw diagonally on top of the entire invoice one word: ANNULLED with RED color.
That means I will make a new report for this case (annulled invoices) and use this one whenever the user wants to print an annulled invoice
So now in Fortes Report there is an RLAngleLabel component that allows me (in theory) to do just that: draw/write the word ANNULLED on the report. But my problem is that I add the label just fine in the btDetail RLBand, only I just can't see it in Preview, and I have no idea what I am doing wrong. If it's not visible in designtime preview, I assume it wont be visible in runtime neither.
Should I place it in a specific way? Should I add it at runtime somehow? I cant seem to be able to access the report's Canvas so I could draw it in some event...
Does anyone have any experience with what I am describing?
In order to reproduce my problem, just add a RLReport control on your form, add bands to it (Titleband, ColumnHeaderBand, DetailBand), and on a detailBand (DetailGridBand)place an AngleLabel, then right click on the report and choose Preview...
If I place the AngleLabel on the TitleBand or on ColumnHeaderBand, then it shows in preview, except that I need to place this Angled label ON TOP of the contents of the invoice, not on the header info.
In the past I used a BMP image as big as the invoice (in order to have it transparent so I would see the contents beneath it), but that made my exported PDF report 5MB in size, and that is a little too much (PNG was not working correctly - I think it would not display it transparent or something like that, so I was stuck to using BMP).
Is there any way of achieving what I want (described above)?

A: For whoever encounters this dilema, I reached the conclusion that I should still go with displaying an image containing the desired text as background and setting the bands to Transparent.
The angleLabel approach seems to be unknown, so I dropped it.
I use this time a PNG file that is about 30-40 KB in size and that does not bother me to have it added to the size of the final PDF.
A lot better than the previous BMP image I used before (that increased the size of the PDF file with about 5 MB).
The neweest version of RLReports works with PNG images. That saved me
Also if you have any RLDraw objects on your report, you must set it's brush style to bsClear, so it would allow the background to be visible.


text:
Q: Is there a way to have better buffer borders in R? I'm hoping maybe someone can help me with the following situation.
I'm working on a project were I need to plot a circle (radius) around a centroid in R. I'm also using this centroid to do an intersection with other geometry. The problem I'm facing is that the buffer border is not a very well defined circle which doesn't look good when I plot both the circle and the intersection.
My code looks somewhat like this:
using sf and ggplot2
Radius of 100km
circle = st_buffer(centroid,100000)
and for the intersection
intersection = st_intersection(geometry,circle)
for the plot
ggplot()+geom_sf(data= circle, fill = "yellow")
The border of buffer is "low quality"

A: Not so bad! That said, if you really want to smooth the circle/buffer border, you can use the package smoothr.
Here is one possibility :
library(smoothr)

# Smooth circle border
circle_smooth <- smooth(densify(circle, max_distance = 10), method = "ksmooth")

# Plot
ggplot2::ggplot()+
  ggplot2::geom_sf(data= circle_smooth, fill = "yellow")

A: You can also use sf::st_buffer(..., nQuadSegs=)
From https://geocompr.robinlovelace.net/geometric-operations.html

The third and final argument of st_buffer() is nQuadSegs, which means 'number of segments per quadrant' and is set by default to 30 (meaning circles created by buffers are composed of 4×30=120 lines). This argument rarely needs to be set. Unusual cases where it may be useful include when the memory consumed by the output of a buffer operation is a major concern (in which case it should be reduced) or when very high precision is needed (in which case it should be increased).


text:
Q: iOS UIPickerView Why Pickerview area is not removed after [pickerView removeFromSuperview]; Why UIPickerView area is not removed after calling  [pickerView removeFromSuperview]?
The picker view is created in this code:
 UIPickerView *pickerAirport = [[UIPickerView alloc] init];
pickerAirport.tag=0;
pickerAirport.dataSource = self;
pickerAirport.delegate = self;
_Airport.inputView = pickerAirport;

The remove code is:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (pickerView.tag == 0)
   {
    NSDictionary * ptr_airport=[self.AllairportsDictionary objectAtIndex:row];
    _Airport.text  =  ptr_airport[@"name"];
   }
else
     _State.text= ptr_aircraftState.StateAircraft[row];;
[pickerView removeFromSuperview];

self.view.center = originalCenter;

}

Thanks


text:
Q: Can I label figures in LaTeX? I googled to find the answers to the above question. But by "label" I mean labeling the figure, not the label that is used for referencing. Let me explain.
Say I am making a figure for a high school presentation which shows various parts of a PC: the  CPU, the monitor, the keyboard, the mouse, etc. I can insert the labels using a software like MS Paint. But inserting equations, letters with subscripts, superscripts is a very difficult using softwares like MS Paint.
For the same purposes I would like to use LaTeX. Is there a way to do that?
Another reason for wanting to use Latex is that Latex will perhaps create text in the form of vectors, i.e. the text will most likely not pixelate when zoomed into.

A: Here's an adaptation of Caramdir's excellent answer to Drawing on an image with TikZ :
\documentclass{article}
\usepackage{graphicx}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[
every pin edge/.style={thick,blue!50},pin distance=15mm,
cir/.style = {align=center,circle,fill=blue!50,minimum size=6pt,inner sep=0pt}
]

\node[anchor=south west,inner sep=0] (image) at (0,0)
  {\includegraphics[width=0.45\textwidth]{ctanlion}};
\begin{scope}[x={(image.south east)},y={(image.north west)}]
  \node [cir,pin=110:{The \TeX book}] at (0.16,0.45) {};
  \node [cir,pin=60:\parbox{4cm}{CTAN lion \\ by Duane Bibby}] at (0.76,0.65) {};
\end{scope}
\end{tikzpicture}

\end{document}