text:
Q: Dependency Injection and JavaFX Since JavaFX runtime wants to instantiate my Application object and all of my controller objects, how do I inject dependencies into these objects?
If objects were instantiated by a DI framework, like Spring, the framework would wire up all the dependencies. If I was instantiating the objects manually, I would provide the dependencies through constructor parameters. But what do I do in a JavaFX application?
Thanks!

A: You can specify a controller factory for the FXMLLoader. The controller factory is a function that maps the controller class to an object (presumably, but not necessarily, an instance of that class) which will be used as the controller.
So if you want Spring to create the controller instances for you, this can be as simple as:
ApplicationContext context = ... ;

FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/fxml"));
loader.setControllerFactory(context::getBean);
Parent root = loader.load();
SomeController controller = loader.getController(); // if you need it...
// ...

And now the FXMLLoader will create controller instances for a Class<?> c by calling context.getBean(c);.
So, e.g., you could have a configuration:
@Configuration
public class AppConfig {

    @Bean
    public MyService service() {
        return new MyServiceImpl();
    }

    @Bean
    @Scope("prototype")
    public SomeController someController() {
        return new SomeController();
    }

    // ...
}

with
public class SomeController {

    // injected by FXMLLoader:
    @FXML
    private TextField someTextField ;

    // Injected by Spring:
    @Inject
    private MyService service ;

    public void initialize() {
        someTextField.setText(service.getSomeText());
    }

    // event handler:
    @FXML
    private void performAction(ActionEvent e) {
        service.doAction(...);
    }
}

If you're not using a DI framework, and you want to do the injection "by hand", you can do so, but it involves using quite a lot of reflection. The following shows how (and will give you an idea of how much ugly work Spring is doing for you!):
FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/fxml"));
MyService service = new MyServiceImpl();
loader.setControllerFactory((Class<?> type -> {
    try {
        // look for constructor taking MyService as a parameter
        for (Constructor<?> c : type.getConstructors()) {
            if (c.getParameterCount() == 1) {
                if (c.getParameterTypes()[0]==MyService.class) {
                    return c.newInstance(service);
                }
            }
        }
        // didn't find appropriate constructor, just use default constructor:
        return type.newInstance();
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }
});
Parent root = loader.load();
// ...

and then just do
public class SomeController {

    private final MyService service ;

    public SomeController(MyService service) {
        this.service = service ;
    }

    // injected by FXMLLoader:
    @FXML
    private TextField someTextField ;

    public void initialize() {
        someTextField.setText(service.getSomeText());
    }

    // event handler:
    @FXML
    private void performAction(ActionEvent e) {
        service.doAction(...);
    }
}

Finally, you might want to check out afterburner.fx, which is a very lightweight (in all the best ways) JavaFX-specific DI framework. (It uses a convention-over-configuration approach, where you just match FXML file names to controller class names, and optionally CSS file names, and everything just works.)

A: i used setControllerFactory methode of FXMLLoader class to Sets the controller factory used by this serializer.
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext();
        ctx.register(AppConfig.class);
        ctx.refresh();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/sample.fxml"));
        loader.setControllerFactory(ctx::getBean);

        Parent root = loader.load();
        Controller controller = loader.getController();
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 925, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);

    }
}

then use @component to controller class
  @Component
        public class Controller {
            @Autowired
            private ItemController itemController;
            @FXML
            private TextField item;
            @FXML
            private TextField quantity;
        }


text:
Q: How to store coordinates to act like a hexagon-esque structure? I realize that many questions about pixels and hexagons have been asked, but I'm struggling to understand a certain aspect of it. Also, I'm not sure how much of a difference it'll make, but I am working in Java.
Starting off with my comprehension of the matter, I understand a Cartesian grid could be stored in a 2d array so that coordinates on the board are each an entry in the 2d array. But, I want to use a hexagonal sort of grid for a better game grid, like described on Amit's page http://www.redblobgames.com/grids/hexagons/.
I understand the concept after the hexagonal grid has been created (using x, y, z to get neighbors), but am struggling to store my coordinates. Previously, each coordinate had corresponded to an entry in the 2d array (cartesian). Now, I'm not sure how to make it correspond to get a hexagonal relationship between the coordinates.
Following the guide, I tried to offset the coordinates every other row (specifically trying the even row offset example from the link), like so:

In this, the top is the coordinates and the bottom is the visual representation of the array (blank spaces are entries with sentinels to 'skip' over, and 1s are the entries that correspond to the coordinates).
So, the neighbors of each coordinate are { {-1, 1}, {1, 1}, {1, -1}, {-1, -1}, {0, 2}, {0, -2} }. However, I don't think this is properly done? I thought of other ways to implement a hexagonal grid, which were to use a doubly linked list sort of structure and start off from the middle and relate the coordinates as 'nodes', or to hard code a map (which is sort of impossible because I plan for a large map). But, I'd rather stick with the offset idea because it's easier to use.
I think my problem is that each other row should be shifted by 1/2, but I give it 'holes' (sentinel entries). Maybe I'm supposed to convert coordinates to a hexagon using the geometry of hexagons. but I don't understand how I can use those individual hexagons when I want to path find unless they were stored in some data structure. Any code or help would be greatly appreciated.

A:         0   1   2   3   4   5
      0   1   2   3   4   5
    0   1   2   3   4   5
  0   1   2   3   4   5
0   1   2   3   4   5

If you don't mind your map having somewhat of a diamond shape, you can neatly fit a set of hexagons into a 2-d array.  The math will be consistent for travelling between nodes--
(E/W change x, NE/SW change y, NW/SE change both).
Basically, you're using the coordinate mapping as a reference.  You don't need to actually construct your map onto a two dimensional array.  Rather, you use the coordinate mapping to simplify your relationships.
For example, you could map coordinates into a hashmap like
map.put("0,2", new Tile(0,2,"Green"));
map.put("0,3", new Tile(0,3,"Yellow"));
map.put("0,4", new Tile(0,4,"Green"));
map.put("0,5", new Tile(0,5,"Green"));
map.put("1,2", new Tile(1,2,"Blue"));
map.put("1,3", new Tile(1,3,"Red"));
map.put("1,4", new Tile(1,4,"Orange"));
map.put("2,1", new Tile(2,1,"Orange"));

For any given tile, you could answer whether any given direction is available, and retrieve the tile in that direction in O(1) time by referencing the HashMap.  Your nodes (e.g. Tile objects) wouldn't need any references to neighboring nodes.  Your coordinate system would take care of that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flot charts x-axis time issues... AARGHHH I am having a difficult time getting my data to display inside of a Flot chart with the x-axis serving as the timeline.  Here is an abbreviated copy of my JSON file:
{
  "label": "ServiceReport",
  "data": [[1328983200, 53], [1328986800, 53], [1328990400, 60]]
}

I've followed the tutorials on the Flot API page, as well as this one on stackoverflow
without any luck.
When modifying the x-axis, this gets the graph to display just fine, but the x-axis is blank.
xaxis: { mode: "time", minTickSize: [1, "hour"]}

This displays 8 through 8 values (not correct according to data file), but no graph data:
xaxis: { mode: "time", minTickSize: [1, "hour"],
                min: (new Date("2000/01/01")).getTime(),
                max: (new Date("2000/01/02")).getTime()

            }

Basically, I just want to display the hours in (really any format: 5:00, 5 AM, doesn't matter) on the x-axis, and have the y-axis correlate to the Service Values.  There are 24 total timestamps in each data file (one day's worth of data).
Any help from you Flot and JavaScript/jQuery experts would be greatly appreciated!!!

A: First for the time to display, use :
 xaxis: { mode: "time",minTickSize: [1, "hour"],timeformat: "%H:%I:%S"}

I had the same problems with JSON data, caused by a bad JSON encoding file.
Are you sure that your JSON file is really a JSON file ?
Let's try something ike that to test it (with jquery for example) :
$.getJSON('yourJSONpage.php',
    function(data) {
        testData=data.pop();
        alert(testData[0]);
});

Last point, your timestamp is not correct, correct time stamp is like that "1328983200000" not like that "1328983200", if you use PHP to generate your JSON data, make sure you do something like that for the dates :
$hour=mktime($h+1,$i,$s,$m,$d,$y)*1000;


text:
Q: VSCode golang module works only in debug mode / module directory problem? I have a small golang project with go modules and I have a dependency for github.com/eiannone/keyboard.
If I start my main file with F5 (Start Debugging) it works. If I start it with CTR-F5 (run without debugging) it says it cannot find the package:
data/work/advent/d13/main.go:9:2: cannot find package "github.com/eiannone/keyboard" in any of:
    /usr/local/go/src/github.com/eiannone/keyboard (from $GOROOT)
    /home/user/work/go/src/github.com/eiannone/keyboard (from $GOPATH)

I can reproduce the same error message from console: Issuing go run d13/main.go works if I'm int the module directory (data/work/advent), but fails with the same error message if I issue the command from a different directory.
Is it possible to set the directory to be used in launch.json?
Or is there something else going on?

A: The reason you get the 'cannot find package' error is because of the package that you are trying to use aren't present inside the GOROOT and also not in the GOPATH. In order to remove the error, do try to make use of go get command followed by the link of the GitHub package.
go get github.com/eiannone/keyboard


text:
Q: JavaFX: setHgrow(...) doesn't work I couldn't get the Elements in my HBox to grow, so I downloaded the following example code from java2s.com. It serves as a minimal not working example:
package fxtest;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Fxtest extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("");
        Group root = new Group();
        Scene scene = new Scene(root, 600, 250, Color.WHITE);

        HBox hbox = new HBox();
        TextField field = new TextField();
        HBox.setHgrow(field, Priority.ALWAYS);
        hbox.getChildren().addAll(new Label("Search:"), field, new Button("Go"));

        root.getChildren().add(hbox);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

The result looks like this.
If I understand it correctly, the TextField should grow, shouldn't it?
My Java Version is 1.7.0_51
My JavaFX Version is 2.2.51-b13
Do you know why it isn't working/what I have to do?
Thanks!

A: jewelsea provided the right answer for the given example; thanks for that!
It helped me figuring out a problem with similar symptoms but another root.
If you use ScrollPanes, you need to set
    scrollPane.setFitToHeight(true);
    scrollPane.setFitToWidth(true);

in order to get the desired growing effect.

A: Why HBox.setHgrow doesn't work for you
You use a Group as the root node of your scene and groups are not resizable, so the group size does not adjust to the scene's size.

A Group will take on the collective bounds of its children and is not
  directly resizable.
By default, a Group will "auto-size" its managed
  resizable children to their preferred sizes during the layout pass

In general, you very rarely want to use a Group as the root node for a scene.
How to Fix it
Use only resizable nodes in your scene (Pane subclasses or Control subclasses).
Sample
Substitute your start method with the method below which removes the Group root node and instead makes the HBox the root node for the scene:
public void start(Stage primaryStage) {
    HBox hbox = new HBox(10);
    TextField field = new TextField();
    HBox.setHgrow(field, Priority.ALWAYS);
    hbox.setAlignment(Pos.BASELINE_LEFT);
    hbox.getChildren().addAll(
        new Label("Search:"), field, new Button("Go")
    );
    hbox.setPadding(new Insets(10));

    Scene scene = new Scene(hbox, 600, 250, Color.WHITE);
    primaryStage.setScene(scene);
    primaryStage.show();
}

Output of the sample after resizing the window (you can see that the search text field grows and shrinks to fit available space as requested):


text:
Q: Count the number of Friday's that fall on the 13th within a given year I would like to create a function that goes through the months of a given year, calculates how many Fridays fall on the 13th, and returns that number. So far this is what I have:
function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    d.setFullYear(jahr, 0, 13);
    var counter = 0;
    var months = 0;
    while(months <= 11) {
        months++;
        if(d.getDay() == 5 && d.getDate() == 13) {
          counter++;
       }
    }
    return counter;
}

I am imagining this code starts on January 13th of a given year, has a counter where the sum of days will go, and will cycle through the months. I know my code is off, but can I get some guidance?

A: Try this:
function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    var counter = 0;
    var month;

    for(month=0;month<12;month++)
    {
     d.setFullYear(jahr, month,13);
        if (d.getDay() == 5)
        {
          counter++;
        }
    }

    return counter;
}

Basically, there are only twelve days in the year with date 13. So, we simply loop through each one and check if it is a Friday or not.

A: The important bit you were missing was to update the date on every loop iteration.
function numberOfFridaythe13thsIn(jahr) {
    var count = 0;
    for (var month=0; month<12; month++) {
        var d = new Date(jahr,month,13);
        if(d.getDay() == 5){
          count++;
       }
    }
    return count;
}

console.log(numberOfFridaythe13thsIn(2015));

A: I think it will help you...
 function numberOfFridaythe13thsIn(jahr) {
            var counter = 0;
            for (i = 1; i <= 12; i++) {
                var d = new Date(i + "/13/" + jahr);
                if (d.getDay() == 5) {
                    counter++;
                }
            }
            return counter;

        }

it is for MM/dd/yyyy format.


text:
Q: Calling function recursively on all fields, and subfields in procmacro I have a derive style procedural macro, where i would like to calculate the potential maximum length of the serialized version of a struct. For example, given the struct TestStruct below, i would like to call some function with all the fields to calculate the worst case length.
#[derive(MyLengthProcMacro)]
struct TestStruct {
    f1: u32,
    f2: i64,
    f3: SomeOtherStruct
}

For primitives this could look something like:
fn get_string_length(ty: &Type) -> usize {
    let type_string = quote! { #ty }.to_string();
    match type_string.replace(" ", "").as_str() {
        "str" => panic!("String slices must be annotated with a length using #[at_arg()]"),
        "tuple" => panic!("Tuples are not supported!"),
        "char" => "a".len(),
        "bool" => "false".len(),
        "isize" => format!("{:?}", std::isize::MAX).len(),
        "usize" => format!("{:?}", std::usize::MAX).len(),
        "u8" => format!("{:?}", std::u8::MAX).len(),
        "u16" => format!("{:?}", std::u16::MAX).len(),
        "u32" => format!("{:?}", std::u32::MAX).len(),
        "u64" => format!("{:?}", std::u64::MAX).len(),
        "u128" => format!("{:?}", std::u128::MAX).len(),
        "i8" => format!("{:?}", std::i8::MIN).len(),
        "i16" => format!("{:?}", std::i16::MIN).len(),
        "i32" => format!("{:?}", std::i32::MIN).len(),
        "i64" => format!("{:?}", std::i64::MIN).len(),
        "i128" => format!("{:?}", std::i128::MIN).len(),
        "f32" => format!("{:?}", std::f32::MIN).len(),
        "f64" => format!("{:?}", std::f64::MIN).len(),
        _ => {
            // println!("Unexpected type: {:?}", type_string);
            0
        }
    }
}

The problem i am asking here is regarding any non-primitive fields, eg. f3: SomeOtherStruct. Is there a way to access the fields of fields, in a proc-macro?

A: No.
Macros are expanded before that kind of analysis is done, so the compiler has no idea what SomeOtherStruct is at that point.

However, this is not how you should implement that macro! Your way doesn't allow the user to use type aliases.
What you should do is simply use your trait recursively and use sum the <T as MyLength>::my_length() where T is the type of the field for each field.
They manually implement your trait for the primitive types.


text:
Q: inserir nomes ordenadamente em uma lista, nao estou sabendo fz isso //função de inserir ai; ai so faz isso com os 3 primeiros nomes, os outros ela nao ordena
Aluno *cad(Aluno *aluno)
{
  Aluno *aux;
  while(1)
  {
    aux = aluno;
    if(aux->prox == NULL)
    {
        Aluno *criar = novo();
        if(criar == NULL)
        {
            break;
        }
        if(strcmp(aux->nome, criar->nome) > 0)
        {
            criar->prox = aux;
            aux = criar;
        }
        else
        {
            aux->prox = criar;
        }
    }
    else
    {
        Aluno *criar = novo();
        if(criar == NULL)
        {
            break;
        }
        Aluno *aux2;
        Aluno *aux3 = aux;
        while(aux3->prox != NULL)
        {
            printf("1\n");
            aux2 = aux3->prox;
            if(strcmp(criar->nome, aux3->nome) > 0)
            {
                printf("entrei no if\n");
                criar->prox = aux2;
                aux3->prox = criar;
                break;
            }
            aux3 = aux3->prox;
        }
        if(aux3->prox == NULL)
        {
            aux3->prox = criar;
        }
    }
    aluno = aux;
}
  return aluno;
}

A: Estou supondo que exista uma função Aluno* criar().
Tente isto aqui:
#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

Aluno* criar(); // prototipo da funcao ja existente

Aluno* inserir(Aluno* alunoAInserir, Aluno* lista)
{
    Aluno* a = lista;
    Aluno* anteA = a;
    int cmpAnterior = 9;
    int cmpAtual;
    int inserido = FALSE;

    if (a == NULL)
    {
        a = lista = criar();
        return inserir(alunoAInserir, lista);
    }

    for (; a != NULL; anteA = a, a = a->prox)
    {
        if ((cmpAtual = strcmp(alunoAInserir->nome, a->nome)) != cmpAnterior)
        {
            if (cmpAnterior != 9)
            {
                if (cmpAtual < 0)
                {
                    // Insere a esquerda.
                    alunoAInserir->prox = anteA->prox /*que e o proprio a*/;
                    anteA->prox = alunoAInserir;
                }
                else if (cmpAtual == 0)
                {
                    // Insere a direita.
                    alunoAInserir->prox = a->prox;
                    a->prox = alunoAInserir;
                }

                if (cmpAtual <= 0)
                {
                    inserido = TRUE;
                    break;
                }
            }
            else if (cmpAnterior == 9 && cmpAtual < 0)
            {
                // Insere na cabeca da lista.
                Aluno* tmp = lista;
                lista = alunoAInserir;
                alunoAInserir->prox = tmp;

                inserido = TRUE;

                break;
            }

            cmpAnterior = cmpAtual;
        }
    }

    if (!inserido)
    {
        // Insere no fim da lista.
        anteA->prox = alunoAInserir;
        alunoAInserir->prox = NULL;
    }

    return lista;
}

Uso da função:
Aluno* lista = inserir(alunoAInserir, NULL);


text:
Q: How regular expression assertions can be written in shell script in ubuntu The following is a valid regex in many languages, but it doesn't work in bash:
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

How can I write this regex in a shell script?

A: Since bash does not implement lookahead assertions, you need to either use a utility which does (for example, grep with the -P option, if available on your system, or a scripting language such as Perl or Python), or break it down into different tests:
if [[ $pwd =~ [[:digit:]] &&
      $pwd =~ [[:upper:]] &&
      $pwd =~ [[:lower:]] &&
      $pwd =~ [@#$%] &&
      $pwd =~ ^.{6,20}$ ]]; then
    # $pwd satisfies all tests
else
    # $pwd fails some test
fi


text:
Q: How to get the url to the current action (after modifying some route data)? I'm localising a site via a Change Language control in the master page. I need to render the control with the current url you're on in each of the different languages.
So if you're on http://site.com/en/Home/About and you change the language to french, I need to direct you to http://site.com/fr/Home/About.
The localisation code works on the route data language property, so I've been trying to figure out how I can:

*

*Get access to the current action (with all original parameters)

*Get the url to the current action (with all original parameters) with the route data changed.

Can anyone point me in the right direction?
I've tried passing the ViewContext from the parent into the UserControl, which gives me access to the route data but I can't figure out how to get the language routed url from that.

A: I ran this on the site I'm working on locally and it seemed to work.  There's probably a cleaner way.
HttpRequestBase hrb = HttpContext.Request;
System.Uri url = hrb.Url;
string[] test = url.AbsoluteUri.Split('/');
int nIndex = 0, nCounter = 0;
foreach(string str in test)
{
  if (str.Contains("site.com"))
  {
    nIndex = nCounter;
    break;
  }
  nCounter++;
}
string strLanguage = test[nIndex + 1];

Obviously the +1 can even go in the IF statement, but I didn't think it looked good there.  Hope this helps some.

A: I'm not 100% happy with this, I haven't got to a stage where I can fully test the impact of this but this is what I'm going for so far. Please do answer if you have a better solution.
I pass the ViewContext from the masterpage so I get the ViewContext with route data from whatever url you're currently on.
private string GetLocalisedUrl(ViewContext viewContext, string language)
{
    viewContext.RouteData.DataTokens[LANGUAGE_ROUTEDATA_KEY] = language;
    UrlHelper helper = new UrlHelper(viewContext.RequestContext);

    return helper.Action(viewContext.RouteData.Values["action"].ToString(), viewContext.RouteData.Values["controller"].ToString(), viewContext.RouteData.DataTokens);
}


text:
Q: Send get data again to another page in php In my website I have some url like
example.com/test/test?name=dd&type=a
I want to send data again to another page like:-
example.com/test/test/again?name=dd&type=a
How can I send data to /again from /test tell me please

A: You first need to store the data from get variables
$name = $_GET['name'];
$type = $_GET['type'];

Now assuming you want to send this data to page2 on  button click
<form method="get" action="page2.php">
      <input type="hidden" name="name" value="<?php echo $name;?>">
      <input type="hidden" name="type" value="<?php echo $type;?>">
      <input type="submit">
</form>

Do the same for getting those variable at page2
$name = $_GET['name'];
$type = $_GET['type'];

Hope this will help you!


text:
Q: How to convert Object to array of object Here is My input Object.
let data = {
  "01-02-20":[{id:1}],
  "23-02-20":[{id:1}]
}

I am trying convert array of objects by this code
let res = Object.entries(data).map(( [k, v] ) => ({ [k]: v }));

But I didn't get my expected value :
My expected result should be like this:
let result = [
  {
    date: '01-02-20',
    item: [{ id: 1 }],
  },
  {
    date: '23-02-20',
    item: [{ id: 1 }],
  },
]

How can I get my expected result?

A: You are using the date as key and the value as value in the resulting objects. Instead you should be using two key-value pairs, one for date using the key as value and one for item using the value as value, like so:
let res = Object.entries(data).map(( [k, v] ) => ({ date: k, item : v }));

More concise using shorthand property names:
let res = Object.entries(data).map(( [date, item] ) => ({ date, item }));

Demo:

let data = {
  "01-02-20": [{ id:1 }],
  "23-02-20": [{ id:1 }]
};

let res = Object.entries(data).map(( [date, item] ) => ({ date, item }));

console.log(res);


text: Q: Is Fedora's Metalink Configuration File Shared Anywhere? I have inherited administration of an air-gaped network with mirrors of various Linux repositories. Currently how the EPEL repository is configured is by using the baseurl key in the epel.repo configuration file. The metalink key is commented out because when configured yum and dnf will look for a dynamically generated XML file, which won't work without the proper parameters of course. So before I go reverse-engineering it I figured I would ask if it is properly documented somewhere. The pages about it on the Fedora Wiki that I found 1 2 appear incomplete and abandoned.


text:
Q: Can fish shell do wildcard globbing in an if statement? I'm having trouble understanding whether I can use wildcard globbing in an if statement in fish. This switch/case works as expected:
# correctly echos macOS on macOS
switch "$OSTYPE"
    case 'darwin*'
        echo 'macOS'
    case '*'
        echo 'not macOS'
end

However, I cannot get an if statement version of the same thing to work.
# doesn't work - prints 'not macOS' on macOS
if [ "$OSTYPE" = 'darwin*' ]
    echo 'macOS'
else
    echo 'not macOS'
end

In zsh/bash you can do something like this:
[[ $OSTYPE == darwin* ]] && echo 'macOS' || echo 'not macOS'
Or, more verbosely,
if [[ $OSTYPE == darwin* ]]
  then echo 'macOS'
  else echo 'not macOS'
fi

My question is, does fish support wildcard globbing against a variable in if statements? Am I doing this wrong? I cannot find an example in the fish docs that tells me either way.
NOTE: I'm not asking about checking $OSTYPE in fish. I know there are better ways to do that. My question is limited strictly to whether it is possible to do wildcard globbing in an if statement in fish.

A: No.
Use switch like you said, or the string builtin like
if string match -q 'darwin*' -- "$OSTYPE"

The if isn't important - the command you are running in your example is [, which is an alternative name for test, which is a builtin with documentation at http://fishshell.com/docs/current/commands.html#test (or man test or help test).


text:
Q: Not possible to place actions with SSJS in Action Bar of XPage OneUI? I¨m working quite a while with XPages, and this must be a rookies question:
I want to place my common actions like "Save Document", "Edit", "Cancel" in the Action Bar in the upper part of the OneUI of the extlib (Place Bar).
I succeeded to get any basic (or other) nodes in the place bar, but I can only give them client side JS, not the usual server side JS which I gave to a button.
Am I missing sth? Of course I searched (here + google), but cannot find any answer for this simple question.
Hope you can "push me into the right direction" ....
thx, Uwe

A: Add the buttons "Save" and "Edit" as xe:basicLeafNode to the action bar
<xe:applicationLayout ... >
    ...
        <xe:this.placeBarActions>
           <xe:basicLeafNode
              label="Save"
              submitValue="save">
           </xe:basicLeafNode>
           <xe:basicLeafNode
              label="Edit"
              submitValue="edit">
           </xe:basicLeafNode>

and define the code you want to execute as SSJS code in xe:applicationLayout's onItemClickevent
  <xp:eventHandler
     event="onItemClick"
     submit="true"
     refreshMode="complete">
     <xp:this.action><![CDATA[#{javascript:
            var s = context.getSubmittedValue();
            if (s=="save") {
                print("write code here for save");
            } else if (s=="edit") {
                print("write code here for edit");
            }
        }]]></xp:this.action>
    </xp:eventHandler>
</xe:applicationLayout>

You can test in onItemClick event with context.getSubmittedValue() for basicLeafNode's submitValue and get to know this way which button was clicked.


text:
Q: Cannot resolve symbol despite Declaration I am a newbie to Android and I am implementing a WebView App where I can open a particular website within the app window. But, In the last line of this code I am getting the error:

Cannot resolve symbol 'imgHeader'

public class MainActivity extends AppCompatActivity {

private String postUrl = "https://api.androidhive.info/webview/index.html";
private WebView webView;
//private ProgressBar progressBar;
//private ImageView imgHeader;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    webView = (WebView) findViewById(R.id.webView);
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    ImageView imgHeader =  findViewById(R.id.backdrop);

    // initializing toolbar
    initCollapsingToolbar();

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(postUrl);
    webView.setHorizontalScrollBarEnabled(false);
}

/**
 * Initializing collapsing toolbar
 * Will show and hide the toolbar txtPostTitle on scroll
 */
private void initCollapsingToolbar() {
    final CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbar.setTitle(" ");
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    appBarLayout.setExpanded(true);

    // hiding & showing the txtPostTitle when toolbar expanded & collapsed
    appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        boolean isShow = false;
        int scrollRange = -1;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (scrollRange == -1) {
                scrollRange = appBarLayout.getTotalScrollRange();
            }
            if (scrollRange + verticalOffset == 0) {
                collapsingToolbar.setTitle("Web View");
                isShow = true;
            } else if (isShow) {
                collapsingToolbar.setTitle(" ");
                isShow = false;
            }
        }
    });

    // loading toolbar header image
    Glide.with(getApplicationContext()).load("https://api.androidhive.info/webview/nougat.jpg")
            .thumbnail(0.5f)
            .crossFade()
            .diskCacheStrategy(DiskCacheStrategy.ALL);
            .into(imgHeader);
}

}
I have already declared the 'imgHeader' variable so I don't understand the reason for this error. I also have the correct ids in my XML file:
<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:fitsSystemWindows="true">

<include
    layout="@layout/toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="12dp"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginEnd="64dp"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleTextAppearance="@android:color/transparent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                android:contentDescription="Contents"/>
        </RelativeLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="-7dp"
    android:indeterminate="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

A: put
ImageView imgHeader =  findViewById(R.id.backdrop);

in your initCollapsingToolbar function.  Look up variable scopes to find out why.


text:
Q: Open specific links from a webpage with javascript? I'm using Tampermonkey, and I can't seem to get jQuery to work on it so this has to be Javacript only.
I'm trying to get a script to open (in a new window) the link of an item on a webpage. I've got a list of items I need to open, here is an example of those items:
...
...
...

   etc.

As you can see, the item is defined by a class and an href. The class is not unique, but the href is.
I'm new to programming but this is my idea on how to open specifically those links from the page:

*

*The script gets elements with class="market_listings",
just to narrow down the search of hrefs on the page.

*The script looks if the href of those elements corresponds with
"http://blabla.com/item*"

*The script opens a new window with that href.
I have pretty much 0 experience with coding, but this is how I'd start it, considering I only want to open items 1 and 3:
function gethrefandopenwindow() {
         var items = document.getElementsByClassName('market_listings')

//don't know how to code from here

         if (*a href of items corresponds to*: 'http://blabla.com/item1')

            {
             *open new window to href of item1*
             }

         if (*a href of items corresponds to*: 'http://blabla.com/item3')

            {
             *open new window to href of item3*
             }

         else {
              *refresh the page and start over*
              }
}

As I said, I have barely programming experience, so I don't know if this is possible, and if it is and you're willing to help, please explain it to me like I'm a TOTAL idiot/newbie. :)
The only other way I could think of is this one: Javascript getElement by href? ;  Except I don't know how to apply it in my situation due to my noobiness (and how to open a specific href out of the elements).
Anyway, I hope you can help me,
Thank you!

A: It looks like you had the right idea.  This function might get you moving in the right direction.
function OpenHrefsInNewWindow() {
    //Get reference to your elements
    var items = document.getElementsByClassName("market_listings");

    for (var i = 0; i < items.length; i++) //Loop through your elements
    {
        //Verify that the href starts with http://blabla.com/item
        if (items[i].href.indexOf("http://blabla.com/item") === 0)
        {
            //If it does, open that URL in a new window.
            window.open(items[i].href, "_blank");
        }
    }
}

Another way to write it:
function OpenHrefsInNewWindow() {
    //Get reference to your elements
    var items = document.getElementsByClassName("market_listings");
    var i = 0;

    while(i < items.length) //Loop through your elements
    {
        //Verify that the href starts with http://blabla.com/item
        if (items[i].href.indexOf("http://blabla.com/item") === 0)
        {
            //If it does, open that URL in a new window.
            window.open(items[i].href, "_blank");
        }

        i++; //Increment i here.
    }
}

A: Can retrive the url of link taking value of atribute and do ankthing later
Url = $(this).attr ('href')


text:
Q: Dependent tests in rspec I write functional tests, and I need to do tests that were being would depend on the passage of previous tests. Let's say I have a button that opens a window in which there is a functional. That is, in order to check this functionality, I need to first check the correct operation of the button (ie, open window or not functional). So, I need to do so that would be if the test failed on a button click, the tests did not run to check the functional window. Writing tests separately - for me is not an option. I would like to see something like this:
describe "some tests" do
  open_result = nil

  it "should check work button" do
    click_to_button()
    open_result = window_opened?
    open_result.should == true
  end

  if open_result

    describe "Check some functional" do

      it "should check first functional"

      it "should check second functional"

    end

  end

end

I know that this method does not work for rspec. It's just a simple description of what I want to see. Is it achievable using rspec? If not, are there other ways (gems, etc.)

A: RSpec is designed as a unit tests framework, so it may be a little difficult to get perfect functional-test behavior from it. In RSpec's philosophy tests must be independent. It is especially important when you use autotest: in this case the order of execution is truly unpredictable. Sad but true.
Still, of course you can save some state between test using global ($a) or instance (@a, not sure here) variables. Anyway you need to move if into it block so that it will be executed in time. You may use pending keyword to interrupt a test without failing it in case if pre-condition is not met.
BUT
I'm sure that the best solution is to avoid golden hammer antipattern, and not to write functional tests in unit-test framework. You want not to test some separate functions. You do want to test scenarios. So I suggest trying some scenario-testing suite.
Behold, Cucumber! Usage is simle:

*

*Define parametrized scenario steps in Ruby, and expectations in RSpec-style

*Write scenarios in natural language (yes, not only English, but even Russian or whatever — the power of Regexps is on your side)
In your case, you will have in features/step_definitions/gui_steps.rb something like
Given /I pushed a button "(.*)"/ do |name|
    @buttons.find(name).click() # This line is pseudo-code, you know
end

and something similar for checking window opening, etc (see examples). Then you can combine defined steps in any way, for example your two scenarios might look like
Scenario: Feature 1
    Given I pushed a button "go"
    And I focus on opened window
    When I trigger "feature 1"
    Then I should se "result 1" in text area

Scenario: Feature 2
    Given I pushed a button "go"
    And I focus on opened window
    When I trigger "feature 2"
    Then I should se "result 2" in text area

In both cases, if some step of scenario fails (like I focus on opened window — if it is not opened), the consequent steps are not executed — just as you want. As a bonus you get an extremely detailed output of what happened and on what step (see pics on the site).
The good news is that you don't always need to define all the step yourself. For example, when you test a web app, you can use webrat steps for typical things like When I go to url/a/b/c and Then I should see text "foo" on the page. I don't know which GUI testing framework you use, but probably there are already steps for it, so I suggest you to google on Cucumber %framework name%. Even if not, writing these steps once will not be more difficult than trying to make Cucumber from RSpec.


text:
Q: Interpolate points to lines every odd and even number We are working in Oracle Database 11g. There is a table with sdo_geomerty column(representing a line) which contains the following :
RSID,       LT,      LF,      GEOM
584908,     30,      34,      [MDSYS.SDO_GEOMETRY]
1312994,     1,      9,       [MDSYS.SDO_GEOMETRY]

In the column of geom is the MDSYS.SDO_ORDINATE_ARRAY there are more than 2 points with known coordinates, so we can say that is a curve too.
For the 2 records above, we want to compute the coordinates for the points placing at the even and odd intervals correspondingly.
To be clear, for the first record we want the point coordinates in 30,32,34.
For the second record we want the point coordinates in 1,3,5,7,9.
The start and end of each line is known as we can extract the first and last pair of coordinates from geometry column.
I am looking for a program logic (I am working on these languages C#, Python, pL SQL) that combines the Pythagorean theorem and the relations between Polar and Rectangular Coordinates to find the coordinates at even intervals when the edges of the line are even and odd numbers correspondingly.
These numbers are street road numbers and the lines depict the road network.
Visit http://math.ucsd.edu/~wgarner/math4c/textbook/chapter9/polar_coordinates.htm
I have good knowledge on plsql.

A: If I understand correctly, it looks like you need something similar to dynamic segmentation. I have written a small series of posts on this a while back. Have a look at Part 2 and Part 3 to see if they help.


text: Q: не получается вызвать django-admin пытаюсь научиться джанго, вроде установил его через pip, даже могу весрию проверить и все равно выдает такую ошибку. не пойму в чем дело(в обычной командной строке, pycharm тоже самое выдает)


text:
Q: XCode 4 automatic navigation to another view In Xcode 4...
I would like to know how to do automatic redirection (or navigation) to another UIViewController after a specific time
Thanks

A: how about
     [self performSelector:@selector(yourRedirectMethod) withObject:nil afterDelay:1]


text:
Q: Write to event log from a driver I want to write to the event log from a driver.
I know that i need to use IoAllocateErrorLogEntry and I also added the registry key

HKLM\System\CurrentControlSet\Services\EventLog\driverName

Now I want to set the source of the log to be the "driverName".
I tried to follow the "write log" instruction in here but it doesn't seem to work.
How can I write to the event log with a specific source?

A: 1) Don't forget to register source as  Registering as a Source of Error Messages
2)Don't leave spaces between iologmsg.dll and your driver in registry
3) Sometimes you will need to reboot after driver installation to see canges
And all will work!


text:
Q: Convergence of exponential random variables How to find necessary and sufficient condition when $X_i \text{ ~ } \text{Exp} (\lambda_i)$ sequence of independent random variables converge to zero in distribution and almost surely.
Thank you very much for your help in advance!

A: Let's see the first part, convergence in distribution means that $F_{X_n}(x) \to_{n \to \infty} F_X(x) \;\;\; \forall x$.
Thus: $ F_{X_i}(x) \to F_0(x) \iff 1-e^{-\lambda_ix} \to 1\text{ if } x> 0 \iff  \lambda_i \to \infty$.
So we found the necessary and sufficient condition.
Let's see the other part: almost surely convergence means that $ \mathbb{P}(\lim_{n \to \infty} X_n=X)=1 $.
Consider the following: $\mathbb{P}(\neg(X_i\to 0))=\mathbb{P}(\bigcup_{m=1}^{\infty}\{\text{for infinitely many } i \;\;|X_i|>\frac1m\}) \leq \sum_{m=1}^{\infty}\mathbb{P}(\text{for infinitely many } i \;\;|X_i|>\frac1m)$
But: $\mathbb{P}(X_i > \frac1m) \leq \frac{\mathbb{E}(X_i)}{\frac1m}=\frac{m}{\lambda_i}$ (We know it from Markov inequality.)
Thus: $\sum_{m=1}^{\infty}\mathbb{P}(X_i > \frac1m)\leq \sum_{m=1}^{\infty}\frac{m}{\lambda_i}&lt\infty \iff \sum_{m=1}^{\infty}\mathbb{P}(\text{for infinitely many } i \;\;|X_i|>\frac1m)=0$ (It follows from Borel-Cantelli lemma.)
Thus: $\mathbb{P}(\neg(X_i\to 0))=0 \Rightarrow \mathbb{P}(\text{for infinitely many } i \;\;|X_i|>\frac1m))=0 \iff \sum_{i=1}^{\infty}\frac{1}{\lambda_i}&lt\infty$ (It follows from Borel-Cantelli lemma.)
So we found the necessary and sufficient condition.

A: Part 1 is answered by Dawson. For part 2, we need to use both Borel Cantelli lemmas:

*

*Use the first BC lemma, for any $\epsilon>0$ we have $\sum P(X_i>\epsilon) &lt \infty\implies\sum e^{-\lambda_i\epsilon} &lt \infty$ is the sufficient condition as $P(\lim_{n\to \infty} X_n>\epsilon)=0$.

*Use the second BC lemma, as the sequence is independent. $\sum P(X_i>\epsilon) = \infty\implies \sum e^{-\lambda_i\epsilon} = \infty$ is the condition for $P(\lim_{n\to \infty} X_n>\epsilon)=1$.

This means $\sum e^{-\lambda_i\epsilon}&lt \infty$ is both necessary and sufficient.
PS: As noted in a comment, it is better not to use Markov inequality in such proofs as it is a weak inequality.


text:
Q: Ruby Array - reverse iterate with next and before element How to reverse iterate an Array with next and before element of the current element ?
Is it possible to use each_cons with reverse_each ?

A: This might work for you:
class Array
  alias :old_each :each
  def each
    reverse.old_each {|e| yield e}
  end
end

a = [1,2,3]
a.each {|e| print "#{e} "}  # => 3 2 1

Note you have to be careful with this because Array, for efficiency reasons, overloads some Enumerable methods without using each.
I used this in a big project with my previous employer, adding it right before I left.  Boy, was I glad to get out of there.
Edit: It just occurred to me that I could have improved this in the above-referenced project:
  def each
    if rand(1000) == 500
      reverse.old_each {|e| yield e}
    else
      old_each {|e| yield e}
    end
  end

A: Yes, it is possible.
[1,2,3,4,5,6].reverse_each.each_cons(3) { |before, current, next_|
  p [before, current, next_]
}

prints
[6, 5, 4]
[5, 4, 3]
[4, 3, 2]
[3, 2, 1]

([nil]+[1,2,3,4,5,6]+[nil]).reverse_each.each_cons(3) { |before, current, next_|
  p [before, current, next_]
}

prints
[nil, 6, 5]
[6, 5, 4]
[5, 4, 3]
[4, 3, 2]
[3, 2, 1]
[2, 1, nil]


text:
Q: Difference between {climb/climb up/climb down/climb on} I saw him climbing up/on or climb the tree to pluck the mangoes.
"Climb", by itself, means to go upward gradually. Then why do we use climb down?
How do we differentiate and use them in a sentence? Can't I simply use climb?

A: climb / climb up: to go up something towards the top… e.g:

*

*
She climbed up the stairs.

*
The car slowly climbed the hill.

climb down: to move down, especially with difficulty or effort… e.g:

Can you climb down?

For more examples, visit this Oxford Learners Dictionaries website.

A: You can use the verb climb without up to mean to go up, but it's more common and idiomatic to use "climb up".  Moreover, if you use climb down to mean to go down, it's more appropriate to use climb up for moving up.
As explained by Jasper in his comments, 'climb on' is also used.


text:
Q: python regex - identify String with more than N non-alphaNumerics I want to identify strings with more than 3 non-alphanumerics (except \.\- \s) in it, which counts punctuations & special characters.
I've tried with below regex but it identifies strings with "non-alphanumerics in sequence"

([^a-zA-Z0-9.-\s]){2,}

eg: abc__def is identified, ab_c_d is not identified
I want to identify any string which has more than 3 non-alphanumerics (except \.\- \s)

A: If you want strings to be identified in which at least three (as suggested by your examples) non-alphanumerics occur, not necessarily in sequence, you can use:
([^a-zA-Z0-9.\-\s].*){3}

You can simply use {3} because .* at the end will take care of the remainder of the string.

A: You can use following for checking strings with more than 3 non-alphanumerics
import re
reg = r'.*([^a-zA-Z0-9\.\-\s]{4}).*'

print(re.search(reg,"!$#@abcdef"))
print(re.search(reg,"123abc"))
print(re.search(reg,"#$abc"))
print(re.search(reg,"abc____def"))
print(re.search(reg,"abc---def"))

Demo
"\W" i.e.([^a-zA-Z0-9_]) can also be used for non-alphanumerics but that will exclude "_".


text:
Q: Database connection not working - System.Data.SqlClient.SqlException: No process is on the other end of the pipe I am trying to connect to a database on my local machine, but keep getting an error.
This is just for a school project, but I can't seem to figure out where I am going wrong. I reviewed a lot of other answers, and tried what they suggested, but have yet to find success. The goal at this point is for my method to return an open connection so that I may use it throughout my App.
Here is my connection string:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
       <add name="AdventureWorks"
            connectionString="data source=Desktop;initial catalog=AdventureWorksLT2008R2"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Here is my method that returns an open connection:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Repository.DataAccess
{
   public class DBFactory
   {
       public static IDbConnection GetLocalDbConnection()
       {
            string conn = ConfigurationManager.ConnectionStrings["AdventureWorks"].ToString();
            IDbConnection connection = new SqlConnection(conn);
            connection.Open();

            return connection;
       }
   }
}

And last but not least, here is the error:

System.Data.SqlClient.SqlException: A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
----> System.ComponentModel.Win32Exception : No process is on the other end of the pipe

A: You have not entered any credentials in the connection string, nor are you using windows authentication it seems.
Either use windows authentication:
"data source=Desktop;initial catalog=AdventureWorksLT2008R2;Integrated Security=true"

Or specify an SQL user with login permissions:
"data source=Desktop;initial catalog=AdventureWorksLT2008R2;UID=myUser;PWD=myPass"

For even more connectionstring goodness, see msdn. Trusted_Connection=yes might be required too.


text:
Q: Detect when the TinyMCE text editor is ready(after initialization) Since it takes some time to load up the tinyMCE text editor, I use useEffect, useRef hooks to detect when the text editor is ready and will probably update the state to render the editor rather than spinner. However, useEffect isn't invoked even after the initialization(editorRef.current is being watched over).
Is there anything wrong with this approach?
import React, { useRef, useEffect } from "react";
import { Editor } from "@tinymce/tinymce-react";

export default function App() {
  const editorRef = useRef(null);
  useEffect(() => {
    console.log("editor is ready")
  }, [editorRef.current]);
  return (
    <>
      <Editor
        onInit={(evt, editor) => (editorRef.current = editor)}
        initialValue="
This is the initial content of the editor.
"
        init={{
          height: 500,
          menubar: false,
          plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table paste code help wordcount",
          ],
          toolbar:
            "undo redo | formatselect | " +
            "bold italic backcolor | alignleft aligncenter " +
            "alignright alignjustify | bullist numlist outdent indent | " +
            "removeformat | help",
          content_style:
            "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
        }}
      />
    </>
  );
}

A: You can try to create a state to store the editor object got from the onInit method parameter.
Set this state as a dependency in a useEffect hook.
In the onInit method, call the setState hook.
See extract code below:
const [editor, setEditor] = useState(null);

useEffect(() => {
    console.log(editor);
}, [editor]);

return (
    <Editor
        onInit={(evt, editor) => {
            setEditor(editor);
            editorRef.current = editor;
        }}
    />
);


text:
Q: What is sharding in machine learning and how to do sharding in Tensorflow? What is sharding in the context of machine learning specifically ( a more generic antic question is asked [here][1] ) and how is it implemented in Tensorflow ?
What is referred to as sharding, why do we need sharding altogether, when speaking about the data pipeline in machine learning ?

A: In Tensorflow -
In Dataset the function shard() creates a Dataset that includes only 1/num_shards of this dataset. Shard is deterministic. The Dataset produced by A.shard(n, i) will contain all elements of A whose index mod n = i.
A = tf.data.Dataset.range(10)
B = A.shard(num_shards=3, index=0)
list(B.as_numpy_iterator())
[0,3,6,9]
C = A.shard(num_shards=3, index=1)
list(C.as_numpy_iterator())
[1,4,7]
D = A.shard(num_shards=3, index=2)
list(D.as_numpy_iterator())
[2,5,8]

Important caveats: Be sure to shard before you use any randomizing
operator (such as shuffle).
Generally it is best if the shard operator is used early in the dataset pipeline. For example, when reading from a set of TFRecord files, shard before converting the dataset to input samples. This avoids reading every file on every worker. The following is an example of an efficient sharding strategy within a complete pipeline:
Autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right tf.data.experimental.AutoShardPolicy is set).
This is to ensure that at each step, a global batch size of non overlapping dataset elements will be processed by each worker.
Setting autosharding options, example
dataset = tf.data.Dataset.from_tensors(([1.],[1.])).repeat(64).batch(16)
options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.DATA
dataset = dataset.with_options(options)

There is no autosharding in multi worker training with ParameterServerStrategy.
Autosharding options are

*

*AUTO: This is the default option which means an attempt will be made to shard by FILE. The attempt to shard by FILE fails if a file-based dataset is not detected.

*FILE: This is the option if you want to shard the input files over all the workers. You should use this option if the number of input files is much larger than the number of workers and the data in the files is evenly distributed. For example, let us distribute 2 files over 2 workers with 1 replica each. File 1 contains [0, 1, 2, 3, 4, 5] and File 2 contains [6, 7, 8, 9, 10, 11]. Let the total number of replicas in sync be 2 and global batch size be 4.
Worker 0:
Batch 1 = Replica 1: [0, 1]
Batch 2 = Replica 1: [2, 3]
Batch 3 = Replica 1: [4]
Batch 4 = Replica 1: [5]
Worker 1:
Batch 1 = Replica 2: [6, 7]
Batch 2 = Replica 2: [8, 9]
Batch 3 = Replica 2: [10]
Batch 4 = Replica 2: [11]

*DATA: This will autoshard the elements across all the workers. Each of the workers will read the entire dataset and only process the shard assigned to it. All other shards will be discarded. This is generally used if the number of input files is less than the number of workers and you want better sharding of data across all workers. The downside is that the entire dataset will be read on each worker. For example, let us distribute 1 files over 2 workers. File 1 contains [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]. Let the total number of replicas in sync be 2.
Worker 0:
Batch 1 = Replica 1: [0, 1]
Batch 2 = Replica 1: [4, 5]
Batch 3 = Replica 1: [8, 9]
Worker 1:
Batch 1 = Replica 2: [2, 3]
Batch 2 = Replica 2: [6, 7]
Batch 3 = Replica 2: [10, 11]

*OFF: If you turn off autosharding, each worker will process all the data. For example, let us distribute 1 files over 2 workers. File 1 contains [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]. Let the total number of replicas in sync be 2. Then each worker will see the following distribution:
Worker 0:
Batch 1 = Replica 1: [0, 1]
Batch 2 = Replica 1: [2, 3]
Batch 3 = Replica 1: [4, 5]
Batch 4 = Replica 1: [6, 7]
Batch 5 = Replica 1: [8, 9]
Batch 6 = Replica 1: [10, 11]
Worker 1:
Batch 1 = Replica 2: [0, 1]
Batch 2 = Replica 2: [2, 3]
Batch 3 = Replica 2: [4, 5]
Batch 4 = Replica 2: [6, 7]
Batch 5 = Replica 2: [8, 9]
Batch 6 = Replica 2: [10, 11]

A: Sharding is a very important concept which helps the system to keep data into different resources according to the sharding process.
Consider a very large database whose sharding has not been done. For example, let's take a DataBase of a college in which all the student's record (present and past) in the whole college are maintained in a single database. So, it would contain very very large number of data, say 100, 000 records.
Sharding can be used in machine learning too... to save your files and models at different locations so that you can use it whenever you want them.
Using Sharding in tensorflow take reference from the following link
https://www.tensorflow.org/jvm/api_docs/java/org/tensorflow/op/xla/Sharding


text:
Q: Referencing ResultSet/Using the Next() method I'm using JavaFX to create a basic GUI. I have a database created in MySQL to store the data. (DBConnect) (connector/j)
This is my very first attempt at connecting the two, as well as using ResultSets/DBConnect
Currently, I have 3 Classes: my Game class, my GameUI class (main), and my DBConnect class.
I am attempting to Reference the ResultSet in my GameUI class, that was originally declared in Game class.
public class Game {

    private static DBConnect dbc;
    private static Connection conn;
    public ResultSet rs;
    int id;
    String name;
    float price;
    String vendor;
    int rating;

    public Game() {

        try {
            conn = dbc.connect();

            String SQL = "Select * from Person";

            rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE).executeQuery(SQL);

            System.out.println("list result set for record..");
            printRs(rs);
        } catch(SQLException ignore) {

        }
    }

My User Defined moveNext() method:
   public Game moveNext() {
        Game g = new Game();
        try {

            if(rs.next() == false)
                rs.previous();
            g.setGameId(rs.getInt("gameId"));
            g.setGameName(rs.getString("gameName"));
            g.setPrice(rs.getFloat("price"));
            g.setVendor(rs.getString("vendor"));
            g.setRating(rs.getInt("rating"));

        } catch(SQLException e) {
            e.printStackTrace();
        }

        return g;
    }

The GameUI class i am trying to reference it in:
public class GameUI extends Application {
    private Button firstButton = new Button("First");
    private Button createButton = new Button("Create");
    private Button updateButton = new Button("Update");
    private Button deleteButton = new Button("Delete");
    private Button lastButton = new Button("Last");
    private Button nextButton = new Button("Next");
    private Button prevButton = new Button("Prev");
    GridPane grid = new GridPane();
    HBox hbox = new HBox(14);

    private static DBConnect dbc;
    private static Connection conn;
   // private static

    private Pane initButtons() {
        hbox.getChildren().addAll(firstButton, createButton, updateButton, deleteButton, lastButton, nextButton, prevButton);

        nextButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                Game.rs.moveNext();
            }
        });

    return hbox;

    }

My Question is, can I Reference my ResultSet  (Game class) in my nextButton event handler (my GameUI class) OR do I have to declare a new result set?
Is this the right place for my user defined moveNext() method, or should I use next()?
I will post more code on request.

A: You can pass the result set further, but it is bad practice (See Is it Ok to Pass ResultSet?). From what I see from the code you posted it is mainly an issue with the layering of the different parts of the application, that should be separated:
Database related code belong into one layer. No other layer should directly talk to the DB or handle any DB specific objects. To achieve this the DBConnection class should handle all database related stuff. To pass data from the database to the other layers and vice versa you use a data transfer object (DTO) which is basically an object representation of a specific result set. Usually this boils down to one DTO per database table.
Then you have an intermediate layer, lets call it service layer, which is used to communicate from the UI to the database and do some computation.
On top of that you have the UI layer where your application lives. Here you have to consider which actions belong into that layer and what should better be delegated to the service layer.
Take also a look at this wikipedia article: https://en.wikipedia.org/wiki/Multitier_architecture


text:
Q: Multiple usage of generator from list in Python Basically, I'm in following situation - I generate a list, e.g.
l = [2*x for x in range(10)]

which I iterate through later on multipletimes, e.g.
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18

The problem is that the list is way too large to fit into memory, hence I use its generator form, i.e.:
l = (2*x for x in range(10))

However, after this construction only first iteration works:
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    #
for i in l: print i    #

Where is the problem? How may I iterate through it multipletimes?

A: Your generator is exhausted the first time. You should recreate your generator each time to renew it:
l = (2*x for x in range(10))
for i in l: print i
l = (2*x for x in range(10))
for i in l: print i

(Note: you should use xrange in python 2 because range creates a list in memory)
You can create also a shortcut function to help you or even a generator function:
def gen():
    for i in range(10):
        yield 2 * i

and then:
 for i in gen(): print i
 for i in gen(): print i

A: You can also iterate on the generator directly:
for i in (2*x for x in range(10)): print i
for i in (2*x for x in range(10)): print i
...


text:
Q: How can I `man print`? Where can I find more information about the command(?) print since I don't receive a result when I input man print? For example, in the zsh I can do the following:
$ print "Hello, world\!"
Hello, world!

I've seen print -P foo and print -n bar used among other flags and have no idea what they mean nor do I know where to look for further information. So we have two questions really:

*

*Where does print come from and where can I find documentation for it?

*Where does one find documentation for similar items that are not to be found in the man pages?

NOTE: For clarification, I'm not trying to print a sheet of paper. I am also aware of printf, which allows for formatted output and has a man page.

A: In zsh, at the prompt, type print, and then Alt-H.
If it gives you the man page for the print system command instead of the print builtin, you may want to follow the instructions given under Accessing On-Line Help at:
info zsh Utilities

For zsh documentation, I prefer to use info in general. The zsh documentation is properly indexed and it's very easy to find documentation using info.
For instance to find the documentation for print, type info zsh, and within info, type i to bring up the index prompt and type print (you can throw in a couple of Tab to get a completion list). Or just run
info zsh print

To open the zsh info book and jump directly to the print index entry.

A: Documentation for the print command
man print only gives you information about a command called print. Unfortunately, the command to print a file is not called print.
Ksh and zsh have a built-in command print. Like all built-ins, they are documented in the manual for the shell (man zshbuiltins or the very long man zshall for zsh). You can tell that a command is built-in with type:
$ type print
print is a shell builtin

apropos print would show a list of commands whose description contains the word "print"; what you're looking for is in there, but buried inside a lot of other commands where "print" is used in the sense of "display text in the terminal".
On Debian and derived distributions including Ubuntu, there is a command called print, which has a man page. It is part of the mime-support package, which also provides commands see, edit and compose. This package uses /etc/mime.types to determine the file's MIME type from the file name extension and /etc/mailcap and ~/.mailcap to determine which program to use.
On most Linux distributions, xdg-open plays a similar role to Debian's edit, but there is no analog for print.
A primer on printing from the command line
Most unix installations these days use CUPS for printing. This system originated on Mac OS X but is now dominant on Linux and present on other unix variants as well. CUPS is easiest to configure through its web interface at http://localhost:631/.
If the printer is already configured and you want to print, depending on your system, the command is either lp or lpr. The simplest form of the command is lp myfile.ps or lpr myfile.pdf; depending on which printing system your computer uses, these commands may support many options. Check the man page on your system for details. If you need to specify a printer name, it's lp -d printername myfile.ps or lpr -Pprintername myfile.ps.
The traditional file format for printing is PostScript. Nowadays, most printing systems support PDF out of the box as well, and possibly other formats. I don't think there's an easy way to find out what input formats are supported, so I recommend converting your file to PS or PDF before printing (you'll have more control over layout options that way anyway).
You can see what files are currently being printed with the command lpstat or lpq. This lets you know when your file has finished printing (or rather when it's been fully transmitted to the printer). This also tells gives you the job ID for your print job, which you can use to cancel the job with lprm or cancel. You can also see a list of available printers with lpstat -a or lpq -a.
If your system is using CUPS, another useful command is lpoptions. The command lpoptions -l lists printer options that you can use on the lp or lpr command lines; for example, with many duplex printers, lp -o Duplex=DuplexNoTumble prints double-sided.

A: You are probably looking for printf. Since printf is a build in of your shell, you should look in the shell's man page, probably with man bash and search for printf

A: If you're asking about how to print from the command line the command you're looking for is usually lpr or lp. These are frontend tools for printing files from the command line.

*

*lp man page

*lpr man page
NOTE: You can search the man pages using -k to search for keywords. If you'd done man -k print you would've found these pages.
To see what printers are available you can use lpstat -a, for example:
$ lpstat -a
brfax accepting requests since Wed 19 Jun 2013 06:20:02 PM EDT
Brother-MFC-4800 accepting requests since Wed 05 Jun 2013 01:35:48 PM EDT
Brother-MFC-J825DW accepting requests since Mon 17 Dec 2012 01:54:12 PM EST
mfc-8480dn accepting requests since Wed 19 Jun 2013 06:19:59 PM EDT
s820 accepting requests since Wed 19 Jun 2013 06:20:01 PM EDT
s820-scully accepting requests since Wed 19 Jun 2013 06:20:02 PM EDT
Stylus-NX300 accepting requests since Fri 08 Mar 2013 03:13:58 PM EST

To print to one of these printers I generally use the lp command like so:
$ lp -d mfc-8480dn sample.txt
request id is mfc-8480dn-454 (1 file(s))

To see what's in your print queue:
$ lpq -a
Rank    Owner   Job     File(s)                         Total Size
1st     saml    453     (stdin)                         0 bytes
active  saml    454     sample.txt                   1024 bytes

To remove a job from the print queue:
$ lprm 453

The print queue is now empty:
$ lpq -a
no entries


text:
Q: Can `std::basic_string::operator[]` return a "distant" protected page nul terminator? So, operator[] does not directly say that s[s.size()] must be the character after s[s.size()-1] in memory.  It seems worded to avoid making that claim.
But s.data() states that s.data()+k == &s[k], and s.data() must return a pointer.
Ignoring the seeming standard defect of using & on CharT above and not std::addressof, is the implementation free to return a different CharT (say, one on a protected page, or in ROM) for s[s.size()] prior to the first call to s.data()?  (Clearly it could arrange the buffer to end on a read-only page with a zero on it; I'm talking about a different situation)
To be explicit:
As far as I can tell, if s.data() is never called (and the compiler can prove it), then s[s.size()] need not be contiguous with the rest of the buffer.
Can std::addressof(s[s.size()]) change after a call to s.data() and the implementation be standards-compliant (so long as s.data()+k == &s[k] has .data() evaluated before [], but the compiler is free to enforce that).  Or are there immutability requirements I cannot see?

A: Since C++11, std::string is required to be stored in contiguous memory. This is the quote from the C++11 standard (section 24.4.1.4):

The char-like objects in a
  basic_string
  object shall be stored contiguously. That is, for any
  basic_string
  object
  s
  , the identity
  &*(s.begin() + n) == &*s.begin() + n
  shall hold for all values of
  n
  such that
  0
  <= n < s.size()
  .

This quote about the return value of operator[] states that it returns the same as &*(s.begin()+n) (section 21.4.5.1):

*(begin() + pos)
  if
  pos < size()
  . Otherwise, returns a reference to an object of type
  charT
  with value
  charT()
  , where modifying the object leads to undefined behavior

Then we have this quote on the return value of data() in (section 24.4.7.1):

A pointer
  p
  such that
  p + i == &operator[](i)
  for each
  i
  in
  [0,size()]
  .

So data returns the same as you would get using the &operator[]. And any value between you retrieve using the &operator should be stored contiguously. So you can conclude both return a pointer to contiguous memory. So it will not return a pointer to a distance page.
Note that this only applies to C++11. Such guarantees were not made by the standard before C++11.


text:
Q: How to send a response back to client using websockets in AWS Lambda I am using the Serverless Framework to deploy a WebSocket app to AWS Lambda.
I need to make it send a response back to the client when it hits a WebSocket route.
Here is my handler:
const AWS = require("aws-sdk");

module.exports.websocketHandler = async (event, _) => {
  const {
    requestContext: { routeKey }
  } = event;

  switch (routeKey) {
    case "$connect":
      // ....
      break;

    case "$disconnect":
      // ....
      break;

    case "getBot":
      const body = JSON.parse(event.body);
      const postData = body.data;
      const params = {
        ConnectionId: event.requestContext.connectionId,
        Data: JSON.stringify(postData)
      };

      postMessage(params, event);
      break;

    case "$default":
    default:
      return { statusCode: 200 };
  }

  return { statusCode: 200 };
};

const postMessage = async (data, event) => {
  try {
    const apigwManagementApi = new AWS.ApiGatewayManagementApi({
      apiVersion: "2018-11-29",
      `https://${event.requestContext.domainName}/${event.requestContext.stage}`
    });

    await apigwManagementApi.postToConnection(data).promise();
  } catch (err) {
    console.log(err);
  }
};

It just responds back with whatever was sent. I am using wscat tool to connect to the WebSocket.
wscat -c wss://{API-ID}.execute-api.{REGION}.amazonaws.com/dev
{"action": "getBot", "data": "Hello world"}

I have tried testing it offline, and it works just fine. And when deployed, I can connect to it, but whenever I try to send the action to getBot, I get no response.

A: The problem was with my lambda, It was in a custom VPC which resulted in lambda not getting internet access.
I fixed this by adding additional subnets with a NAT Gateway in AWS.

A: For others coming to this question, you need to do a few things:

*

*Create a WebSocket API with the API Gateway.

*Create route keys for each WS event you need to handle.

*Simultaneously while creating route keys (or before), create Lambda functions for each WS event. Connect your given Lambda function to the WS API route. (Be sure to deploy your Lambda functions)

*Ensure your permissions are setup correctly for each Lambda function (make sure the API Gateway can access them).

*Deploy your WS API from the API Gateway. Use the wss://[...] URL to connect via a client.

Helpful docs: https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-api-develop.html
Enjoy!


text:
Q: How make insert if select rows == '0' in one query? In mysql, I have the following:
Structure Table:
id(int primary key)
name(varchar 100 unique)

Values:
id  name

1   test
2   test1

I have two queries:
1) SELECT count(*) FROM Table WHERE name='test'
2) if count select rows == 0 second query INSERT INTO Table (name) VALUES ('test')
I know that may be use:
$res = mysql(SELECT count(*) as count FROM Table WHERE name='test');
// where mysql function make query in db

$i = $res -> fetch_assoc();

if($i['count'] < 1 ){$res = mysql(INSERT INTO Table (name) VALUES ('test');}

But I would like know how to make two query in one query.
How do I make one query inside of two?

A: You can do it with a simple trick, like this:
insert into Table1(name)
select 'test' from dual
where not exists(select 1 from Table1 where name='test');

This will even work if you do not have a primary key on this column.
Explanation: DUAL is a special dummy table that is only referenced here to enable the WHERE clause. You would not be able to have a statement without a FROM clause (like select 'test' where not exists(select 1 from Table1 where name='test')) as it will be incomplete.

A: Assuming your name column has a UNIQUE constraint, just add IGNORE to the INSERT statement.
INSERT IGNORE INTO Table (name) VALUES ('test')

This will skip the insertion if a record already exists for a particular value and return 0 affected rows. Note that a primary key is also considered a UNIQUE constraint.
If the name column doesn't have such a constraint, I would advice that you add one:
ALTER TABLE `Table` ADD UNIQUE(name)

See also the documentation for INSERT

A: If you don't need to check whether there is duplication, other's suggestion is good for  you. But you need, use 'INSERT' and check error number like this:
mysql_query('INSERT INTO ...');

if (mysql_errno() == 1062)
{
    echo "duplicated";
}
else
{
    echo "inserted";
}

(I know mysql_XXXX() is deprecated.. just example)


text:
Q: Why border radius 50% image looks blurry using CSS? Something weird is happening with an image that i have working in my HTML site.
I'm using Bootstrap Vue 4 (with Laravel 8). I'm working with a 250x250 pixeles image

and i'm trying to convert it into an rounded avatar of 50x50 pixels of dimension. I was trying to use avatar and rounded-circle classes but i'm getting the same blurry weird result, regarding i'm using native CSS or bootstrap helper classes.

HTML Code:
user()->avatar) }}" id="my-avatar"
                                         alt="">

CSS Code:
#my-avatar {
    object-fit: cover;
    border-radius:50%;
    width: 50px;
    height: 50px;
}

EDIT: I've reproduced a DEMO with the current issue to expose my problem (please watch it as full screen because is part of a navbar):

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

    <title>Hello, world!</title>

                 Fernando Torres

      </navbar>

A: The problem already occurs when having just the image and resizing it.

#my-avatar {
  width: 50px;
  height: 50px;
}

The problem is that the original image is significantly larger than how it is displayed. Resizing however is expensive so browsers could do some approximations, which can have blurry results.
You can force better processing of the image using image-rendering

#my-avatar {
  width: 50px;
  height: 50px;
  image-rendering: -moz-crisp-edges;
  image-rendering:   -o-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor
}

You however should consider using an image with a dimension that matches the display size better.


text:
Q: Problem changing the TextMeshPro UI text within a canvas using a script I'm having a problem changing the scoring values using TextMeshPro in a canvas from a script within the canvas. I'm getting a NullPointerException error because i feel that i am not referencing the score text files correctly but im not sure how to do it correclty.
Error :

NullReferenceException: Object reference not set to an instance of an object
  Score.PlayerOneScored () (at Assets/Scripts/Score.cs:20)

Code :
public class Score : MonoBehaviour
{
static int scoreValue1 = 0;
static int scoreValue2 = 0;
private TMP_Text score1;
private TMP_Text score2;

public void PlayerOneScored() {
    Debug.Log("Player One Scored");
    scoreValue1++;

    TMP_Text score1 = GetComponent<TextMeshProUGUI>();
    Debug.Log("P1 Score: " + scoreValue1);
    score1.text = "Score: " + scoreValue1;
    }

public void PlayerTwoScored()
{
    Debug.Log("Player Two Scored");
    scoreValue2++;

    TMP_Text score2 = GetComponent<TMP_Text>();
    Debug.Log("P2 Score: " + scoreValue2);
    score2.text = "Score: " + scoreValue2;
    }
}

Line 20 is
score1.text = "Score: " + scoreValue1;

Picture of the Hierarchy :
ScoreCanvas
Update Have it working now! This was my class in the end
   using System.Collections;
   using System.Collections.Generic;
   using UnityEngine;
   using UnityEngine.UI;
   using TMPro;

   public class Score : MonoBehaviour
   {
   static int scoreValue1 = 0;
   static int scoreValue2 = 0;
   public TextMeshProUGUI score1;
   public TextMeshProUGUI score2;

void Awake()
{
    score1.text = "Score: " + scoreValue1;
    score2.text = "Score: " + scoreValue2;
}

public void PlayerOneScored() {

    if (scoreValue1 < 10) {
        scoreValue1++;
        Debug.Log("Player One Scored");
        Debug.Log("P1 Score: " + scoreValue1);

        score1.text = "Score: " + scoreValue1;
    }
    else { }
}

public void PlayerTwoScored()
{
    if (scoreValue2 < 10)
    {
        scoreValue2++;
        Debug.Log("Player Two Scored");
        Debug.Log("P2 Score: " + scoreValue2);

        score2.text = "Score: " + scoreValue2;
    }
    else { }
}
}

A: In the comment you said your script is attached to the Canvas GameObject.
But you are using
GetComponent<TextMeshProUGUI>();

Note that GetComponent

Returns the component of Type type if the game object has one attached, null if it doesn't.

It only returns Components attached to the very same GameObject. In your description this is not the case. The Components you are trying to get are on child GameObjects of your Canvas!

Now if there would be only one you could use another variant like GetComponentInChildren ... BUT: since in your case you have two different ones and want to be able to differ between them you can't use it .. it would always return the same reference.

There are multiple possible solutions but here is what I would do: Simply remove both GetComponent lines completely and rather set your references via the Unity Inspector! This can be done by either make a field public or use [SerializeField] on a private one:
// Now both these fields will appear in the Inspector
// so you can simply drag&drop the according GameObjects into the slots
[SerializeField] private TextMeshProUGUI score1;
public TextMeshProUGUI score2;

Another option would be to get the according child objects on runtime (this is more error prone ofcourse)
score1 = transform.GetChild(0).GetComponemt<TextMeshProUGUI>();

...

score2 = transform.GetChild(1). GetComponent<TextMeshProUGUI>();


text:
Q: sql more than one count I have a database with Names of workers, names of projects they are working on, names of tools they know how to use and name of languages they speak, among other data. I want to create an SQL query in R that gives me the name of each worker with a count of how many projects they are working on, how many tools they know how to use and how many langauge they speak. For example: Miller 5 3 2.
I have tried this code:  (it's not working)
sql= "SELECT Name.worker, count(Name).project, count(Name).tool, count(Name).language
      FROM worker GROUP BY worker"

any ideas? :)


text:
Q: How to convert XElement to XDocument How can I convert XElement into XDocument? Is there some built-in method for this?
The only way I can think of is without new XDocument(xelement.ToString()) which will result in creating big strings and then parsing them, thus reducing the performance.

A: Just pass the XElement to the constructor of XDocument:
var xdoc = new XDocument(new XElement("a", "b"));

A: I've had great success with this:
var xDoc = XDocument.Load(xml.CreateReader());


text:
Q: Merge two Graph entries into one - about one website I've had like buttons on my photography website http://www.tomaskouba.cz. The main page had 15 likes and some of the pictures had likes too. About a month ago, I played with Facebook Apps, made an FB application saying it's url is www.tomaskouba.cz, set up canvas and deactivated the canvas soon.
Problem:
Likes disappeared. I can see in Graph API, that my 15 likes are at URL
https://graph.facebook.com/http://www.tomaskouba.cz (btw I didn't look at my likes for 2 month so I'm not 100% sure if my app is the reason)
An when I check my FB app: https://graph.facebook.com/175067675881467 it gives some info but not domain (which I filled in the app settings) and not likes.
Question:

*

*What URL should I give in Like Button to have 15 likes back?

*Is it possilble to join these Graph entries to have my likes back under url www.tomaskouba.cz?

Thank you!


text:
Q: Using the Parse.com Javascript API with users authenticated via the PHP API If my site uses the Parse.com PHP API to authenticate users, can I use the Javascript API for ajax requests in such a way that the user, having been logged in via PHP, can access data via the Javascript API?
What would I need to set up differently?

Some background
I have a site that uses the Parse.com PHP API to handle all backend tasks like storing and retrieving data and authenticating users.
I have several pages that use ajax to refresh page content.
I have written my own Javascript class for sending JSON data to my server via ajax where the info is processed and my PHP code steps in to create, update, or delete Parse objects as needed.
This all works very well with the exception of dealing with files. I see several approaches to dealing with files but I feel like I'm re-inventing the wheel.
The Parse.com Javascript API is great, I'm pretty familiar with it and it already deals with files really well. It would be awesome If I could use it for the ajax.

I have tried...
Logging in with the PHP API and then attempting to use the Javascript SDK directly to get the current user like
    var currentUser = Parse.User.current();
    if (currentUser) {
        // do stuff with the user
        alert(currentUser);
    } else {
        // show the signup or login page
        alert('that didnt work');
    }

This did not work.

A: It turns out that you can do this by passing the Parse PHP session token to the Javascript API like this:
   <?php
        $sessionToken = ParseUser::getCurrentUser()->getSessionToken();
        echo 'var token="'.$sessionToken.'";';
    ?>

    Parse.User.become(token).then(function (user) {
        // The current user is now set to user.
        alert('User has access to javascript API');
    }, function (error) {
        // The token could not be validated.
        alert('Error: ' + error.code + ' ' + error.message);
    });


text:
Q: Angular 2 component using plain/vanilla JavaScript Due to some architectural decisions, my team has decided to fallback to using Javascript without any framework dependencies (Angular or react).
I would now want to write custom components(that do the exact same thing as Angular's components: a selector that can be used in HTML with a scope & a controller to play with) with no dependencies on frameworks.
jQuery widgets is an option we thought of. But there's a dependency on jQuery :(
What's the best approach to proceed?
Does ES6 provide any ways to do this?

A: Angular is parsing the html and searching to match with the selectors.. before this, it parses your templates to generate dynamic code... and a lot more things under the hood.. so, no, you wont be able to create a custom html tag easily.
Maybe take a look at Polymer?
https://www.polymer-project.org/

A: Why bother creating something what is sucessfully done by a huge team of developers on your own? You will most likely fail.
But if you still want to try it, there's a thing called WebComponents, but it has very limited browser support at the moment. A better support would also lead to another library called Polymer.
Another lightweight library to create custom components is Vue.js.
Fyi: React isn't a framework.


text:
Q: Dynamic Run-Time object creation: Keep intellisense? Recently I have been exploring using the fancy new dynamic keyword introduced in C# 4.0 (DynamicObject, ExpandoObject etc..)
Now I can identify several uses (and several pitfalls) for the new introduction, but for the purpose of my project, and for this question - I am looking into cleaning up my late-bound string-based indexed collections to make them more safe.
So, before dynamics I had:
Car car1 = CARWarehouse1["Honda"];

And WITH dynamics I can now do (where CARWarehouse1 now extends the DynamicObjects base)
Car car1 = CARWarehouse1.Honda

This is all well and good, and from a quick glance it looks like I have achieved what I wanted.. but have I?
Because lets face it, for either method at compile time should I have mistyped my referenced car type, the compiler won't have a problem, but I will run into issues at runtime.
Therefore, what I really need is compile time property checking, and Intellisense support. So - can I do it?
I know that there are libraries out there such as Moq that have this capability, and Resharper gives some sort of support within intellisense, but I'm looking for a more rounded solution.
Any ideas, big, small, easy or complex are welcome.

A: Nope, no such thing for dynamic types.
Basically the compiler just skips all checks on variables marked as dynamic because there is no way to check anything. Properties on dynamic objects may be created at runtime, so the code can't be checked at compile time for accuracy.

A: If compile time checks and intellisense are important, don't use dynamic.  If the scope of the object is pretty small you could use anonymous types instead, but I don't get the impression that's applicable to your situation.  I'd suggest you just define the types you need, and stick with dictionaries and hashtables for any properties that you can't predict when coding.


text:
Q: ERROR 1005 (HY000): Can't create table? I have read through this about a billion times and I cannot figure it out... I generated this in workbench so it should work but it creates all of the tables except for SECTIONS... it will create it if i remove the relationship between SECTION and INSTRUCTOR but I need that relationship to work.... Any help would be greatly appreciated! code is below... Hopefully someone can help me! Thanks!
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

CREATE SCHEMA IF NOT EXISTS `385_s11_turpinvp` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `385_s11_turpinvp` ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`TUTORS`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`TUTORS` (
  `Name` VARCHAR(45) NOT NULL ,
  `Banner_Id` CHAR(8) NOT NULL ,
  `Email` VARCHAR(45) NOT NULL ,
  `Ssn` CHAR(9) NOT NULL ,
  `Address` VARCHAR(45) NOT NULL ,
  `Phone` INT NOT NULL ,
  PRIMARY KEY (`Banner_Id`) )
ENGINE = InnoDB;

CREATE UNIQUE INDEX `Ssn_UNIQUE` ON `385_s11_turpinvp`.`TUTORS` (`Ssn` ASC) ;

CREATE UNIQUE INDEX `Banner_Id_UNIQUE` ON `385_s11_turpinvp`.`TUTORS` (`Banner_Id` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`STUDENTS`
-    - -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`STUDENTS` (
  `Name` VARCHAR(45) NOT NULL ,
  `Banner_Id` CHAR(8) NOT NULL ,
  `Email` VARCHAR(45) NOT NULL ,
  `Phone` INT NOT NULL ,
  PRIMARY KEY (`Banner_Id`) )
ENGINE = InnoDB;

CREATE UNIQUE INDEX `Banner_Id_UNIQUE` ON `385_s11_turpinvp`.`STUDENTS` (`Banner_Id` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`INSTRUCTORS`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`INSTRUCTORS` (
  `Name` VARCHAR(45) NOT NULL ,
  `Banner_Id` CHAR(8) NOT NULL ,
  `Email` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`Banner_Id`, `Name`) )
ENGINE = InnoDB;

CREATE UNIQUE INDEX `Banner_Id_UNIQUE` ON `385_s11_turpinvp`.`INSTRUCTORS` (`Banner_Id` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`COURSES`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`COURSES` (
  `Course_Id` VARCHAR(45) NOT NULL ,
  `Course_Name` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`Course_Id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`APPOINTMENTS`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`APPOINTMENTS` (
  `Courses_Course_Id` VARCHAR(45) NOT NULL ,
  `TUTORS_Banner_Id` CHAR(8) NOT NULL ,
  `STUDENTS_Banner_Id` CHAR(8) NOT NULL ,
      `Start_Time` DATETIME NOT NULL ,
  `End_Time` DATETIME NOT NULL ,
  PRIMARY KEY (`Courses_Course_Id`, `TUTORS_Banner_Id`, `STUDENTS_Banner_Id`, `Start_Time`, `End_Time`) ,
  CONSTRAINT `fk_COURSES_has_TUTORS_Courses1`
    FOREIGN KEY (`Courses_Course_Id` )
    REFERENCES `385_s11_turpinvp`.`COURSES` (`Course_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_COURSES_has_TUTORS_TUTORS1`
    FOREIGN KEY (`TUTORS_Banner_Id` )
    REFERENCES `385_s11_turpinvp`.`TUTORS` (`Banner_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_APPOINTMENTS_STUDENTS1`
    FOREIGN KEY (`STUDENTS_Banner_Id` )
    REFERENCES `385_s11_turpinvp`.`STUDENTS` (`Banner_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

CREATE INDEX `fk_COURSES_has_TUTORS_TUTORS1` ON `385_s11_turpinvp`.`APPOINTMENTS` (`TUTORS_Banner_Id` ASC) ;

CREATE INDEX `fk_COURSES_has_TUTORS_Courses1` ON `385_s11_turpinvp`.`APPOINTMENTS` (`Courses_Course_Id` ASC) ;

CREATE INDEX `fk_APPOINTMENTS_STUDENTS1` ON `385_s11_turpinvp`.`APPOINTMENTS` (`STUDENTS_Banner_Id` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`QUALIFIED`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`QUALIFIED` (
  `Courses_Course_Id` VARCHAR(45) NOT NULL ,
  `TUTORS_Banner_Id` CHAR(8) NOT NULL ,
  PRIMARY KEY (`Courses_Course_Id`, `TUTORS_Banner_Id`) ,
  CONSTRAINT `fk_Courses_has_TUTORS_Courses2`
    FOREIGN KEY (`Courses_Course_Id` )
    REFERENCES `385_s11_turpinvp`.`COURSES` (`Course_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_Courses_has_TUTORS_TUTORS2`
    FOREIGN KEY (`TUTORS_Banner_Id` )
    REFERENCES `385_s11_turpinvp`.`TUTORS` (`Banner_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

CREATE INDEX `fk_Courses_has_TUTORS_TUTORS2` ON `385_s11_turpinvp`.`QUALIFIED` (`TUTORS_Banner_Id` ASC) ;

CREATE INDEX `fk_Courses_has_TUTORS_Courses2` ON `385_s11_turpinvp`.`QUALIFIED` (`Courses_Course_Id` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`Availability`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`Availability` (
  `Start_Time` DATETIME NOT NULL ,
  `End_time` DATETIME NOT NULL ,
  `TUTORS_Banner_Id` CHAR(8) NOT NULL ,
  PRIMARY KEY (`TUTORS_Banner_Id`, `End_time`, `Start_Time`) ,
  CONSTRAINT `fk_Availability_TUTORS1`
    FOREIGN KEY (`TUTORS_Banner_Id` )
    REFERENCES `385_s11_turpinvp`.`TUTORS` (`Banner_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`SECTIONS`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`SECTIONS` (
  `COURSES_Course_Id` VARCHAR(45) NOT NULL ,
  `INSTRUCTORS_Name` VARCHAR(45) NOT NULL ,
  `Section_Id` CHAR(1) NOT NULL ,
  PRIMARY KEY (`COURSES_Course_Id`, `INSTRUCTORS_Name`, `Section_Id`) ,
  CONSTRAINT `fk_COURSES_has_ENROLLED_COURSES1`
    FOREIGN KEY (`COURSES_Course_Id` )
    REFERENCES `385_s11_turpinvp`.`COURSES` (`Course_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_SECTIONS_INSTRUCTORS1`
    FOREIGN KEY (`INSTRUCTORS_Name` )
    REFERENCES `385_s11_turpinvp`.`INSTRUCTORS` (`Name` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

CREATE INDEX `fk_COURSES_has_ENROLLED_COURSES1` ON `385_s11_turpinvp`.`SECTIONS` (`COURSES_Course_Id` ASC) ;

CREATE INDEX `fk_SECTIONS_INSTRUCTORS1` ON `385_s11_turpinvp`.`SECTIONS` (`INSTRUCTORS_Name` ASC) ;

-- -----------------------------------------------------
-- Table `385_s11_turpinvp`.`ENROLLED`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `385_s11_turpinvp`.`ENROLLED` (
  `STUDENTS_Banner_Id` CHAR(8) NOT NULL ,
  `COURSES_Course_Id` VARCHAR(45) NOT NULL ,
  `SECTIONS_Section_Id` CHAR(1) NOT NULL ,
  PRIMARY KEY (`STUDENTS_Banner_Id`, `COURSES_Course_Id`, `SECTIONS_Section_Id`) ,
  CONSTRAINT `fk_COURSES_has_STUDENTS_STUDENTS1`
    FOREIGN KEY (`STUDENTS_Banner_Id` )
    REFERENCES `385_s11_turpinvp`.`STUDENTS` (`Banner_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_ENROLLED_COURSES1`
    FOREIGN KEY (`COURSES_Course_Id` )
    REFERENCES `385_s11_turpinvp`.`COURSES` (`Course_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_ENROLLED_SECTIONS1`
    FOREIGN KEY (`SECTIONS_Section_Id` )
    REFERENCES `385_s11_turpinvp`.`SECTIONS` (`Section_Id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

CREATE INDEX `fk_COURSES_has_STUDENTS_STUDENTS1` ON `385_s11_turpinvp`.`ENROLLED` (`STUDENTS_Banner_Id` ASC) ;

CREATE INDEX `fk_ENROLLED_COURSES1` ON `385_s11_turpinvp`.`ENROLLED` (`COURSES_Course_Id` ASC) ;

C    REATE INDEX `fk_ENROLLED_SECTIONS1` ON `385_s11_turpinvp`.`ENROLLED` (`SECTIONS_Section_Id` ASC) ;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

A: To get details on your foreign key error, run SHOW ENGINE INNODB STATUS\G and look at the "LATEST FOREIGN KEY ERROR" section.
It should tell you that the foreign key is invalid because there is no unique index or primary key index on INSTRUCTORS.Name. The primary key is INSTRUCTORS.(Banner_Id, Name) and you have a unique index on INSTRUCTORS.Banner_Id. You either need to use one of those column combinations for the foreign key, or add a unique key on INSTRUCTORS.Name