text:
Q: How to get the button's border size in Android How can I get the border width of a stand Android button programmatically? I simply need to resize the text to fit to the gray area and need to position other objects inline with the buttons, but I cannot do that without knowing the size of the border. I need this to work in all API's 7+. The red arrows in the image below show what I am trying to get:

Here is the code I use for creating my button:
cmdView = new Button(this);
params = new RelativeLayout.LayoutParams(widthLblViewVerbs , (int) fieldHeight);
params.leftMargin = (int) (screenWidth - params.width);
params.topMargin = (int) yPos;
cmdView.setSingleLine();
cmdView.setText("View");
cmdView.setPadding(0, 0, 0, 0);
cmdView.setTextSize(TypedValue.COMPLEX_UNIT_PX, SetTextSize(cmdView.getText().toString(), params.width, params.height));
layout.addView(cmdView, params);

NB. I've had to ask this question again because someone downvoted my question last time and I am desperate for a solution. I have made absolutely no progress with my program in weeks because I have been stuck with this and another problem. If there is something unclear about my question, please let me know and I will edit it. Thank you

A: Not really clear on the question - you want the margins of the underlying view and then the set the size of the button to match ? Then Have you tried
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

margins are accessible via
lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;

Details here:http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

A: This gets the width and height of the button's border:
final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
    @Override
    public void run()
    {
        button.buildDrawingCache();
        Bitmap viewCopy = button.getDrawingCache();

        boolean stillBorder = true;
        PaddingLeft = 0;
        PaddingTop = 0;
        while (stillBorder)
        {
            int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
            if (color != Color.TRANSPARENT)
                stillBorder = false;
            else
                PaddingLeft++;
        }
        stillBorder = true;
        while (stillBorder)
        {
            int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
            if (color != Color.TRANSPARENT)
                stillBorder = false;
            else
                PaddingTop++;
        }
    }
});

A: My initial code recommendation from the comments can be found here. The implementation done by Dan Bray is:
final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
@Override
public void run()
{
    button.buildDrawingCache();
    Bitmap viewCopy = button.getDrawingCache();

    boolean stillBorder = true;
    PaddingLeft = 0;
    PaddingTop = 0;
    while (stillBorder)
    {
        int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
        if (color != Color.TRANSPARENT)
            stillBorder = false;
        else
            PaddingLeft++;
    }
    stillBorder = true;
    while (stillBorder)
    {
        int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
        if (color != Color.TRANSPARENT)
            stillBorder = false;
        else
            PaddingTop++;
    }
}
});

A: Assuming you are using a nine patch background image, there is a much easier way.
In the nine patch image, you can define a padding box. This padding box will automatically be applied to the contents you set. No need to recalculate the paddings manually in that case.
Note that you should not set a padding on views using a nine patch as a background as the padding from the nine patch will be ignored.


text:
Q: Multiplying and Adding Values across Rows I have this data frame:
color <- c("AKZ", "ZZA", "KAK")
color_1 <- sample(color, 100, replace=TRUE, prob=c(0.4, 0.3, 0.3))
id = 1:100

sample_data = data.frame(id, color_1)

 id color_1
1  1     KAK
2  2     AKZ
3  3     KAK
4  4     KAK
5  5     AKZ
6  6     ZZA

Suppose there is a legend:

*

*K = 3

*A = 4

*Z = 6

I want to add two columns to the above data frame:

*

*sample_data$add_score : e.g. KAK = K + A + K = 3 + 4 + 3 = 10

*sample_data$multiply_score : e.g. KAK = K * A * K = 3 * 4 * 3 = 36

I thought of solving the problem like this:
sample_data$first = substr(color_1,1,1)
sample_data$second = substr(color_1,2,2)
sample_data$third = substr(color_1,3,3)

sample_data$first_score = ifelse(sample_data$first == "K", 3, ifelse(sample_data$first == "A", 4, 6))

sample_data$second_score = ifelse(sample_data$second == "K", 3, ifelse(sample_data$second == "A", 4, 6))

sample_data$third_score = ifelse(sample_data$third == "K", 3, ifelse(sample_data$third == "A", 4, 6))

sample_data$add_score = sample_data$first_score + sample_data$second_score + sample_data$third_score

sample_data$multiply_score = sample_data$first_score * sample_data$second_score * sample_data$third_score

But I think this way would take a long time if the length of "color_1" was longer. Given a scoring legend, is there a faster way to do this?
Thank you!

A: Here is a way.
The main trick is to strsplit into single characters and match these vectors with the legend. Then add or multiply the matching numbers.
set.seed(2022)
color <- c("AKZ", "ZZA", "KAK")
color_1 <- sample(color, 100, replace=TRUE, prob=c(0.4, 0.3, 0.3))
id <- 1:100

sample_data = data.frame(id, color_1)

legend <- setNames(c(3, 4, 6), c("K", "A", "Z"))

add_mul <- function(x, l){
  add <- function(y, l){
    i <- match(y, names(l))
    sum(l[i])
  }
  mul <- function(y, l){
    i <- match(y, names(l))
    prod(l[i])
  }

  s <- strsplit(x, "")
  add_score <- sapply(s, add, l = l)
  mul_score <- sapply(s, mul, l = l)
  data.frame(add_score, mul_score)
}

sample_data <- cbind(sample_data, add_mul(sample_data$color_1, legend))
head(sample_data)
#>   id color_1 add_score mul_score
#> 1  1     ZZA        16       144
#> 2  2     KAK        10        36
#> 3  3     AKZ        13        72
#> 4  4     KAK        10        36
#> 5  5     AKZ        13        72
#> 6  6     KAK        10        36

Created on 2022-03-10 by the reprex package (v2.0.1)

A: We can use stri_replace_all_regex to replace your color_1 into integers together with the arithmetic operator.
Here I've stored your values into a vector color_1_convert. We can use this as the input in stri_replace_all_regex for better management of the values.
library(dplyr)
library(stringi)

color_1_convert <- c("K" = "3", "A" = "4", "Z" = "6")

sample_data %>%
  group_by(id) %>%
  mutate(add_score = eval(parse(text = gsub("\\+$", "", stri_replace_all_regex(color_1, names(color_1_convert), paste0(color_1_convert, "+"), vectorize_all = F)))),
         multiply_score = eval(parse(text = gsub("\\*$", "", stri_replace_all_regex(color_1, names(color_1_convert), paste0(color_1_convert, "*"), vectorize_all = F)))))

# A tibble: 100 × 4
# Groups:   id [100]
      id color_1 add_score multiply_score
   <int> <chr>       <dbl>          <dbl>
 1     1 KAK            10             36
 2     2 ZZA            16            144
 3     3 AKZ            13             72
 4     4 ZZA            16            144
 5     5 AKZ            13             72
 6     6 AKZ            13             72
 7     7 AKZ            13             72
 8     8 KAK            10             36
 9     9 ZZA            16            144
10    10 AKZ            13             72
# … with 90 more rows

A: Here is another option using tidyverse. I use recode from dplyr to change the letters to numbers according to the legend.
library(tidyverse)

legend <- c(K = 3, A = 4, Z = 6)

sample_data %>%
  rowwise %>%
  mutate(code = list(recode(str_split(color_1, "", simplify = T), !!!legend)),
         add_score = sum(code),
         multiply_score = prod(code)) %>%
  select(-code)

Output
      id color_1 add_score multiply_score
   <int> <chr>       <dbl>          <dbl>
 1     1 AKZ            13             72
 2     2 AKZ            13             72
 3     3 KAK            10             36
 4     4 KAK            10             36
 5     5 AKZ            13             72
 6     6 AKZ            13             72
 7     7 KAK            10             36
 8     8 AKZ            13             72
 9     9 AKZ            13             72
10    10 AKZ            13             72
# … with 90 more rows

Data
set.seed(103)
color <- c("AKZ", "ZZA", "KAK")
color_1 <- sample(color, 100, replace=TRUE, prob=c(0.4, 0.3, 0.3))
id = 1:100

sample_data = data.frame(id, color_1)

Benchmark
It looks like Rui Barradas' solution is the fastest of the answers so far.

A: Here's an approach based on tidyr::separate_rows() followed by a grouped dplyr::summarize():
library(tidyverse)
set.seed(1)

legend <- c(K = 3, A = 4, Z = 6)

sample_data %>%
  mutate(decoded = color_1) %>%
  separate_rows(decoded, sep = "(?!^)") %>%
  mutate(decoded = legend[decoded]) %>%
  group_by(id, color_1) %>%
  summarize(
    add_score = sum(decoded),
    multiply_score = prod(decoded),
    .groups = "drop"
  )

Output:
# A tibble: 100 x 4
      id color_1 add_score multiply_score
   <int> <chr>       <dbl>          <dbl>
 1     1 AKZ            13             72
 2     2 AKZ            13             72
 3     3 KAK            10             36
 4     4 ZZA            16            144
 5     5 AKZ            13             72
 6     6 ZZA            16            144
 7     7 ZZA            16            144
 8     8 KAK            10             36
 9     9 KAK            10             36
10    10 AKZ            13             72
# ... with 90 more rows

A: Yet another alternative, using some libraries optimized for speed, stringi for string manipulation and Rfast for matrix operations. Note that when any NA values are present in your data matrixStats is safer to use than Rfast.
set.seed(2022)
color <- c("AKZ", "ZZA", "KAK")
color_1 <- sample(color, 100, replace=TRUE, prob=c(0.4, 0.3, 0.3))
id = 1:100
sample_data = data.frame(id, color_1)

m <- strsplit(sample_data[["color_1"]], "") |>
  unlist(use.names = F) |>
  stringi::stri_replace_all_regex(
    c("K", "A", "Z"),
    c("3", "4", "6"), vectorize_all = F) |>
  as.integer() |>
  matrix(ncol = 3, byrow = T)
sample_data$add_score <- Rfast::rowsums(m)
sample_data$mul_score <- Rfast::rowprods(m)

head(sample_data)
  id color_1 add_score mul_score
1  1     ZZA        16       144
2  2     KAK        10        36
3  3     AKZ        13        72
4  4     KAK        10        36
5  5     AKZ        13        72
6  6     KAK        10        36

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't pass prop to component in svelte with typescript I have this BigButton component with a title prop

{title}

then on my index.svelte , I tried to pass the prop in different ways none of them work:
<BigButton title={'Join a Game'} />
<BigButton title='Join a Game' />
the lint is giving me the following error:
Type '{ title: string; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'title' does not exist on type 'IntrinsicAttributes'.

A: Use should export it, like:
export let title: string;

Svelte uses the export keyword to mark a variable declaration as a
property or prop, which means it becomes accessible to consumers of
the component


text:
Q: How to parse jsonp returned from api using python I'm very new to coding, and I'm building my first web application using open REST api with python flask.
I think the api is returning jsonp which looks like this - callbackfunction{ json }; and I get from other posts that all I need to do is getting rid of this padding. However, I can't figure out at which point I should implement the stripping.
This is my code. 5th line is throwing an error "the JSON object must be str, bytes or bytearray, not HTTPResponse"
def lookup(title):
    try:
        url = "http://www.aladin.co.kr/ttb/api/ItemSearch.aspx?ttbkey=foo&Query=bar"
        result = urllib.request.urlopen(url)
        data = json.loads(result)
        data_json = data.split("{", 1)[1].strip("}")
        return data_json

    except requests.RequestException:
        return None

I'm sure it's working well until 4th line. When I tried the code below, at least it returned result, though cryptic, like this.

b'{ "version" : "20070901", "title" :
  "\xec\x95\x8c\xeb\x9d\xbc\xeb\x94\x98 \xea\xb2\x80 ...
  "customerReviewRank":9  } ] };'

Judging by the keys, I'm pretty sure this is the information I requested. So what can I do to fix this? Thanks in advance!
def lookup(title):
    try:
        url = "http://www.aladin.co.kr/ttb/api/ItemSearch.aspx?ttbkey=foo&Query=bar"
        result = urllib.request.urlopen(url)
        res = result.readline()
        return res


text:
Q: ¿Cómo validar el tipo de entrada en C? Tengo un programa que pide datos datos al usuario, pero si agregas " | #$&#$&& !!"#!23 " etc.. con símbolos raros, el programa no valida que pases un int o un float.
¿Alguien sabe por qué pasa eso? Y ¿cómo podría agregar algún tipo de condicional que permita verificar si los datos introducidos son correctos?
Mi código actual:
#include<stdio.h>//libreria

int main(){

    int a;
    float b;
    char c;

    printf("digite el valor de la variable A : ");
    scanf("%i",&a);
    printf(" el valor de la variable B : ");
    scanf("%f",&b);
    printf("el valor es : %i",a);
    printf("el valor es : %f",b);

    return 0;
}

A: Hola aquí te dejo un pequeño código para un ejemplo con un valor entero. El código verifica que el número de parámetros correctos introducidos por consola es 1 ya que scanf devuelve el número de parámetros correctos introducidos. En ese caso imprime valid integer En caso contrario imprime failure.
int num;
if(scanf("%i", &num) != 1)
    printf("failure\n");
else
    printf("valid integer");

Una adaptación de tu código podría ser:
#include<stdio.h>//libreria

int main(){

    int a;
    float b;
    char c;

    // variable A
    printf("digite el valor de la variable A : ");
    if(scanf("%i", &a) != 1)
        printf("Entero no válido\n");
    else
        printf(" el valor es: %i\n",a);

    // variable B
    printf("digite el valor de la variable B : ");
    while((c = getchar()) != '\n' && c != EOF);
    if(scanf("%f", &b) != 1)
        printf("Valor con coma flotante no válido\n");
    else
        printf(" el valor de la variable B es: %f\n",b);

    // variable C
    printf("digite el valor de la variable C : ");

    while((c = getchar()) != '\n' && c != EOF);
    if(scanf("%c", &c) != 1)
        printf("Valor caracter no válido\n");
    else
        printf(" el valor de la variable C es: %c\n",c);

    return 0;
}

Por último, he añadido un fragmento de código que borra del escaner los enter introducidos en el scaner para poder verificar la entrada de los siguientes registros sin que la aplicación salte al siguiente elemento.
while((c = getchar()) != '\n' && c != EOF);

Puedes ejecutar el código aquí: https://onlinegdb.com/ryfe798Gb


text:
Q: JavaScript Returning Previous Value Immediately after Changing the Value I have a single html document that simulates many pages by modifying the content and url as users click through the page.
In my JavaScript there is a place I use history.back(). This works as expected changing the url and content (even though the user really stays on the same html document). However, immediately after I use history.back() I try to get the users new window.location. This is still showing the previous url instead of the new one.
Do I need to force some type of update, refresh, calculation, garbage collection or something in-between those two lines of code so I get the new url?

A: Try waiting for the next tick before checking the new window.location:
history.back()
setTimeout(() => {
  console.log(window.location)
})

A: Listen for the popstate event. Browsers handle timing history.back() slightly different from each other.
window.onpopstate = logHistory;

function logHistory(e) {
  console.log(this.location);
}


text:
Q: What are the event parameters in google analytics for? I work with statistics of the application in google analytics. I have question about events parameters:

Part of them was created automatically, other parameters are custom. I found that they can't be used in reports. Is there other meaning of these parameters except displaying information about events of 30 last minutes?

A: Yes, there is another meaning. Say, for instance, you want to track how many menu clicks happen on a particular nav bar by item. Well, you create an event in GTM to send that data to GA4 shown below:

Please note that the two parameters with this event will be stored for analysis in GA4 ONLY when you add them as custom dimensions. It's a pain we didn't have in universal Google Analytics but we now have to deal with this. I hope it helps answer your question.


text:
Q: Proving that as N increases, it is more likely that x - y > z, with x \in X, y \in Y, z \in Z In trying to solve a bigger applied problem, I found myself facing the following.
Let $X$, $Y$ and $Z$ be three independent random variables, each coming from an unknown distribution, and each with $1...n$ realizations $x \in X, y \in Y, z \in Z$ . I know that:

*

*they all have the same number $n$ of sampled realizations.

*they all have the same support, i.e. $x,y,z \in [a,b]$, where $a,b \in \mathbb{R^{\geq0}}$ and $b>a$.

So, let's say we draw $n$ samples from each variable, so we get $n$ realizations from each of the three variables (where each draw is indexed by $i$ such that $i \in 1...n$). How can I show that as $n$ increases, it becomes more likely that $x_i + y_i > z_i$ for at least one draw $i$? If extra assumptions are needed, which would be the minimal assumptions required?

A: Given a sequence of independent events $A_i$ each of them has probability $p > 0$, the probability of having at least one event $A_i$ happening for $i \le n$, is $1-(1-p)^n$ which is always increasing and converges to $1$. So you only have to prove that $P(X+Y > Z) > 0$.
Your assumptions about $X, Y$ and $Z$ are a bit unclear, but if there is a couple of values $x, y$ for which:
$$P(X > x) > 0,\\ P(Y>y) > 0,\\P(Z < x+y) > 0$$
then, there is a probability greater than 0 that $X+Y >Z$, and what you want to prove is proven already.


text:
Q: Populating my jquery autocomplete with contents of an ajax call to cakephp I have an input field that I'm turning into a jqueryUI autocomplete:
$( "#autocomplete" ).autocomplete({
    autoFocus: true,
    source: mylist
 });

The mylist variable is just a string in the array format ['Value1','Value2,'Blah'] which i originally just hardcoded into the script.
Now I want the mylist variable to be the result of an ajax call to a function in my cakephp app. The function is basically as follows, it just grabs all the data as a list, and json encodes it.
public function source() {
    $this->layout = 'ajax';
    $countries=$this->Country->find('list',array('fields'=>'Country.country'));
    ChromePhp::log($countries);
    echo json_encode($countries);
}

This outputs:
{"1":"Afghanistan","2":"Albania ","3":"Algeria ","5..

My issue is getting the output of this function, (which ends up in the ajax success callback as 'data') into the correct format to place into the options array of the autocomplete.
I can get as far as console logging each value, but I'm stumped. Basically clutching at straws at the correct syntax.
$.ajax({
    type: "GET",
    dataType: "json",
    url: "/source/",
    success: function(data){
        /*
        magic array string creation code would go here instead of my code below...
        */
        $.each(data, function(i, item) {
            console.log(item);
        });
        console.log('data',data);

    }
})

A: The autocomplete plugin can do a lot of the work for you if you give it things in the right format.
I would start by re-indexing the $countries variable to start from 0. You can use the array_values() function for that:
echo json_encode(array_values($countries));

This should give you the JSON in the format of:
['Afghanistan','Albania','Algeria',...]

Then you can change the source property in the autocomplete code to be a url for your source action.
$( "#autocomplete" ).autocomplete({
    autoFocus: true,
    source: "/your_controller/source"
});

The autocomplete plugin won't filter the results for you, instead a query string is added to the url with a term field (e.g. /your_controller/source?term=foo) so you need to modify your find() method to use this.
$countries = $this->Country->find('list', array(
    'fields' => 'Country.country',
    'conditions' => array(
        'Country.country LIKE' => $this->request->query['term'] . '%'
    )
));

You can read more about the different types the source option can accept in the autocomplete on the API Documentation.


text:
Q: Does ExoPlayer or AVFoundation work with an udpxy stream? I'm building a frontend for a proprietary IPTV backend, which receives its channel streams via multicast, then for the end users it uses udpxy to convert the traffic from multicast to HTTP. However, neither ExoPlayer or AVFoundation seem to accept this stream (both the VLC app & flutter_vlc_player play this stream nicely) - I'm using the video_player plugin for Flutter, so I may miss over some live stream specific impls. Can anyone point me in the right direction? Thanks!
Media information (VLC):

udpxy: udpxy 1.0-23.12 (prod) standard [Linux 5.10.0-10-amd64 x86_64], the output stream is application/octet-stream (maybe that can cause some problems?)


text:
Q: Thunderbird bulk save attachments from many emails in older versions of TB we had attachment extractor, which had many useful functions.
Now as far as I know its not compatible with TB 78.7.0 (32bit).
Is thare a way either directly from TB or with add-on to save attachments from few emails with one command/function?
Win7 64bit / TB 78.7.0(32bit).


text:
Q: How do I use a c:/ directory path in php5 using file_get_contents? Hello I'm having problems getting my file_get_contents(); to return a string, if I use this function for a file on the actual web server it works fine but if that file which worked on the web server is now moved to my personal computer c:/ drive then file_get_contents(); does not work anymore.... I've tried adding a ini_set(); include path with no avail.
Bit flustered with the lack of absolute accurate documentation on php side unless I've missed something.
I've read the documentation here --> http://www.php.net//manual/en/function.file-get-contents.php and here --> http://www.php.net//manual/en/function.set-include-path.php too.
Here is my code :
<?php
ini_set("auto_detect_line_endings", true);

$db = mysqli_connect("localhost", "root","pass", "DB");

if(mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}

$SQL_query = "SELECT text FROM table";

$query = mysqli_query($db, $SQL_query);

echo getcwd();

$file_path = "C:\folder\file.txt";

echo file_get_contents($file_path);

while($result = mysqli_fetch_array($query))
{
    echo $result["username"] . " ";

    if(strstr($file, $result["username"]))
    {
        echo "Hello this is equal!";

    }else {
        echo"this is not equal!"
    }
}

A: Since the backslash is the escape character, you are escaping the f character in that string. The result is C:folderfile.txt.
You have to double the backslash each time you want to use it (with another words, you have to escape the backslash with backslash):
$file_path = "C:\\folder\\file.txt";

chandlermania's suggestion is even better to use the DIRECTORY_SEPARATOR constant
$file_path = "C:" . DIRECTORY_SEPARATOR . "folder" . DIRECTORY_SEPARATOR . "file.txt";


text:
Q: RoundOffTest() seems to round UP and DOWN
void RoundOffTest(double number)
{
    // What value would you pass to RoundOffTest() in order to get this output:
    // BEFORE number=1.785000 round=178.000000 (round down)
    // AFTER  NUMBER=1.785000 round=179.000000 (round up)
    //
    // It seems to round it DOWN.
    // But the 2nd line seems to round it UP.
    // Isn't that impossible?  Wouldn't there be NO possible number you could pass
    // this function, and see that output?  Or is there?

    NSLog(@"BEFORE number=%f round=%f (round down)", number, round(number * 100));
    double NUMBER = 1.785000;
    NSLog(@"AFTER  NUMBER=%f round=%f (round up)  ", NUMBER, round(NUMBER * 100));

}

A: Set number to 1.7849995 and you'll get the result you see. Note that %f is printing 6 decimal places, and that the output is rounded to that number of places - so 1.7849994 will not work.
Formatting without rounding
To answer your comment question: use NSNumberFormatter. I think all the printf style formatters round. NSNumberFormatter provides 7 different rounding modes. Here is a modified version of your test function:
void RoundOffTest(double number)
{
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setFormat:@"0.000000"];  // see docs for format strings
    [formatter setRoundingMode:NSNumberFormatterRoundFloor]; // i.e. truncate
    NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithDouble:number]];
    NSLog(@"%@\n", formatted);
    [formatter release];
}


text:
Q: Can you assign a shortcut for a custom tool you created in P4V I have recently created a custom tool in Perforce P4V that I can use by right clicking a changelist and executing the tool. However, I would like to assign a shortcut to that tool and it does not appear is the "Shortcuts" section. Is it possible to do that?

A: This is possible now (eg. Verion 2017.3), You can assign a shortcut in the 'Manage Custom Tools' dialog. Just make sure that the dialog is big enough, otherwise you can't see the Shortcut column next to the Name column, or simply scroll to the left.


text:
Q: What are the Command Line options for the VB6 IDE (Compiler) I'm doing batch compiling and need to specify the output directory.

A: A bit of Google work suggests that such a list of options can be obtained by going to the directory containing vb6.exe in Command Prompt and running
vb6.exe /?

A: VB6
Information directly from running VB6.exe /?:

Command Line Options
VB6[.EXE] [[{/run | /r}] | [/runexit] | [{/make | /m}] projectname] [/out filename]
          [/outdir path] [/d const=value{[:constN=valueN]}]
          [/mdi | /sdi] [{/cmd argument | /c argument}]

/run or /r projectname  Tells Visual Basic to compile projectname
and run it, using the arguments stored in the Command Line Arguments
field of the Make tab of the Project Properties dialog box.
/runexit projectname    Tells Visual Basic to compile projectname and
run it.  Visual Basic will exit when the project returns to design
mode.
/make or /m projectname Tells Visual Basic to compile projectname
and make an executable file from it, using the existing settings
stored in the project file.
/out filename   Specifies a file to receive errors when you build
using /m or /runexit. If you do not use /out, command line build
errors are displayed in a message box.
/outdir path    Specifies a directory path to place all output files in
when using /make.
/d or /D const=value... Tells Visual Basic which values to use for
conditional compilation constants when making an .EXE or ActiveX
component with the /make switch.  Separate multiple constants with
colons.
/cmd or /c argument Puts argument in the Command Line Arguments
field in the Make tab of the Project Properties dialog box. When used,
this must be the last switch on the command line.
/mdi or /sdi  Changes the Visual Basic environment to either Single
Document Interface (SDI) or Multiple Document Interface (MDI) mode.
Visual Basic remains in this mode until you change it.
You may use a group name in place of projectname in any of the above
switches.

Sourced from here is some additional information which pertains to older versions of VB as well. That external page may eventually disappear.

VB Command Line Summary
All Versions
vb*[.exe] [[{/run | /r} projectname] {/make | /m } projectname]
          {/cmd argument | /c argument}]

projectname The name of your project (.vbp) file.
/run or /r Tells Visual Basic to compile and run projectname using
the arguments stored in the Command Line Arguments field of the Make
tab of the Project Properties dialog box. You can run more than one
project using this command. Replace projectname with
projectgroupname.
/make or /m Tells Visual Basic to compile projectname and make
an executable (.exe) file, using the existing settings of the Path,
EXEName, and Title properties of the APP object. You can compile and
make an executable (.exe) file from more than one project using this
command. Replace of the projectname with projectgroupname.
/cmd or /c Puts argument in the Command Line Arguments field in
the Make tab of the Project Properties dialog box. When used, this
must be the last switch on the command line.
Versions 4 + Only
vb*[.exe] {/d compileconst} [{/makedll | /l} projectname]

/makedll or /l Tells Visual Basic to compile projectname and make
an in-process ActiveX server (.dll) file from it.
/d or /D Tells Visual Basic which values to use for conditional
compilation constants when making an .EXE with the /make switch or an
ActiveX DLL with the /makedll switch.
compileconst The names and values of conditional compilation
constants used in the project file.
Version 5+ Only
vb*[.exe] [{/runexit} projectname][{/m} or {/runexit} projectname /out filename}][{/m}][/sdi] or [/mdi]

/runexit Tells Visual Basic to run projectname. If for any reason
the file is changed in the process of running, all changes are ignored
and no dialog appears on exit to design mode.
filename The name of the file to receive errors when you build an
executable using the /m or /runexit option.
/out Allows you to specify a file to receive errors when you build
using the /m or /runexit option. The first error encountered is
placed in this file with other status information. If you do not use
the /out option, command line build errors are displayed in a message
box. This option is useful if you are building multiple projects.
/? Lists the available Command Line arguments.
/sdi Changes the Visual Basic environment to SDI (Single Document
Interface) mode. Visual Basic remains in SDI mode until you change it.
You can change to MDI mode by using the /mdi argument or by clearing
the SDI Development Environment option in the Advanced tab of the
Options dialog box.
/mdi Opens Visual Basic in MDI (Multiple Document Interface) mode.
Visual Basic remains in MDI mode until you change it. You can change
to SDI mode by using the /sdi argument or by selecting the SDI
Development Environment option in the Advanced tab of the Options
dialog box. MDI mode is the default.

A: /run
/runexit    - Compile and then run it.  Exit VB IDE when project returns to design mode.
/make or /m projectname  - compiles an makes exe using the existing settings in proj file
/out filename
/outdir path   Specifies a directory path to place all output files in when using /make
/d
/cmd
/mdi or /sdi
... and a couple of others.
Run vb6.exe /? for more information.

A: /make /outdir path

A: Here is the output of vb6.exe /?


text: Q: Connecting 3 or more different php files with each other (Include/Require functions) I have a problem like this before but I solved it the indecent way (copy pasting codes of one file to other which makes it redundant). I got several files included/required to other files (example, classes/class1.php, classes/class2.php and models/session.php) but I got an error when I include two files saying something about include. I know my explanation is bad but I somehow understand that it involves the path of the files. My guess are the ____DIR____ and ____FILE____ functions but I don't know how to use them. Can somebody help me?


text:
Q: file upload a pdf in laravel Hi everyone i need some help i work a program called file upload , but i dont get it what happen to the file i upload in laravel. in public folder there's a name called php4CA1.tmp every time i upload a pdf file please can anybody help me ? what is the meaning of this php4CA1.tmp or my code is wrong?
    $request->validate([
        'cover' => 'required',
        'book' => 'required',
        'name' => 'required',
        'description' => 'required',
        'price' => 'required|numeric'
    ]);

    $image = $request->file('cover');
    $new_name = rand() . '.' . $image->getClientOriginalExtension();
    $image->move(public_path('images'),$new_name);

    $book = $request->file('book');
    $new_book_name = rand() . '.' . $book->getClientOriginalExtension();
    $book->move(public_path('books'),$book);

    $data = array(
        'cover' => $new_name,
        'book' => $new_book_name,
        'name' => $request->name,
        'description' => $request->description,
        'price' => $request->price
    );
    Book::create($data);

A: Hi friend please follow as below you are passing the file instead of file name,
$book = $request->file('book');
$new_book_name = rand() . '.' . $book->getClientOriginalExtension();
$response = $book->move(public_path('books'),$new_book_name );

A: You are passing $book in

$book->move(public_path('books'),$book);

Use this:
$book = $request->file('book');
$new_book_name = rand() . '.' . $book->getClientOriginalExtension();
$book->move(public_path('books'),$new_book_name);


text:
Q: Dense basic open set contained in dense open subset For an affine variety $X$ with coordinate ring $A$ it is not hard to see that for $g\in A$ the basic open set (or distinguished open set) $$D(g):=\{ P\in X | g(P)\neq 0\}$$ is dense in $X$ if and only if $g$ is not a zero divisor in $A$.
Now let $U\subset X$ be a dense open subset. It should be true that $U$ contains one of the dense $D(g)$. Is this easy to see? Is it possible to prove this without using any scheme theory?

A: Let $P_1,\ldots,P_r$ be the minimal primes of $A$. Next let $U=X - Z$ with $I \subseteq A$ an ideal of $A$ and $Z=V(I)$. Now as $U$ is dense in $X$ we have $I \not\subseteq P_i$ for all $i$. Therefore $I \not\subseteq P_1 \cup \cdots \cup P_r$ by the prime avoidance lemma. Now $P_1 \cup \cdots \cup P_r$ is the set of zero-divisors of $A$. (More generally the set of zero divisors of an arbitrary noetherian ring is the union of all its associated primes. But here all associated primes are minimal, as $X$ is a variety, therefore $A$ is a reduced ring).
So there is a $f$ in $I$ that is no zero-divisor of $A$. The $D(f)$ is the basic open set sought for.


text:
Q: Interrupt a sleeping thread Trying to interrupt a running thread, in this example, t1, which is executed by a thread in a thread pool.
t2 is the one that sends the interrupt.
I'm unable to stop the running t1, t1 does not get InterruptedException.
What am I missing?
    Executor exec1 = Executors.newFixedThreadPool(1);

    // task to be interrupted
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("starting uninterruptible task 1");
                Thread.sleep(4000);
                System.out.println("stopping uninterruptible task 1");
            } catch (InterruptedException e) {
                assertFalse("This line should never be reached.", true);
                e.printStackTrace();
            }
        }
    };
    final Thread t1 = new Thread(runnable);

    // task to send interrupt
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                t1.interrupt();
                System.out.println("task 2 - Trying to stop task 1");
                Thread.sleep(5000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Thread t2 = new Thread(runnable2);

    exec1.execute(t1);
            t2.start();
    t2.join();

A: Seems like you misunderstand threads and Executors. You create two threads object for two runnables, but start only one of them (t2), t1 you pass to Executor to run inside it. But executor does not need Thread to be supplied -- it just need Runnable implementation. Executor itself is a thread pool (usually, but it's not required), and it just creates (and pool) threads inside it. It sees you thread just as simple Runnable (which is Thread implements). So you actualy send interrupt to the thread which was never started.
If you really want to make your code works, you should remove Executor, and just start both threads explicitly.

A: Your mistake is that you're trying to execute a Thread on a ThreadPool.
This appears to work, because Thread happens to implement Runnable, but because the thread is only being used as a Runnable and is not started as a Thread, calling methods like #interrupt() won't have the desired effect.
If you still need to use a thread pool, you should instead look into using a class like FutureTask. Wrap your Runnable in a FutureTask, and then submit the task to a thread pool. Then, when you want to interrupt the task, call futureTask.cancel(true).

A: The problem is that you can never really know which thread would be used by the Executor to run your task.
Even though you have submitted a Thread object, The Executor will use the thread created by the fixed thread pool. Thus the thread with reference t1 is not the thread in which your task is going to be executed. so calling t1.interrupt() is not going to do anything.
To properly way to do this is to use an ExecutorService and use the submit() to submit a Runnable/Callable object. This will return a Future which exposes a cancel() method which can be used to cancel the task.

A: To interrupt the executor thread ,
final ExecutorService exec1 = Executors.newFixedThreadPool(1);
final Future<?> f = exec1.submit(runnable);
...
f.cancel(true);

A: Calling Thread.interrupt does not necessarily throw an InterruptedException. It may just set the interrupted state of the thread, which can be polled by Thread.interrupted() or Thread.isInterrupted.
See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#interrupt() for more details.


text: Q: How to create a MySql innodb Cluster I am trying some days now to create a cluster with some nodes using the innodb database in MySQL but I can't find any documentation how to do so. Does anyone has a clue about it ?


text:
Q: Hausdorff space in which each point has a compact neighbourhood is locally compact Could you help me prove the following fact? I've been trying to prove it and I've searched for a hint in Englking's book, but I haven't come up with anything:
If $X$ is a Hausdorff space and each $x \in X$ has at least one compact neighbourhood, then $X$ is locally compact.
$U$ is a neighbourhood of $x \in X$ $\iff$ $\exists V$ - open $: x \in V \subset U$.
$X$ is locally compact $\iff$ each $x \in X$ has a basis of compact neighbourhoods.

A: Actually, a stronger result is true: If each point has a compact Hausdorff neighborhood, then $X$ is locally compact.
Let $x\in X$, $U$ a neighborhood of $x$, and $K$ a compact Hausdorff neighborhood of $x$. Since $K$ is regular as a subspace of $X$ and $U\cap K$ is a neighborhood of $x$ in $K,$ there is a neighborhood $C\subseteq U\cap K$ of $x$ in $K$ (and thus also in $X$ since $K$ is a neighborhood of $x$) which is closed in $K$, thus compact. This proves that there are arbitrary small compact neighborhoods around $x$.

A: A tricky one, indeed. I already had that once. Here we go :
We suppose that every point of $X$ has at least one compact neighborhood.
Let $x\in X$ and let $V$ be an open neighborhood of $x$.
We want to show that there exists a compact neighborhood $W$ of $x$ with $W \subset V$.
By hypothesis, $x$ has a compact neighborhood, let's call it $C$.
Let's take the subspace topology for $C$, so we have that $C$ is a compact Hausdorff space.
Let's now take  $U = C \cap V$. And now we have that in $C$, $U$ is an open neighborhood of $x$. We know that $C$ is locally compact since it's compact and Hausdorff.
Thus, in $C$  we have a compact neighborhood $W$ of $x$ with $W \subset U$, and then also $W \subset V$.
In the end, we must check that $W$ is a neighborhood of $x$ in $X$, too. But since a neighborhood in a neighborhood is a neighborhood, we have it directly.


text: Q: Multilayer neural networks in Python that can work with factor variables I am new to Python and I need to solve classification problem in finance with neural net. There are many factor variables in my data. Could you help me to find out if there are any neural networks with at least two hidden layer that can accept factor variables?


text:
Q: Why is regrouping the summands differently sometimes creating a different result in JS? Why is ordering the summands differently creating a different result (note this question is not about why 0.1 + 0.2 is not 0.3)?
15.2 + 30.7 + 3 = 48.9

15.2 + (30.7 + 3) = 48.900000000000006

A: It's because of the value of the intermediate results.
In the first example, it's done in this order:

*

*15.2 + 30.7 = 45.9

*45.9 + 3 = 48.9
and so we have an intermediate result of 45.9.
In the second example, it's done in this order:

*

*30.7 + 3 = 33.7

*15.2 + 33.7 = 48.9
...and so we have an intermediate result of 33.7.
Apparently, the imprecision we all know about (the old 0.1 + 0.2 thing) creeps in with the second and not the first. I'd assume that the intermediate value in the first case (33.7 or very close to it) is exactly representable, but that the intermediate value in the second case (48.9 or very close to it) is not; or at least that the first intermediate value is more precisely held than the second intermediate value.
The IEEE-754 standard requires that intermediate results be rounded to the nearest value the type can hold, rather than kept in a more precise form, apparently to increase compatibility between platforms. From this article (which is linked from this article that Paul Roub linked in a comment):

The IEEE standard requires that the result of addition, subtraction, multiplication and division be exactly rounded. That is, the result must be computed exactly and then rounded to the nearest floating-point number (using round to even)....
One reason for completely specifying the results of arithmetic operations is to improve the portability of software. When a program is moved between two machines and both support IEEE arithmetic, then if any intermediate result differs, it must be because of software bugs, not from differences in arithmetic.


text:
Q: Best way to write and run unit tests for Brunch with Coffee I am developing an application using Brunch with Coffee.
How do I write unit tests for it? I am currently mostly thinking about the model classes, so it can run without the browser, using NodeJS.
Writing the tests themselves is not the problem here, but having a good way to integrate into how brunch is set up (the way it compiles and stitches everything together and takes care of dependencies) seems a bit tricky.

A: Have you looked to see how the demo app for Brunch does it:
https://github.com/brunch/todos/tree/gh-pages/test


text:
Q: Learning JavaScript... Should I skip straight to the good stuff (the frameworks)? I learnt HTML/CSS a good few years back, then PHP a little later. I've recently become interesting in web development again, just started playing with frameworks like Django and RoR. I'm curious as to how much time/effort I should spend learning straight JS before looking at frameworks. I've been reading through a let of articles called Mastering AJAX by Brett McLaughlin which seems quite good, but I'm seeing a lot of stuff (such as cross browser compatibility - even for things like XMLHttpRequest) coming up which look like they would be non-issues if using a framework.
So, should I keep reading through these articles and try to build stuff using basic JS, or should I just start looking into jQuery and the like?
Also, I've been watching a few videos regarding GWT from Google I/O. I've been learning Java over the last year, built a few medium sized apps in it. I'm wondering if GWT is something that's worth going straight to, along with gQuery?

A: No.
Just as when you are learning to program you are taught first C/Pascal then Java/C++ and finally Python/Ruby/Smalltalk/Lisp, and when learning any language you start with simple language constructs, you should first learn ECMAScript, then learn DOM and finally frameworks.
Why? Because you'll have a deeper understanding of the language, and will be able to debug things that might seem odd unless you've got that learning experience.
If you are a seasoned developer, you can speed up each phase, but don't skip them, or you will have problems due to not fully understanding the small oddities.
Javascript is an interesting and fun language, but can act rather odd at times (Date has bitten me a  couple of times in the ass).
Use frameworks to avoid repetitive tasks and to simplify your code, but not as a starting point. Simplicity is a final goal, not the starting point, and frameworks are for that, simplicity, not for learning a language. Frameworks are intended for simplifying things for experienced developers.

Learning the differences between browsers (DOM implementations) will allow you to debug your framework. That is priceless.

I've been learning Java over the last
  year...

Javascript is not Java. Never was never will.
Even if you can compile to Javascript from Java, it's still a framework, don't jump into it unless you already know what you are doing.

A: Starting with the basics of JavaScript is a good idea, IMHO.
Read JavaScript: The Good Parts, by Douglas Crockford.  Very, very good book.

You should also check out Douglas Crockford's web site.
I also had to come back here and mention this in an update:
Douglas Crockford presented an illuminating talk about JavaScript - past, present, future - at the Microsoft MIX10 conference earlier this year.  You'll find the full video for Crockford's talk at Microsoft MIX10 - The Tale of JavaScript. I Mean ECMAScript.

A: I think "both." Mix it up. Play around with a framework. You'll get stuck when you try to do something real, so you'll pick up some JavaScript to figure it out.
A lot of the good jQuery books teach you JavaScript along the way.

A: This is one of the best videos for beginner javascript developers that understand how to program in other languages:
It's a talk the John Resig did last year at Northeastern, most of it is devoted to talking about core javascript, then the last quarter of the talk jumps into jQuery:
http://video.google.com/videoplay?docid=-7485992465859932389&ei=jhZUSu73OpfSrQLgyYV3&q=john+resig&hl=en
It's actually a really interesting tech talk and presentation since he does live examples and Resig is pretty good at presenting.
Like others in this question, I also highly recommend reading Javascript: The Good Parts for a better understanding.

A: Yes, jumping straight to framework-based programming instead of DOM is a good idea.
I started doing JS before any major frameworks like jQuery came along, and was reluctant to switch at first, but when I first started using jQuery, it felt so good to be able to write selectors and stuff and not have to worry about cross-browser compatibility.
However, there are some areas of JS where frameworks wouldn't be available.  One of them is in userscripting, where you have to make your script work on a site you don't control.  Another such one is the use of JavaScript in applications such as XUL.
Overall, I suggest you start with some trivial JS applications, then switch to jQuery instead of going on to the complex topic of DOM.

A: What makes you think that the frameworks are the good stuff and the JavaScript is not?
If you ask me, I will say that JavaScript is a real fun language and you should learn it first. JavaScript has received bad rap because it was mainly used for browser scripting and those browsers were buggy making people think that JavaScript sucks.
Crockford says that JavaScript is the world's most misunderstood language.
If your prior experience is with PHP (or any non functional language for that matter), the concept of 'first class functions' will really give you an 'aha' moment. 'Closure' will be another tool which will simplify your code and will make you wonder why all languages don't have it. Prototype inheritance will show you that there are alternatives to OOP. I would definitely suggest that you learn JavaScript first before you jump to any frameworks. I must add that you will also have to learn the concepts (first class functions/closure/prototype inheritance), to use any JS framework efficiently as all frameworks exploit the features of JavaScript.
To learn JavaScript, get Crockford's 'JavaScript, The Good Parts' book and try to learn the language using a standards compliant browser (say Firefox [with FireBug], Safari, Chrome) without focusing on DOM manipulation. This presentation by Simon Wilson is also good.
Once you have a good feel for the language, move on to the next step i.e. manipulating the DOM. I would personally suggest that you try to do some DOM manipulation using bare bone JavaScript to get better understanding of the DOM and the pain points involved. [E.g., when I attach a method to onClick of event, 'this' doesn't refer to what I think it refers to?]
After you have suffered a little bit of pain by doing DOM manipulation by hand, move on to a JavaScript framework which removes all the pain and makes JavaScript fun again. Personally, I would highly recommend jQuery over other frameworks.
And if you have any questions while on your JavaScript journey, you can always ask them on SO! :) Good luck.

A: I wouldn't touch any framework in any language until I have good basic understanding of underlying technology. Worth type of coder is one that uses tool without a knowledge.
JavaScript has somewhat sad history but in its latest incarnation it's surprisingly powerful and even fascinating language. I say - learn it well, then use whatever framework suits your current needs

A: It depends on where you want to invest your time. Ideally, we're all expert in assembly language, but that's not realistic or practical. We have to pick our battles. Then generally we attack each other for picking the wrong battle, which we call "cargo cult coding."
Personally, out of all the things I could spend a lot of time banging my head against, the intricacies of cross-platform JavaScript seemed less interesting and rewarding than other choices, so I decided to jump straight to jQuery. I'm happy with how it worked out.

A: I had the same background as you.  After 6 months of MooTools I found out that mootools was indirectly teaching me "vanilla" javascript.
I've heard people say that mootools feels more like plain ol' javascript than jquery (after all, jquery's tagline is "jQuery is designed to change the way that you write JavaScript.").
I'd recommend starting with a framework.  Plenty of the best javascript developers use frameworks.  Once you're comfortable there you'll likely be able to pick up the others frameworks and plain ol' javascript quite readily.


text:
Q: (compact, non-empty boundary )Surface Geodesics on Hyperbolic Geometry I have a basic knowledge of hyperbolic geometry . I am trying to understand the meaning of "a compact surface S  with non-empty boundary(which is neither a disk nor an annulus )with a complete hyperbolic metric with geodesic boundary" .
I know about the upper-half plane model with the metric $$ ds^2 =\frac {dx^2+dy^2}{y^2} $$
in which the geodesics are half-circles with the endpoints in the Real line and vertical half-lines with an endpoint on the Real line. But I don't have a clear idea about the issue of geodesics in a surface with a hyperbolic metric. I imagine we may use charts to pullback the metric locally from $ \mathbb R^2 $ and then somehow patch it up with partitions of unity (which should have no problem working because of the compactness of S ). I guess completeness then follows from compactness of S. Could someone please give me some intro. comments and refs?
Thanks.

A: Let's start with generalities. Suppose that $M$ is a smooth manifold with boundary. In order to define the notion of a Riemannian metric on $M$, embed $M$ as a codimension 0 submanifold in a smooth manifold $M'$ without boundary (this is always possible). Now, a Riemannian metric $g$ on $M$ is the restriction of a Riemannian metric $g'$ on $M'$. The manifold $(M,g)$ has totally geodesic boundary iff the boundary of $M$ is totally geodesic in $(M',g')$.
One say that $(M,g)$ has negative curvature iff the curvature of $(M',g')$ is negative at each point of $M$. Same for "constant curvature".
Now, in dimension 2, you can use Gauss-Bonnet to show that if $(M,g)$ is compact negatively curved with geodesic boundary, then $\chi(M)<0$. This rules out disks and annuli. Conversely, given  a compact surface $M$ with $\chi(M)<0$, $M$ admits a metric of constant negative curvature with geodesic boundary. You can prove it by gluing "pairs of pants" with geodesic boundary and equal boundary lengths.
Here are two books as references:

*

*W.P.Thurston "Three-dimensional Geometry and Topology", section 4.6.

*W.Abikoff "Real-analytic theory of Teichmuller space", chapter 2, section 3.


text:
Q: How can i use nvl function in scala I am trying to code the following :
df.select(nvl(col("id"),0))
When I execute this, I get an error value nvl not found.
Please help me to solve this issue.

A: In Spark its called coalesce, you can check this article for more details
# create new column with non Null values
tmp = testDF.withColumn('newColumn', coalesce(testDF['id'], testDF['number']))

# Check the content of new df
tmp.show()

+----+------+---------+
|  id|number|newColumn|
+----+------+---------+
|   1|     1|        1|
|   2|     2|        2|
|null|     3|        3|
|   4|  null|        4|
+----+------+---------+

In your case it may look like this:
df.select(coalesce(col("id"),lit(0)))

A: You can use a when-otherwise construct as well - see the snippet below:
df = spark.createDataFrame([(1, 2), (2, None), (None, 3)], "id: int, value: int")
df.withColumn("non_null_value", when(col("value").isNull(), 0).otherwise(col("value"))).show()

+----+-----+--------------+
|  id|value|non_null_value|
+----+-----+--------------+
|   1|    2|             2|
|   2| null|             0|
|null|    3|             3|
+----+-----+--------------+


text:
Q: Automatically create an account from specific Web-to-Lead forms Within our Web-to-Lead forms we use a hidden form field to identify the forms location. Is it possible to automatically convert certain leads (if the hidden form field matches our requirements) directly into a new account?

A: One option would be to use a trigger on lead that automatically converts the lead based on the  field value.
NOTE: This trigger was written to show you the general idea. I haven't tested it in practice.
trigger convertLead on Lead (after insert) {

    LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

    List<Database.LeadConvert> conversions = new List<Database.LeadConvert>();

    for(Lead l : Trigger.new) {
        // This is where you can test your hidden field requirements.
        if(l.CustomField__c == 'convertCondition') {
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(l.Id);
            lc.setDoNotCreateOpportunity(True);
            lc.setConvertedStatus(convertStatus.MasterLabel);

            // Use List to bulkify conversion process rather than doing one at a time
            conversions.add(lc);
            //Database.LeadConvertResult lcr = Database.convertLead(lc);
            //System.assert(lcr.isSuccess());
        }
    }

    if(conversions.size() > 0) {
        List<Database.LeadConvertResult> lcrs = Database.convertLead(lc);
    }
}


text:
Q: Why "ORA-00940: invalid ALTER command" when i try alter my procedure MY_PRC using this procedure? CREATE OR REPLACE PROCEDURE COMPILE_OBJECT(my_type VARCHAR2,
                                           my_name VARCHAR2,
                                           my_package_part VARCHAR2 := NULL) IS
    v_text VARCHAR2(500) := 'ALTER :my_type :my_name COMPILE :my_package_part';
BEGIN
    --try alter objects
    EXECUTE IMMEDIATE v_text USING my_type, my_name, my_package_part;
END;

A: That would be, as Sayan commented, something like this:
SQL> CREATE OR REPLACE PROCEDURE compile_object (
  2     my_type           VARCHAR2,
  3     my_name           VARCHAR2,
  4     my_package_part   VARCHAR2 := NULL)
  5  IS
  6     v_text  VARCHAR2 (500);
  7  BEGIN
  8     v_text :=
  9           'alter '
 10        || my_type
 11        || ' '
 12        || DBMS_ASSERT.sql_object_name (my_name)
 13        || ' compile '
 14        || my_package_part;
 15
 16     EXECUTE IMMEDIATE v_text;
 17  END;
 18  /

Procedure created.

SQL> EXEC compile_object('procedure', 'p_roles', null);

PL/SQL procedure successfully completed.

SQL>


text:
Q: Is there a way to make a smart pointer that points to either a std::ifstream or std::cin? I want to take input from an istream from either a std::ifstream or std::cin depending on some condition.
As far as I can get it working, I had to use a raw std::istream* pointer:
int main(int argc, char const* argv[]) {
    std::istream *in_stream;
    std::ifstream file;
    if (argc > 1) {
        std::string filename = argv[1];
        file.open(filename);
        if (not file.is_open()) {
            return -1;
        }
        in_stream = &file;
    } else {
        in_stream = &std::cin;
    }
    // do stuff with the input, regardless of the source...
}

Is there a way to rewrite the above using smart pointers?

A: This may be a question about ownership: How does one wrap and pass around two different std::istream instances, one of which is owned and needs disposal (which calls close() upon destruction) and ownership transfers, whereas the other one is not owned by user code (e.g. std::cin) and cannot be deleted. The solution is polymorphism: Create an interface like
struct StreamWrapper {
  virtual std::istream &stream() = 0;
  virtual ~StreamWrapper() = default;
};

and two implementations, e.g. OwnedStreamWrapper and UnownedStreamWrapper. The former can contain a std::istream directly (which is moveable, but not copyable) and the latter can contain (e.g.) a std::istream&, i.e. have no ownership over the referenced stream instance.
struct OwnedStreamWrapper : public StreamWrapper {
  template <typename... A>
  OwnedStreamWrapper(A &&...a) : stream_{std::forward<A>(a)...} {}
  std::istream &stream() override { return stream_; }

 private:
  std::ifstream stream_;
};

struct UnownedStreamWrapper : public StreamWrapper {
  UnownedStreamWrapper(std::istream &stream) : stream_{stream} {}
  std::istream &stream() override { return stream_; }

 private:
  std::istream &stream_;
};

Apart from the stream ownership, wrapper ownership matters as well and can be used either to handle the wrappers' (and streams') lifespan automatically on the stack, or to allow a wrapper's lifespan to exceed that of the current stack frame. In the example below, the first ReadWrapper() takes ownership of the wrapper and deletes it automatically whereas the second ReadWrapper() does not take ownership. In both cases polymorphism (i.e. the implementation of StreamWrapper) determines how the underlying stream is handled, i.e. whether it outlives its wrapper (like std::cin should) or dies together with it (like a manually instantiated stream should).
void ReadWrite(std::istream &in, std::ostream &out) {
  std::array<char, 1024> buffer;
  while (in) {
    in.read(buffer.data(), buffer.size());
    out.write(buffer.data(), in.gcount());
  }
}

void ReadWrapper(std::unique_ptr<StreamWrapper> stream) {
  ReadWrite(stream->stream(), std::cout);
}

void ReadWrapper(StreamWrapper &stream) {
  ReadWrite(stream.stream(), std::cout);
}

Below are all four combinations of { owned | unowned } { streams | stream wrappers } in a runnable example:
#include <array>
#include <fstream>
#include <iostream>
#include <memory>
#include <utility>

namespace {

/********** The three snippets above go here! **********/

}  // namespace

int main() {
  OwnedStreamWrapper stream1{"/proc/cpuinfo"};
  std::unique_ptr<StreamWrapper> stream2{
      std::make_unique<OwnedStreamWrapper>("/proc/cpuinfo")};
  std::ifstream stream3_file{"/proc/cpuinfo"};  // Let's pretend it is unowned.
  UnownedStreamWrapper stream3{stream3_file};
  std::ifstream stream4_file{"/proc/cpuinfo"};  // Let's pretend it is unowned.
  std::unique_ptr<StreamWrapper> stream4{
      std::make_unique<UnownedStreamWrapper>(stream4_file)};

  ReadWrapper(stream1);             // owned stream, wrapper kept
  ReadWrapper(std::move(stream2));  // owned stream, wrapper transferred
  ReadWrapper(stream3);             // unowned stream, wrapper kept
  ReadWrapper(std::move(stream4));  // unowned stream, wrapper transferred
}

A: A smart pointer is kind of an awkward fit for this situation, because it requires a dynamic allocation (which is probably not necessary in this case)

1. Do your processing in another function
As @BoP pointed out in the comments a nice way to handle this could be to use another function that gets passed the appropriate input stream:
godbolt
int do_thing(std::istream& in_stream) {
    // do stuff with the input, regardless of the source...
    int foobar;
    in_stream >> foobar;

    return 0;
}

int main(int argc, char const* argv[]) {
    std::ofstream{"/tmp/foobar"} << 1234;

    if(argc > 1) {
        std::ifstream file{argv[1]};
        if(!file) return -1;

        return do_thing(file);
    } else {
        return do_thing(std::cin);
    }
}

2. Switch the stream buffer
If you won't be using std::cin at all if a filename is passed you could change the streambuffer of std::cin to the one of the file with rdbuf() - that way you can use std::cin in both cases.
godbolt
std::ifstream file;
std::streambuf* oldbuf = std::cin.rdbuf();

if (argc > 1) {
    file.open(argv[1]);
    if (!file) return -1;

    // switch buffer of std::cin
    std::cin.rdbuf(file.rdbuf());
}

// do stuff with the input, regardless of the source...
int foobar;
std::cin >> foobar; // this will reader either from std::cin or the file, depending on the current streambuffer assigned to std::cin

// restore old stream buffer
std::cin.rdbuf(oldbuf);

3. Using std::unique_ptr / std::shared_ptr with a custom deleter
The easiest solution if you still want to use smart pointers would be to use std::unique_ptr / std::shared_ptr with a custom deleter that handles the std::cin case:
godbolt
// deletes the stream only if it is not std::cin
struct istream_ptr_deleter {
    void operator()(std::istream* stream) {
        if(&std::cin == stream) return;
        delete stream;
    }
};

using istream_ptr = std::unique_ptr<std::istream, istream_ptr_deleter>;

// Example Usage:
istream_ptr in_stream;
if (argc > 1) {
    in_stream.reset(new std::ifstream(argv[1]));
    if (!*in_stream) return -1;
} else {
    in_stream.reset(&std::cin);
}

int foobar;
*in_stream >> foobar;


text:
Q: In how many ways can you create a paragraph in LaTeX? How many ways are there to indicate the beginning of a new paragraph in LaTeX? Only way I know of is the double linebreak.

A: An empty line and \par have been already mentioned, but there is more. Quoting The TeXbook, p. 86:

A paragraph also ends when you type
  certain things that are incompatible
  with horizontal mode. For example, the
  command \vskip 1in on line 16 of
  Chapter 6's story file was enough to
  terminate the paragraph about
  ...beautiful documents.; no \par was
  necessary, since \vskip introduced
  vertical glue that couldn't belong to
  the paragraph.

A: Neither an empty line nor a \par token indicate the beginning of a new paragraph; they end an active paragraph and switch to unrestricted vertical mode (if the processor has been in unrestricted horizontal mode so far). To begin a new paragraph, either \indent, \noindent or a horizontal command has to be used—i.e., a command that forces TeX to switch to (unrestricted) horizontal mode. Well known horizontal commands are the character-insertion commands such as a, and \unhbox. The full list of horizontal commands is given by §6.2 of TeX by Topic.

A: Phillip has given a great explanation how paragraphs can be started. Since you question means alternatives to a double line break, which actually doesn't start a paragraph but it ends one, I assume your intention is how to create a paragraph break, i.e. how to end a paragraph.
You could use the command \par instead of two consecutive linebreaks, i.e. instead of an empty line in your source code.
Another possibility is \endgraf, since latex.ltx defines
\let\endgraf=\par

Then, there's ^^M (if active, such as done by \obeylines) and \@@par. Packages could define further aliases and even modify paragraph commands (yes, there's also \@par).
Just scan latex.ltx or source2e to find such commands.
I would recommend to use blank lines or \par, but not other internal commands or shortcuts, to keep your code readable.


text:
Q: how to get the filename and filebody? $(function(){
    $('#clickme').click(function(){
        $('#uploadme').click();
    });

    $('#uploadme').change(function(){
        $('#filename').val($(this).val());
    });
});

<input type="button" id="clickme" value="Browse" />
  <input type="text" id="filename" />
  <input type="file"  id="uploadme" />

<style>

    #uploadme {
  width: 1px;
  height: 1px;
  visibility: hidden;
}
</style>

From these , I need to get the file name and filebody which I select(For Eg: filename.txt) .. Please provide a solutionenter code here


text:
Q: why can't i type in div and i can't see code snippets when i type getElementById why can't i change innerHTML

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document</title>

output :
output
i can't even see the code snippets:
code snippets-1,
code snippets-2
where is wrong in this code?,I searched but couldn't find the result I wanted, I'm not even sure I'm asking the right question, it happens every time I see an example but not when I do,i scare of stop myself in the start.
I'm trying to write hi to the div and check the hi in the console as a result I can't see what I'm typing on the page but I see it in the console

A: document.getElementsByClassName() returns an array of items that match the class you passed in as an argument.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

A: In your example, you get the innerHTML DATA, it is not a reference to the element's HTML. The a variable is now a string of text. Therefore, when you try and change it, you change the value of a and NOT the innerHTML of the element.
Instead, get the element reference as below. Then set the innerHTML on that element.
Also, as you getting multiple elementS (plural), you will either need to loop after all, or get the first one. Often it's easier to just use document.querySelector('.sa') when working with css selectors.

var a = document.getElementsByClassName("sa").innerHTML; // a is a string
a = "new";
console.log(a);

// You want
var aElement = document.getElementsByClassName("sa")[0]
aElement.innerHTML = "new";

old

A: document.getElementsByClassName() returns a collection of elements. If you want to access the innerHTML property if these elements you will have to use a .forEach() loop like in:
document.getElementsByClassName().forEach(e=>e.innerHTML="new stuff");


text:
Q: guess = raw_input() when i press enter button what will the value of the guess variable? guess = raw_input(): if I press enter button here what will be the value inside the guess variable and is it printable?
Executable code in shell IDE:
>>> guess = raw_input()

>>> print guess

A: If you press enter then guess=''.
You can print guess which will turn out to be blank.


text:
Q: Image created in PHP is shown only if accessed with direct link I created a script on localhost which shows some stats from a json. If I access the direct link, everything is fine. If I tried to add that link to an  HTML image tag, the page is rendered white with no image.
What could be the problem? If you need the code, I'll edit later (I'm on mobile).

Could this error be due to the usage of localhost?
<!DOCTYPE html>

    <title>TEST</title>

I can see the image if I access localhost/file.php?id=NUMERIC_STEAMID, but if I add this line  the page remains empty.
<?php
include("settings.php");

// GET CULOURS
if(!isset($_GET['culoare_titlu'])) $color_title = "FFC200"; else $color_title = substr($_GET['culoare_titlu'],0,6);
if(!isset($_GET['culoare_info'])) $color_info = "FFFFFF"; else $color_info = substr($_GET['culoare_info'],0,6);
if(!isset($_GET['bg'])) $bg = "bg1"; else $bg = $_GET['bg'];
if(!isset($_GET['rank'])) $rank = "0"; else $rank = (int)$_GET['rank'];
// Get Userid
if(!$_GET['id'] || !ctype_digit($_GET['id'])){
    echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
$steamid = $_GET['id'];

// Get username, avatar , kills, deaths and played time
$noDigit = 0;
$hoursPlayed = 0;
$weHaveCSGO = 0;
$nullJson = 0;
if(ctype_digit($steamid)){
    $noDigit = 1;
    $uuser = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$steamauth['apikey']."&steamids=".$steamid."";
    // cURL for this
    $ch_1 = curl_init($uuser);
    curl_setopt($ch_1, CURLOPT_RETURNTRANSFER, true);
    $mh = curl_multi_init();
     curl_multi_add_handle($mh, $ch_1);
     // execute all queries simultaneously, and continue when all are complete
    $running = null;
    do {
        curl_multi_exec($mh, $running);
        $content = curl_multi_getcontent($ch_1);
    } while ($running);
    $response_1 = curl_multi_getcontent($ch_1);
    $user = json_decode($response_1, true);
    // Until here
    if(isset($user['response']['players'][0]['steamid'])){
        $nullJson = 1;
        $customURL = $user['response']['players'][0]['profileurl'];
        $username = $user['response']['players'][0]['personaname'];
        $avatar = $user['response']['players'][0]['avatarfull'];
        $privacy = $user['response']['players'][0]['communityvisibilitystate'];
        if($privacy == 3){
            $getGames = simplexml_load_file($customURL."games?tab=all&xml=1");
            foreach($getGames->games->game as $game){
                if($game->appID == "730"){
                    $weHaveCSGO = 1;
                    $hoursPlayed = $game->hoursOnRecord;
                }
            }
            $xml = simplexml_load_file($customURL."?xml=1");
            $customMessage = $xml->stateMessage;
            if($weHaveCSGO == 1){
                $ggame = "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=".$steamauth['apikey']."&steamid=".$steamid."";
                // cURL for this too
                $ch_2 = curl_init($ggame);
                curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, true);
                $mh = curl_multi_init();
                curl_multi_add_handle($mh, $ch_2);
                // execute all queries simultaneously, and continue when all are complete
                $running = null;
                do {
                    curl_multi_exec($mh, $running);
                    $content = curl_multi_getcontent($ch_2);
                } while ($running);
                $response_2 = curl_multi_getcontent($ch_2);
                $game = json_decode($response_2);
                foreach($game->playerstats->stats as $stats){
                    if($stats->name == "total_kills"){ $total_kills = $stats->value ; }
                    else if($stats->name == "total_deaths"){ $total_deaths = $stats->value ; }
                    else if($stats->name == "last_match_favweapon_id"){ $last_match_weapon = $stats->value ; }
                    else if($stats->name == "total_rounds_played"){ $total_rounds_played = $stats->value; }
                    else if($stats->name == "total_wins"){ $total_wins = $stats->value; }
                }
            }
        }

// Convert weaponID to weaponName

// This function just convert weaponID to weaponName so i removed from here

    }
}

$rank_image = "images/ranks/0.png";
$rankimage = ImageCreateFromPNG($rank_image);

// Create banner
switch($bg){
    case 'bg1':
    case 'bg2':
    case 'bg3':
    case 'bg4':
        $im = ImageCreateFromPNG("images/banners/$bg.png") or die ( 'GD Library not available atm.' );
    break;
    default:
        $im = ImageCreateFromPNG("images/banners/bg1.png") or die ( 'GD Library not available atm.' );
    break;
}

// Last match weaponID
$weapon = "images/weapons/hud/".$last_match_favweapon.".png";
$lmweapon = ImageCreateFromPNG($weapon);

//Culours for text
$color_green = imagecolorallocate($im, 0, 183, 21);
$color_red = imagecolorallocate($im, 255, 0, 0);
$color_title = "0x$color_title";
$color_info = "0x$color_info";
$color_online = "0x24FF00";
$color_offline = "0xFF0000";
$color_black = "0x000000";
$color_bgreen = imagecolorallocate($im,0,160,0);

// Make some changes
$avatar = str_replace("https","http",$avatar);

// Get new sizes for avatar
list($width, $height) = getimagesize($avatar);
$newwidth = 90;
$newheight = 90;

// Load
$source = imagecreatefromjpeg($avatar);

// Lenght username
if(strlen($username) > 21){
    $username = substr($username,0,21);
}

// Kills/Deaths Ratio
$kdr = @round($total_kills/$total_deaths,2);

// Win Ratio

$win = round((($total_wins/$total_rounds_played)*100),2);

//Let's create image, but first check user
if($noDigit == 0 || $weHaveCSGO == 0 || $nullJson == 0){
    imagettftext($im,20,0,140,60,$culoare_text_info,'fonts/arialbd.ttf',"This user doesn't exist !");
} else {
//Avatar
imagecopyresized($im, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Rank
imagecopy($im,$rankimage,96,3,0,0,imagesx($rankimage),imagesy($rankimage));
// Username
imagettftext($im,9,0,153,20,$color_info,'fonts/arialbd.ttf',$username);
// Status
if($customMessage == "Online"){
    imagettftext($im,7,0,290,20,$color_bgreen,'fonts/arialbd.ttf',"Online");
}
$cauta   = 'Last Online';
$cautare = strpos($customMessage, $cauta);
$cauta2 = 'In-Game
Counter-Strike: Global Offensive';
$cautare2 = strpos($customMessage, $cauta2);
$cauta3 = 'In-Game
';
$cautare3 = strpos($customMessage, $cauta3);
if ($cautare !== false) {
    imagettftext($im,7,0,290,20,$color_red,'fonts/arialbd.ttf',"Offline");
} elseif($cautare2 !== false){
    imagettftext($im,7,0,282,20,$color_bgreen,'fonts/arialbd.ttf',"Playing CS:GO");
} elseif($cautare3 !== false){
    imagettftext($im,7,0,276,20,$color_title,'fonts/arialbd.ttf',"IN OTHER GAME");
}
// Fav weapons from last match
imagecopy($im,$lmweapon,107,30,0,0,imagesx($lmweapon),imagesy($lmweapon));
imagettftext($im,9,0,112,70,$color_title,'fonts/arialbd.ttf',$last_match_favweapon);
// K/D Ratio
imagettftext($im,11,0,166,52,$color_info,'fonts/arialbd.ttf',$kdr);
imagettftext($im,9,0,168,70,$color_title,'fonts/arialbd.ttf',"K/D");
// Win RATIO
imagettftext($im,11,0,216,52,$color_info,'fonts/arialbd.ttf',$win."%");
imagettftext($im,9,0,218,70,$color_title,'fonts/arialbd.ttf',"WIN %");
// Hours Played
imagettftext($im,11,0,276,52,$color_info,'fonts/arialbd.ttf',$hoursPlayed."h");
imagettftext($im,9,0,278,70,$color_title,'fonts/arialbd.ttf',"TIME");
}
header( 'Content-type: image/png' );
imagepng($im);
imagedestroy($im);

?>

A: localhost/banner.php?id=STEAMID&bg=bg1&rank=0
Should be http://localhost/banner.php?id=STEAMID&bg=bg1&rank=0

A: Your problem is you are pointing to image file in wrong way

it should be like this

if you will not add http:// protocol browser will read it as file/directory and will find your image like this
Assumming you are in localhost root directory
browser will load it as
http://localhost/localhost/banner.php?id=STEAMID&bg=bg1&rank=0

instead of
http://localhost/banner.php?id=STEAMID&bg=bg1&rank=0

When you direct access your image your browser read it as
http://localhost/banner.php?id=STEAMID&bg=bg1&rank=0


text:
Q: Pointer to array - initialize element I have a class Pixel and a class Image with a function used to update a pixel line. I want to initialize the pixel line. My problem is to initialize the array. Actually I have this :
bool UpdateLine(Pixel line[], int nb)
{
    bool noError = true;
    line = new Pixel[nb];
    for (int r = 0; r < nb; r++)
    {
        line[r] = new Pixel(); // -> line causing troubles

        // do some stuff with my pixel
        [...]
    }
    return noError;
}

When I try this I have :

no viable overloaded '='

How can I initialize each elements for my array ?

A: You actually have two problems.
The first, regarding your error, is because new Pixel() results in a pointer to a Pixel object. In C++ you don't need new to create objects (do you come from a Java or C# background perhaps?). The initial allocation of the array creates the objects for you.
The second problem is that you assign to the pointer variable line, but line is a local variable inside the function. All modification to it will be lost once the function returns, and you will have a memory leak. You need to pass line by reference.

In the future when dealing with collections of a single type of data, I suggest you use std::vector instead. You still need to pass the vector by reference though, if you want to add elements to it.

A:     line[r] = new Pixel(); // -> line causing troubles

line[r] is a Pixel object, not a pointer, so you can't assign a pointer to it.
Why aren't you using a std::vector?


text:
Q: Cannot cast array data from dtype('float32') to dtype('int64') according to the rule 'safe' I'm trying to use a script 'format_veg_params.py' that takes geotiff data for vegetation parameterization and converts it to the needed text format for the VIC model (a model that uses remote sensing data to calculate the hydraulic balance in a watershed).
Usage:
 python format_veg_params.py <template raster> <land cover raster>
<output veg parameter file> <land cover classification scheme>

The commande Line Used:
$ python format_veg_params.py
../data/input/gis/Nyando_grid.tif
../data/input/gis/Nyando_basin_LC_IGBP.tif
../data/input/veg.param IGBP

running the script on terminal, gives me the following error:
Traceback (most recent call last):
  File "format_veg_params.py", line 180, in <module>
    main()
  File "format_veg_params.py", line 174, in main
    format_veg_params(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
  File "format_veg_params.py", line 120, in format_veg_params
    clsAttributes)-1)].ravel()).argmax()
TypeError: Cannot cast array data from dtype('float32') to dtype('int64') according to the rule 'safe'

I'd like to know what the problem is and how to solve it.
the script of 'format_veg_params.py' is as follows:
# import dependencies
import os
import sys
import json
import numpy as np
from osgeo import gdal
from osgeo.gdalnumeric import *
from osgeo.gdalconst import *

def format_veg_params(basinMask,lcData,outVeg,scheme='IGBP'):
    """
    FUNCTION: format_veg_params
    ARGUMENTS: basinMask - path to basin template raster
               lcData - path to land cover raster
               outveg - path output vegetation parameter file
    KEYWORDS:  scheme - Abbreviation of land cover classification scheme the
                        input land cover data is formatted in
    RETURNS: n/a
    NOTES: Returns no variables but writes an output file
    """

    # define script file path for relative path definitions
    __location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

    # get land cover classification scheme and create path to lookup table
    if scheme == 'IGBP':
        attriFile = os.path.join(__location__,'veg_type_attributes_igbp.json')
    elif scheme == 'GLCC':
        attriFile = os.path.join(__location__,'veg_type_attributes_glcc.json')
    elif scheme == 'IPCC':
        attriFile = os.path.join(__location__,'veg_type_attributes_ipcc.json')
    else:
        raise SyntaxError('Land cover classification scheme not supported')

    band = 1 # constant variable for reading in data

    # open/read veg scheme json file
    with open(attriFile) as data_file:
        attriData = json.load(data_file)

    # pass look up information into variable
    clsAttributes = attriData['classAttributes']

    # create list of input raster files
    infiles = [os.path.join(__location__,basinMask),
               os.path.join(__location__,lcData)]

    try: # try to read in the raster data

        # read basin grid raster
        ds = gdal.Open(infiles[0],GA_ReadOnly)
        b1 = ds.GetRasterBand(band)
        mask = BandReadAsArray(b1)
        maskRes = ds.GetGeoTransform()[1]
        ds = None
        b1 = None

        # read land cover raster
        ds = gdal.Open(infiles[1],GA_ReadOnly)
        b1 = ds.GetRasterBand(band)
        lccls = BandReadAsArray(b1)
        clsRes = ds.GetGeoTransform()[1]
        ds = None
        b1 = None

    # if not working, give error message
    except AttributeError:
        raise IOError('Raster file input error, check that all paths are correct')

    ratio = maskRes/clsRes # get ratio of high resoltion to low resolution

    # get file path to output file
    vegfile = os.path.join(__location__,outVeg)

    # check if the output parameter file exists, if so delete it
    if os.path.exists(vegfile)==True:
        os.remove(vegfile)

    try: # try to write output veg parameter file

        # open output file for writing
        with open(vegfile, 'w') as f:

            cnt = 1 # grid cell id counter

            # loop over each pixel in the template raster
            for i in range(mask.shape[0]):
                y1 = int(i*ratio)
                y2 = int(y1+ratio)
                for j in range(mask.shape[1]):
                    x1 = int(j*ratio)
                    x2 = int(x1+ratio)

                    # get land cover data within template raster pixel
                    tmp = lccls[y1:y2,x1:x2]

                    # if not a mask value...
                    if mask[i,j] == 1:
                        # if there are nodata values...
                        if np.any(tmp>len(clsAttributes)-1)==True:
                            # ...find where they are...
                            negdx = np.where(tmp>len(clsAttributes)-1)
                            try:
                                # ...and calculate hisogram for only data values
                                tmp[negdx] = np.bincount(tmp[np.where(tmp<len(
                                                clsAttributes)-1)].ravel()).argmax()
                            except ValueError:
                                tmp[negdx] = 0
                        uniqcnt = np.unique(tmp) # number of unique values
                        clscnt = np.bincount(tmp.ravel())

                        # check if there is only 1 value in unique value array
                        if type(uniqcnt).__name__ == 'int':
                            Nveg = 1 # if so, only 1 value
                        else:
                            Nveg = len(uniqcnt) # if not, n veg equal to unique values

                        # write the grid cell id and number of classes
                        f.write('{0} {1}\n'.format(cnt,Nveg))

                        # if there is vegetation data...
                        if Nveg != 0:
                            # ...loop over each class...
                            for t in range(uniqcnt.size):
                                # ...and grab the parameter attributes
                                vegcls = int(uniqcnt[t]) # class value
                                Cv = np.float(clscnt[uniqcnt[t]])/np.float(clscnt.sum()) # percent coverage
                                attributes = clsAttributes[vegcls]['properties'] # intermediate variale
                                rdepth1 = str(attributes['rootd1']) # rooting depth layer 1
                                rfrac1 = str(attributes['rootfr1']) # rooting fraction layer 1
                                rdepth2 = str(attributes['rootd2']) # rooting depth layer 2
                                rfrac2 = str(attributes['rootfr2']) # rooting fraction layer 2
                                rdepth3 = str(attributes['rootd3']) # rooting depth layer 3
                                rfrac3 = str(attributes['rootfr3']) # rooting fraction layer 3

                                # write the veg class information
                                f.write('\t{0} {1:.4f} {2} {3} {4} {5} {6} {7}\n'.format(vegcls,Cv,rdepth1,rfrac1,rdepth2,rfrac2,rdepth3,rfrac3))

                    cnt+=1 # plus one to grid cell id counter

    # except raise an error when it doesn't work
    except IOError:
        raise IOError('Cannot write output file, error with output veg parameter file path')

    return

def main():
    n_args = len(sys.argv)

    # Check user inputs
    if n_args != 5:
        print("Wrong user input")
        print("Script writes the vegetation parameter file for the VIC model")
        print("usage: python format_veg_params.py <template raster> <land cover raster> <output veg parameter file> <land cover classification scheme>")
        print("Exiting system...")
        sys.exit()

    else:
        # Pass command line arguments into function
        format_veg_params(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])

    return

# Execute the main level program if run as standalone
if __name__ == "__main__":
    main()

A: It's a type cast error at this line:
  tmp[negdx] = np.bincount(tmp[np.where(tmp<len(
                                           clsAttributes)-1)].ravel()).argmax()

it means it is expecting an integer value at some point in this instruction, but there is a floating point value instead.
But it's impossible to tell without having a reproducable example (the GeoTIFF file and the rest of the parameters you use to run it).


text:
Q: Difference between "Find Usages" and "Find All References" What's the difference between "Find Usages" and "Find All References" in Visual Studio (in particular, VS 2017)?  They generate a different UI window so they seem like distinct features.  When would they return a different set of results?

A: Find Usages is a Resharper feature (i.e. not built into Visual Studio directly).


text:
Q: Invalid HTML (img: 'src' must be non-empty) when using "attr-binding" with knockout.js I love knockout.js and I use is very often.
But when I use the "attr-binding" for an img's src or alt attribute, like
data-bind="attr: { src: photo.src, alt: 'description'}"

The W3C-validator says that's invalid HTML:

Bad value for attribute src on element img: Must be non-empty.

And they are right, because the attributes are empty until the model was bound and executed.
Is there any other workaround than providing a link to a wrong image? Or in other words, is it a real problem somebody has been facing before?

A: You can try
<img src="#" alt="" data-bind="attr: { src: photo.src, alt: 'description'}" />

A: You can always use this -
data-bind="attr: { src: photo.src || 'default.jpg' }"

Fiddle example - http://jsfiddle.net/jAYPL/


text:
Q: Visualforce Styling - How to put command button after inputfield? I have a quick question regarding vf page styling. I have a page that looks like this

Basically, what I want to do is get the button "find study" to be on the right side of the field. My vf code looks like
<!-- Fields -->
        <apex:pageBlockSection collapsible="false" columns="2" id="pbsInfo" >
            <!-- Row 1 -->

            <apex:inputText value="{!query}" label="Protocol Number" id="inputField" >
            <apex:commandButton value="Find Study" action="{!runSearch}" reRender="pbsInfo" status="filterChangeStatus" />
                <apex:actionStatus id="filterChangeStatus">
                        <apex:facet name="start">
                            <apex:image value="/img/loading.gif"/>
                        </apex:facet>
                </apex:actionStatus>
            </apex:inputText>

I've tried using html tags like div and span, but haven't been able to get it to work. Without creating a 3rd column, does anyone know how to solve this issue?

A: I got the answer after playing around with it for a while. Just added style="float:left" to the input text field
<apex:inputText value="{!query}" label="Protocol Number" id="inputField" style="float:left">
        <apex:commandButton value="Find Study" action="{!runSearch}" reRender="pbsInfo" status="filterChangeStatus" />
            <apex:actionStatus id="filterChangeStatus">
                    <apex:facet name="start">
                        <apex:image value="/img/loading.gif"/>
                    </apex:facet>
            </apex:actionStatus>
        </apex:inputText>


text:
Q: Objeto Panel en visual studio c# - Windows Forms Estoy realizando una aplicación que consta de un solo Windows Forms y varios objetos Panel. La idea es que cuando se pulse una opción del programa muestre un panel u otro dependiendo de la opción elegida.
Los paneles los activo para visualizar con su método Show() y los escondo con Hide(). Los paneles para las opciones del programa tienen todos las mismas dimensiones.
Mi problema es que cuando elijo la primera vez una opción del programa desactiva el panel que hay en curso pero no visualizo el panel que activo con el método show(). No se si es posible mostrar y ocultar paneles las veces que se necesite.

A: Seguramente hayas creado todos los paneles dentro del panel que estás ocultando, y por lo tanto, ocultas todos de golpe.
Prueba a poner antes del show()
nombreDelPanel.Parent = this;

A: Si quieres tener tu Formulario principal siempre activo y que tus Paneles se abran o se visualicen dentro del mismo formulario, con Paneles no es lo ideal; cambia a Formularios.
Para que tenga esa funcionalidad tu formulario principal tiene que ser IsMDIContainer = true esta opcion esta las propiedades del formulario.
Teniendo eso solo haces:
Formulario2 Form2 = new Formulario2;
Form2.MdiParent = this;
Form2.show();


text:
Q: CompletableFuture executing at server startup and not when invoked I have two CompletableFutures and one combining them as below and they are getting executed on server start up and not when I call them. How do I make them execute when I call them?
@Service
public class testFutures {

public String runFutures(){
return combinedFuture;
}

CompletableFuture<String> future1(){
return CompletableFuture.supplyAsync(() -> {
   System.out.println("Future 1");
return "Future 1"
});
}

CompletableFuture<String> future2(){
return CompletableFuture.supplyAsync(() -> {
   System.out.println("Future 2");
   return "Future 2";
});
}

CompletableFuture<String> combinedFuture = future1().thenCombine(future2(),
(future1, future2) -> {
   System.out.println("Combined Future);
    return "Combined Future";
});

}


text:
Q: go + elastigo panic: runtime error: index out of range I'm testing golang with elasticsearch
I'm using the library:
https://github.com/mattbaird/elastigo
My problem is when i run:
go run elastigo_postal_code2.go

The compiler show something like this:
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x893ce0, 0xc82000a150)
        /opt/go/src/runtime/panic.go:464 +0x3ff
main.main()
        /home/hector/go/elastigo_postal_code2.go:80 +0xa30
exit status 2

I'm not sure what this means or how I can fix it!
Someone can help me and tell me I'm doing wrong
/*

curl -X PUT "http://localhost:9200/mx2/postal_code/1" -d "
{
    \"cp\"         : \"20000\",
    \"colonia\"    : \"Zona Centro\",
    \"ciudad\"     : \"Aguascalientes\",
    \"delegacion\" : \"Aguascalientes\",
    \"location\": {
        \"lat\": \"22.0074\",
        \"lon\": \"-102.2837\"
    }
}"

curl -X PUT "http://localhost:9200/mx2/postal_code/2" -d "
{
    \"cp\"         : \"20008\",
    \"colonia\"    : \"Delegacion de La Secretaria de Comercio y Fomento Industrial\",
    \"ciudad\"     : \"Aguascalientes\",
    \"delegacion\" : \"Aguascalientes\",
    \"location\": {
        \"lat\": \"22.0074\",
        \"lon\": \"-102.2837\"
    }
}"

*/

package main

import (
    "encoding/json"
    "flag"
    "log"
    elastigo "github.com/mattbaird/elastigo/lib"
)

var (
    eshost *string = flag.String("host", "localhost", "Elasticsearch Server Host Address")
)

func main() {
    flag.Parse()
    log.SetFlags(log.Ltime | log.Lshortfile)

    c := elastigo.NewConn()
    c.Domain = *eshost

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    searchJson := `{
        "size": 10,
        "query": {
            "match": {
                "all": {
                    "query": "aguascalientes",
                    "operator": "and"
                }
            }
        },
        "sort": [{
            "colonia": {
                "order": "asc",
                "mode": "avg"
            }
        }]
    }`

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    searchresponse, err := c.Search("mx2", "postal_code", nil, searchJson)
    if err != nil {
        log.Println("error during search:" + err.Error())
        log.Fatal(err)
    }

    // try marshalling to ElasticSearchResponse type
    var t ElasticSearchResponse
    bytes, err := searchresponse.Hits.Hits[0].Source.MarshalJSON()
    if err != nil {
        log.Fatalf("err calling marshalJson:%v", err)
    }

    json.Unmarshal(bytes, &t)
    log.Printf("Search Found: %s", t)
    c.Flush()

}

func (t *ElasticSearchResponse) String() string {
    b, _ := json.Marshal(t)
    return string(b)
}

// used in test suite, chosen to be similar to the documentation
type ElasticSearchResponse struct {
    Cp         string `json:"cp"`
    Colonia    string `json:"colonia"`
    Ciudad     string `json:"ciudad"`
    Delegacion string `json:"delegacion"`
    Location Location `json:"location"`
}

type Location struct {
    Lat string `json:"lat"`
    Lon string `json:"lon"`
}

The code of my scritp is here:
https://gist.github.com/hectorgool/c9e18d7d6324a9ed1a2df92ddcc95c08#file-elastigo_example-go-L80

A: That's not a compile error, you are getting panic: runtime error: index out of range
If the slice searchresponse.Hits.Hits has a length of 0, indexing the first element is going to be out of range and panic. You can check for the number of Hits first with searchresponse.Hits.Len().


text:
Q: Can't get index from a 2d array I am trying to get 25 Numbers to put them in a 2D list/array but whenever i try to get the index of the item, I'm always facing a valueError.
What i tried.
I have tried using a for loop with the enumerate() function to get the specfic Item which is (1).
I have also tried using the .index() method but also with that I was faced with a ValueError: 1 is not in the list. Which made me confused as to why the code isn't working.
mylist = [list(map(int, input().split())),
                  list(map(int, input().split())),
                  list(map(int, input().split())),
                  list(map(int, input().split())),
                  list(map(int, input().split())),]
print(mylist)
print(mylist.index(1))

A: Here is one approach to consider:
myList = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]

def index_2d(input_list, value):
    for i, row in enumerate(input_list):
        try:
            return (i, row.index(value))
        except ValueError:
            continue
    # You can also raise ValueError here instead of implicit return (un-comment the next line)
    # raise ValueError(f'{value} is not in the list')

Output:
>>> print(myList)
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]

>>> print(index_2d(myList, 12))
(2, 0)

>>> print(index_2d(myList, 11))
None

Explanation:
We accept the 2d-list and a value we are trying to check. Then use enumerate (to keep track of the index of the main array). We then use index() at each row (list in the main array) to check if the value belongs there, if not (ValueError exception got raised) we simply move to the next row and repeat. But if index() resolves, we return a tuple of the index of the list inside the main list (from the enumerate()) and the index inside the second list or row.


text:
Q: How to hide keyboard automatically in sony xperia using android code? I am using Textview and ImageView display for some things in my layout,I did not
use any EditView in my latout. But whenever I run my application in sony xperia device, I
got keyboard view, How can i hide keyboard, This problem only appear in sony xperia, How can I solve this problem?

A: use android:windowSoftInputMode="stateHidden" for your activity in maifest file.


text:
Q: Siri reading CFBundleName instead of CFBundleDisplayName when using INSendPaymentIntent We are facing some weird case when sending money via Siri, as it doesn't spell the app name defined in CFBundleDisplayName, so it does the one defined in CFBundleName on iOS > 14.0
First let me introduce the scenario to reproduce this.

*

*Have 2+ Apps installed that offers the Send Money functionality via Siri.

*Enable Siri via "Hey Siri" activation and ask to "Send Money"

*When Siri asks you what app do you want to use and spells their name, is using the one defined in CFBundleName, but the name displayed in the screen is the one defined in CFBundleDisplayName

We tried the same scenario on iOS13 and iOS12 and both spells the correct CFBundleDisplayName.
We didn't find any related change to this on iOS14 or Xcode12 changelogs, so not sure if this is a bug or what.
Changing the CFBundleName (which points to $(PRODUCT_NAME) right now) solves the issue, but that's a change that we don't want to do, since could add us some extra problems we don't expect.
Does anyone experienced this issue, and is there another way to fix it that is not changing the CFBundleName?
Thanks


text:
Q: Regular expression for set max width i have a regular expression
 /^(COM|ORG|IN)$/

and this is for validating that particular words,i also want to set the max width is 3 in this regular expression. can anybody please help me

A: Try this:
/^(\w{3}|IN)$/

the first part matches any 3 characters and second part matches IN
I have excluded COM and ORG as they are just example of 3 characters. If you wish to allow only alphabets use
/^([A-Z]{3}|IN)$/

Here is the code:
var regEx = /^([A-Z]{3}|IN)$/

console.log(regEx.test("COM")) // Logs true
console.log(regEx.test("ORG")) // Logs true
console.log(regEx.test("IN")) // Logs true
console.log(regEx.test("IN1")) // Logs false
console.log(regEx.test("XYZW")) // Logs false