text:
Q: PHPUnit - Procedural code needing to be included multiple times I am currently trying to build up a phpunit testsuite to test some ajax code which is written procedurally. I am unable to edit the original code, fooBar.php, because it might cause issues elsewhere. The issue occurs when I am trying to run a php file multiple times with different parameters; the code has a function which throws redeclare exceptions. Below is an example of what I am dealing with.
fooBar.php - php file hit with an ajax call
$foo = $_POST['bar'];

function randomFunctionName(){
    echo "randomFunctionName";
}

if($foo == "fooBar"){
     $jsonResponse = array('success'=>true);
}else{
     $jsonResponse = array('success'=>false);
}

echo json_encode($jsonResponse);

fooBarTest.php - phpunit test file
class fooBarTest extends \PHPUnit\Framework\TestCase
{

   private function _execute() {
       ob_start();
       require 'fooBar.php';
       return ob_get_clean();
   }

   public function testFooBarSuccess(){
       $_POST['bar'] = "fooBar";

       $response = $this->_execute();
       $this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'true') !== false));

   }
   public function testFooBarFailure(){
       $_POST['bar'] = "notFooBar";

       $response = $this->_execute();
       $this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'false') !== false));

   }

So when I run this test, I get the following error
PHP Fatal error:  Cannot redeclare randomFunctionName() (previously declared in.......

The problem is coming from the fact that fooBar.php is technically already there when the second test, testFooBarFailure(), is ran. As you can see though, I need to rerun fooBar.php in order to get a new response.
Is there any way to remove fooBar.php from the php stack/memory so I can run it again as though it was never loaded from the first test? I have tried pulling the second test function into its own test class but when I run the testsuite as a whole, I get the same exact error.

A: So I figured out a way to do what I was looking for. Long story short, I use CURL to hit the ajax file. This allows me to hit the file multiple times within my test without causing any re-declaration issues. Below is an example of my solution for the fooBarTest.php file.
class fooBarTest extends \PHPUnit\Framework\TestCase
{

   public function testFooBarSuccess(){
       $postData = array('bar'=>"fooBar");

       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

       $response = curl_exec($ch);
       curl_close($ch);

       $this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'true') !== false));

   }
   public function testFooBarFailure(){
       $postData = array('bar'=>"notFooBar");

       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

       $response = curl_exec($ch);
       curl_close($ch);

       $this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'false') !== false));

    }
}

A: PHP has built-in function to checking that specific function is defined, it's called function_exists. Example:
if (false === function_exists('randomFunctionName')) {
    function randomFunctionName()
    {
        echo "randomFunctionName";
    }
}

Thanks to this, you can include/require file many times but function will be loaded once.
Second way is just import your fooBar.php once using require_once instead of require (Difference between require, include and require_once?).


text:
Q: SOQL Like Query? I am trying to make a query that will search for accounts with a name similar or exactly matching a field value.
So for example I have "Sales-Force" in the field. There is an account called "Salesforce" or "Sales Force"
My current query
Select Id, Name FROM Account WHERE Name LIKE '%Sales-Force%'

This isn't returning my accounts named "Sales Force" or "Salesforce" in my query editor.
UPDATED * My Apex code
string accountName= record.Name;
    if(accountName.contains('-'))
    {
        accountName = accountName.replace('-', '%');
    }
    if(accountName.contains(' '))
    {
        accountName = accountName.replace(' ', '%');
    }
    accountName= '%' + accountName+ '%';

List<Account> accountLookup = new List<Account>();
accountLookup = [Select Id, Name FROM Account WHERE Name LIKE :accountName];

A: Have you considered:
Select Id, Name FROM Account WHERE Name LIKE '%Sales%Force%'

or:
String likeValue = '%Sales%Force%';

Account[] accounts = [Select Id, Name FROM Account WHERE Name LIKE :likeValue];

PS
Just noticed Oleksandr had posted this and deleted it: please clarify your question.
PPS
You could add some code that tries to generalize the pattern e.g. replaces non-alphabetic characters with a % and puts a % between each character. Or you could consider e.g. a Metaphone approach to the matching.

A: First off, here's the LIKE docs

LIKE  Like    Expression is true if the value in the specified fieldName
  matches the characters of the text string in the specified value. The
  LIKE operator in SOQL and SOSL is similar to the LIKE operator in SQL;
  it provides a mechanism for matching partial text strings and includes
  support for wildcards.
The % and _ wildcards are supported for the LIKE operator.
The % wildcard matches zero or more characters.
The _ wildcard matches exactly one character.
The text string in the specified value must be enclosed in single quotes.
The LIKE operator is supported for string fields only.
The LIKE operator performs a case-insensitive match, unlike the case-sensitive matching in SQL.
The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.
Don't use the backslash character in a search except to escape a special character.

For example, the following query matches Appleton, Apple, and Appl,
  but not Bap

So for your query Select Id, Name FROM Account WHERE Name LIKE '%Sales-Force%', what you're asking for is all accounts with a name that contains 'Salesforce-Force', so that wouldn't match either accounts.
So to capture all of your examples you'd need this query
SELECT Id, Name FROM Account WHERE Name LIKE 'Sales_Force' OR Name LIKE 'SalesForce' which would match 'Sales-Force', 'Sales Force', 'SalesForce', or 'sAlEsFoRcE' (like is case-insensitive)

A: You can't do it. It is not possible to use value of a field in condition expression, as a value.
According to documentation

fieldExpression uses the following syntax:
fieldName comparisonOperator value

A value used to compare with the value in fieldName. You must supply a
  value whose data type matches the field type of the specified field.
  You must supply a native value—other field names or calculations are
  not permitted. If quotes are required (for example, they are not for
  dates and numbers), use single quotes. Double quotes result in an
  error.

update
looks like it is XY problem, and I am sure desired result could be achieved by means of formula fields and other tools. Maybe you can post source of this question?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use union in select clause? I have two tables (created here for example) like:
X1   Y1
a   1
b   2
c   3
d   4

and
X2   Y2
a    5
m    6
n    7
b    4

And I want the output column:
X    Y1   y2
a    1    5
b    2    4
c    3    0
d    4    0
m    0    6
n    0    7

What I tried is:
SELECT (A.X1 UNION B.X1) AS X, A.Y1,B.Y2
FROM A FULL OUTER JOIN B
ON A.X1 = B.X2

(the query mentioned above is just sample).
After executing this query I am getting error message:

Syntax error: near UNION in select clause

Can someone tell me what is wrong here. Is there any other option to get the output table in the mentioned format?

A: union is used to join results one after another. You're attempting to join results side by side (which you already did!). The only thing you're missing is a coalesce call to handle the missing values:
SELECT COALESCE(a.x1, b.x2) AS x,
       COALESCE(a.y1, 0) AS y1,
       COALESCE(b.y2, 0) AS y2
FROM   a
FULL OUTER JOIN b on a.x1 = b.x2

A: You can try COALESCE

The COALESCE function returns the first of its arguments that is not
  null. Null is returned only if all arguments are null.

SELECT COALESCE(A.X1,B.X2) AS X, COALESCE(A.Y1, 0) AS Y1, COALESCE(B.Y2, 0) AS Y2
FROM A FULL OUTER JOIN B
ON A.X1 = B.X2

A: SELECT Coalesce(a.x1,b.x1) AS X, coalesce(a.y1,0) as Y1 coalesce(b.y2,0) as Y2
FROM a
FULL OUTER JOIN
b ON a.x1 = b.x2

You don't need the UNION statement here, the union is used to add a resultset from a select to a resultset from a different select
You just need to use your join here with the correct on statement (which you did correct) and get the x1 or x2 from one of the tables as x1 would be equal to x2 within the same row
EDIT: Added coalesce statements to my query to return value for x if a.x1 does not exist but b.x2 does exist, also added 0 if a field doesn't exist for y1 or y2

A: The error is because UNION is not command that can be used in the list of columns, it is on set level, you can UNION two selects like:
SELECT * FROM table1
UNION
SELECT * FROM table2

they just need to have same columns


text:
Q: Android Loss write permissions on Service I browsed a lot to try and find an answer, I'm trying to download a file through an Android Service,
I do check and grant permissions on MainActivity and also validate that it's been granted.
When I get in Service Class the app just get Permission denied.
Here is the code:
public class MainActivity extends AppCompatActivity  implements EasyPermissions.PermissionCallbacks{

private static final int WRITE_REQUEST_CODE = 300;

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

    final TextView text = findViewById(R.id.text);
    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (text.getText().toString().equals("Started")) {
                text.setText("Stoped");
                stopService(new Intent(MainActivity.this,DownloadService.class));
            } else {
                text.setText("Started");

                startService(new Intent(MainActivity.this,DownloadService.class));
            }
        }
    });

    EasyPermissions.requestPermissions(this, getString(R.string.write_file), WRITE_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
    }

    /*  MARKED CODE
DownloadFile downloadFile;
        downloadFile = new DownloadFile(getApplicationContext());
        downloadFile.execute("<https link>");*/
    }

@Override
public void onBackPressed() {

    moveTaskToBack (true);

    Toast.makeText(getApplicationContext(), "Move to Back", Toast.LENGTH_SHORT).show();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}

@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
    Log.d("app", "Permission has been granted");
    Toast.makeText(getApplicationContext(), "Permission has been granted", Toast.LENGTH_SHORT).show();
}

@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
    Log.d("app", "Permission has been denied");
    Toast.makeText(getApplicationContext(), "Permission has been denied", Toast.LENGTH_SHORT).show();
    }
}

Service Class (only relevant section):
public class DownloadService extends Service {

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

 if (!EasyPermissions.hasPermissions(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    Toast.makeText(getApplicationContext(), "Permission Lost", Toast.LENGTH_SHORT).show();
                                }
                                // download file and get it's locat path
                                String msg = downloadFile.downloadFile(imagePATH);
}

Main Activity do have permission the Service not!
DownloadFile is a simple class.
Some weird behavior, If I do execute MARKD CODE while i change DownloadFile  to be AsyncTask, I do manage to download and store the file. than when I switch back to the original code the Service also can Write files to storage.
What's going on?


text:
Q: relations between degree and dimension I have a stupid question: assume $X \subset P:=\mathbb{P}^{N_1}\times \mathbb{P}^{N_2} $ closed, irreducible, Cohen-Macaulay, not a product of two varieties and non degenerate, meaning that it is not contained in any hyperplane $H\times K$ where $H$ is an hyperplane in the first factor and $K$ an hyperplane in the second. Is there a lower bound depending on $N_1$ and $N_2$ for the degree of $X$ in terms of the dimension of $P$?

A: No - there are plane curves of arbitrarily high degree.  (Take $N_1 = 2, N_2 = 0$.)


text:
Q: How to find the important variable for every prediction in R XGboost I am applying xgboost to the below data set and getting prediction, I am also able to get the most important feature for the over all model, However I would also like to know for every prediction which are the most important features, I am able to use dalex package to find for every prediction the important variables but getting error
Please find below the code
rm(list=ls(all=T))
library("iBreakDown")
library("breakDown")
library("xgboost")
library("DALEX")
library("ingredients")
data(HR_data)
head(HR_data)
table(HR_data$left)
str(HR_data)

label<-HR_data$left
HR_data<-HR_data%>%select(-c(sales,salary,left))

#trian and tes split
n=nrow(HR_data)
train.index = sample(n,floor(0.75*n))
train.data = as.matrix(HR_data[train.index,])
train.label = label[train.index]
test.data = as.matrix(HR_data[-train.index,])
test.label = label[-train.index]

## set the seed to make your partition reproducible

xgb.train = xgb.DMatrix(data=train.data,label=train.label)
xgb.test = xgb.DMatrix(data=test.data,label=test.label)

params = list(
  booster="gbtree",
  eta=0.001,
  max_depth=5,
  gamma=3,
  subsample=0.75,
  colsample_bytree=1,
  objective="binary:logistic",
  eval_metric="auc"
)

xgb.fit=xgb.train(
  params=params,
  data=xgb.train,
  nrounds=10000,
  nthreads=1,
  early_stopping_rounds=10,
  watchlist=list(val1=xgb.train,val2=xgb.test),
  verbose=0
)

xgb.fit

xgb.pred = predict(xgb.fit,test.data,reshape=T)
xgb.pred = as.data.frame(xgb.pred)

### important Variables
xi <- xgb.importance(colnames(xgb.train), model = xgb.fit)

### using train data to find the best attributes of it's prediciton
train_d<-as.data.frame(train.data)
train_l<-as.data.frame(train.label)
colnames(train_l)<-"left"
train_df<-cbind(train_d,train_l)

### exgboost explainer
library("DALEX")

model_martix_train <- model.matrix(train_df$left ~.-1,train_df)
data_train <- xgb.DMatrix(model_martix_train, label = train_df$left)

xgb_model <- xgb.train(param=params, data_train, nrounds = 50)
xgb_model

predict_logit <- function(model, x) {
  raw_x <- predict(model, x)
  exp(raw_x)/(1 + exp(raw_x))
}
logit <- function(x) exp(x)/(1+exp(x))

explainer_xgb <- explain(xgb_model,
                         data = model_martix_train,
                         y = train_df$left,
                         predict_function = predict_logit,
                         link = logit,
                         label = "xgboost")

nobs <- model_martix_train[1:50, , drop = FALSE]
sp_xgb  <- break_down(explainer_xgb, observation = nobs)

I am getting error when using break_down error is
Error in break_down(explainer_xgb, observation = nobs) :
unused argument (observation = nobs)
when I used the below code it is not giving error but when I try to use the same logic for my data set I am getting error.
The below code runs without error
library("iBreakDown")
library("breakDown")
library("xgboost")
library("DALEX")
library("ingredients")
data(HR_data)

model_martix_train <- model.matrix(left ~ . - 1, HR_data)
data_train <- xgb.DMatrix(model_martix_train, label = HR_data$left)
param <- list(max_depth = 2, eta = 1, silent = 1, nthread = 2,
              objective = "binary:logistic", eval_metric = "auc")

HR_xgb_model <- xgb.train(param, data_train, nrounds = 50)

predict_logit <- function(model, x) {
  raw_x <- predict(model, x)
  exp(raw_x)/(1 + exp(raw_x))
}

logit <- function(x) exp(x)/(1+exp(x))

### Explainer from dalex
explainer_xgb <- explain(HR_xgb_model,
                         data = model_martix_train,
                         y = HR_data$left,
                         predict_function = predict_logit,
                         link = logit,
                         label = "xgboost")

### predicitons Plot
nobs <- model_martix_train[1, , drop = FALSE]
sp_xgb  <-break_down(explainer_xgb, nobs)
plot(sp_xgb)

I would appreciate if someone could help me on this also if there is any other way to find best attributes for every prediction, the reason I am looking for some other alternate solution is because I have data frame with more 3 million rows and using dalex would be very time consuming.


text:
Q: Is the sub-level set of a concave function convex? Suppose I have a set defined as follows:
\begin{align*}
S=\{ x: f(x) \le c\}
\end{align*}
where $f(x)$ is continuous  and  concave function defined over some $x \in K$ where $K$ is compact and convex. Note, that $S \subset K$. Is the set $S$ convex or non-convex?
I would really like it to be convex for my purpose but I am not sure.
Here is what I tried. Let $x_1,x_2 \in S$ then
\begin{align*}
f(\alpha x_1+(1-\alpha)x_2) \ge \alpha f(x_1)+(1-\alpha) f(x_2)
\end{align*}
but how to proceed next. The above doesn't tell me anything.
Would be grateful, for any input you can have.


text:
Q: How to remove a part of a string which will always be at the last? I made a function that removes the last part of the string which will always start from _ and get the integer, but all I get is the text part and not the integer
How can this be achieved?

function splitLast(arg) {
  if (arg.includes(".") && arg.includes("_")) {
    return parseFloat(arg.split("_").pop())
  } else if (arg.includes(".") != true && arg.includes("_")) {
    return parseInt(+arg.split("_").pop())
  } else {
    throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
  }
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')

A: UPD: A better solution
You can use parseFloat() function without additional checks and string parsing (it will do it all for you):

function splitLast(arg) {
  if (isNaN(arg.trim()[0])) {
    throw new Error('argument is not valid')
  }

  return parseFloat(arg)
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
console.log(splitLast("a22.1_no"), 'should throw')
console.log(splitLast("  a22.1_no"), 'should throw')

isNaN() check is needed because parseFloat(string) returns:

*

*A floating-point number parsed from the given string (which is exactly what you need)

*NaN when the first non-whitespace character cannot be converted to a number (which is an edge-case but we should know about it)

Old solution:
Probably, you have to use the shift() method instead of pop().

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

function splitLast(arg) {
  if (arg.includes(".") && arg.includes("_")) {
    return parseFloat(arg.split("_").shift())
  } else if (arg.includes(".") != true && arg.includes("_")) {
    return parseInt(arg.split("_").shift())
  } else {
    throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
  }
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')

A: You could use a regexp and .replace:

function splitLast(value) {
  return value.replace(/_.*$/, '');
}

console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')

A: You can use this to remove text from string and only numbers with underscore remains.
 var ret = "22.1_no";
    var str = ret.replace(/[^0-9\.]+/g, "");
    console.log("_"+str);


text:
Q: Search for a value in a column, then modify all the cells contain this value by adding a number to the end I am fairly new to VBA.
I need to create a macro that searches the entire column K for keywords " C Box", for any cell in this column that contains these keywords, I need to add a numerical value to the end of the text (this numerical is always in the same row as the cell that contains the keywords, but in column L)
for example:
              K                       L
Row 43      C Box                    14"
Row 55      C Box                    28"

after run the macro, the text in column K becomes C Box 14" on row 43, and C Box 28" on row 55.
Any help would be greatly appreciated !


text:
Q: How to update a variable from a text file in python3 So, let's say that I got a shell script that generates a v.py on the output that contains
v = some-float

And I'm accessing it in the main.py script via from v import v
But later the main Script toggles generation process again and the variable in v.py gets updated, but the variable v is not updating for the main script.
To make main script work I need to update the variable from v.py while script is running
I've tried importlib.reload(v) - didn't work
I'm still new to python and don't understand it completely

A: Presuming you are using python 3.*, v needs to be a module, so the way you import it changes to example below.
import v
import importlib

print(v.v)

with open('v.py', 'w') as f:
    f.write('v = 20.0')

importlib.reload(v)
print(v.v)

Also note the document of importlib
"When a module is reloaded, its dictionary (containing the module's global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem."
Though our minimal example works, this is something to bear in mind for more complicated cases.


text:
Q: nginx config still serving default home page after root has been set map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
server{
    server_name sample.com;
    listen 80;
    location = / {
        root /root_path;
        index index.html;
    }

    location / {
        # root /root_path;
        # index index.html;

        # proxy_pass http://127.0.0.1:5200;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # proxy_set_header Host $host;  # pass the host header -                                     http://wiki.nginx.org/HttpProxyModule#proxy_pass

        # proxy_http_version 1.1;  # recommended with keepalive connections - http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_http_version

        # WebSocket proxying - from http://nginx.org/en/docs/http/websocket.html
        # proxy_set_header Upgrade $http_upgrade;
        # proxy_set_header Connection $connection_upgrade;
    }
}

This is only config file in "/etc/nginx/site-enable", but still its load nginx default page. How is this possible? If default root is not defined within server block but only within location blocks does root defaults to nginx default root directory?

A: I found issue and solution for my question.

"It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location.
    For example, with the following configuration:

location = / {
    index index.html;
}

location / {
    ...
}

a "/" request will actually be processed in the second location as
  "/index.html". "

I Quote this from
> http://nginx.org/en/docs/http/ngx_http_index_module.html
In my case,i'm requesting to load index.html in first location block.
location = / { }

but nginx redirect and catch it from second location block.
location / { }

but index.html file is commented there. so it'll load the default nginx page.


text:
Q: "any other" + singular / plural Which one is correct, and could you please tell me why?

She is more popular than any other singers/singer in the USA.

Thank you.

A:
She is more popular than any other singer in the USA.

"Any other" can be used with both singular and plural nouns, but in this case, you have to use singular, "singer", as the use of "more popular than" and "any other" suggests the use of singular noun.
E.g.

She is more popular than him

A: Any other implies 'any one other'. There is no individual singer in the USA more popular than she is.
If you wish to use the plural, you need to leave out any.

She is more popular than [all the] other singers in the USA.


text:
Q: Função Jquery.click() com problemas para executar Segundo o meu código abaixo, quando clico no botão Ver senha na web está fazendo um GET quando na verdade quero apenas que mostre o campo senha. O que pode estar de errado?

$('.passwordShowLabel').hide();
$('#passwordShow').hide();
$('#password').removeAttr("required");
$('#confirmPassword').removeAttr("required");

$('#btnPasswordEditDesistir').hide();
var checkbox = $('#chkPassword');
var checked = checkbox.prop("checked");

$('#btnPasswordEdit').click(function() {
  $(this).hide();
  $('#btnPasswordEditDesistir').show("slow");
  $('#passwordSection').show("slow");
  $('#password').attr('required', 'true');
  $('#confirmPassword').attr('required', 'true');
});

$('#btnPasswordEditDesistir').click(function() {
  $(this).hide();
  $('#btnPasswordEdit').show("slow");
  $('#passwordSection').hide("slow");
  $('#password').removeAttr("required");
  $('#confirmPassword').removeAttr("required");
});

    <button id="btnPasswordEdit" class="btn btn-info">
              Editar
             </button>

    <button id="btnPasswordEditDesistir" class="btn btn-secondary">
              Desistir
             </button>

    <button id="btnPasswordView" class="btn btn-info">
              Ver Senha
             </button>

  Senha atual

    <input title="" id="passwordShow" name="object.passwordRoundTripV1" type="text" class="form-control  readonly " placeholder="" value="12345678a" style="display: none;" readonly="readonly">

      Senha

        <input title="" id="password" name="password" type="password" class="form-control" placeholder="" value="">

      Confirmar senha

        <input title="" id="confirmPassword" name="confirmPassword" type="password" class="form-control  " placeholder="" value="">

A: Caso seu botão esteja dentro de uma tag <form> será necessário cancelar o evento para que botão não envie o formulário. Assim:
De:
$('#btnPasswordEdit').click(function() {

Para:
$('#btnPasswordEdit').click(function(e) {
  e.preventDefault();


text:
Q: Set the mnesia directory with rebar running eunit test I am using rebar, and I need to set the mnesia directory for my Erlang eunit tests (which you can usually do by doing erl -mnesia dir DIRECTORY at the cmdline). How do I run eunit tests with a special mnesia dir with rebar?
I do not think that the erl_opts section of the rebar.conf file will help because the mnesia directory is an emulator argument and I don't think it can be set through erlang. Also, I think these are options for when rebar compiles your code, not when it runs eunit tests. However, even if it did work, it will not work for me because I need to be able to set the directory dynamically (I am writing a Makefile where different targets have different db dirs).

A: What you actually are setting for Mnesia using erl -mnesia dir DIR is setting the environment variable for Mnesia, this can be set in the application resource file, as a switch from the command line as you have done or using a configuration file. The order in order of precedence is command line, config file and last the application resource file. An applications environment variables can also be set dynamically using application:set_env/3,4, this may not work in your case but it useful in many cases to get a particular (or even peculiar :-) ) setup for a test by setting the environment variables in the setup part of an eunit fixture.


text:
Q: How do I reject a snapshot during recovery? I'm currently attempting to implement snapshotting to an event sourced application using Akka Persistence. The strategy that I'm attempting to take here is:

*

*Save a snapshot every X events

*Maintain a schemaVersion property on my state object. The purpose of the schemaVersion is to allow me to evolve/migrate my state if I change the way I'm replying my events.

*During recovery, if I receive a SnapshotOffer whose state.schemaVersion is less than my current schema version, discard that snapshot and replay events from the beginning

*Delete all snapshots earlier than my latest valid snapshot after recovery complete

However, I'm finding that I'm not able to discard snapshots during recovery. If there is a snapshot in the snapshot store, earlier events will not be offered to me.
I'm having a hard time reading up on how this should be handled. What's the proper approach here?

A: There is one thing I don't get, what is the state object? And from where it's getting the schemaVersion? Isn't the state exactly the state of your actor that is reconstructed from the snapshot / events?
In any case, you can't delete and/or skip a snapshot once it's offered. Instead, you can do the following:

*

*add a config drop-snapshot (defaults to false)

*on preStart

override def preStart(): Unit = {
   super.preStart()
   if (dropSnapshot) deleteSnapshots(SnapshotSelectionCriteria.Latest)
}

*override recovery method

override def recovery = {
   if (dropSnapshot) {
     Recovery(fromSnapshot = SnapshotSelectionCriteria.None)
   } else {
     Recovery(fromSnapshot = SnapshotSelectionCriteria.Latest)
   }
}


text:
Q: How to use NER model fine tuned using hugging face transformers with spark nlp on databricks I needed to train (fine tune) NER token classifier to recognize our custom tokens.
The easiest way to do that I found was:
Token Classification with W-NUT Emerging Entities

But now I encountered a problem - the plan was to follow:
HuggingFace in Spark NLP - BERT Sentence.ipynb ,
but when I try:
model.save_pretrained(<path on DBFS>)

I get file write error. As far as I understand this is because tranformers/keras won't work on distributed file systems like DBFS
Is there any walkaround for this?
I cannot move training away from databricks because I'm using data (entities) from the database to create training file
PS. Maybe I can do the same using only spark nlp? How- prefarably using same "tag only" format?

A: You should save the model to the local file system first and then copy it to DBFS:
from distutils.dir_util import copy_tree

local_path = "./tmp/model"
dbfs_path = "/dbfs/tmp/model"

model.save_pretrained(local_path)
copy_tree(local_path, dbfs_path)


text: Q: Which design pattern should follow while developing react native application? I am newbie to react native.I would like to build an application using react native,but before that I want to know which design pattern/framework does react native support?


text:
Q: sql 2005 force table rename that has dependencies How do you force a rename???
Rename failed for Table 'dbo.x.  (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.2531.0+((Katmai_PCU_Main).090329-1045+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Rename+Table&LinkId=20476

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

Object '[dbo].[x]' cannot be renamed because the object participates in enforced dependencies. (Microsoft SQL Server, Error: 15336)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.4035&EvtSrc=MSSQLServer&EvtID=15336&LinkId=20476

A: Find the "enforced dependencies", then remove or disable them.
By "enforced dependencies", it means Schema binding, so you'll have to look specifically for that.
Here's a query to look for schema binding references to your object:
select o.name as ObjName, r.name as ReferencedObj
from sys.sql_dependencies d
join sys.objects o on o.object_id=d.object_id
join sys.objects r on r.object_id=d.referenced_major_id
where d.class=1
AND r.name = @YourObjectName

As I noted in the comments, there is no way to FORCE-ibly override Schema Binding.  When you use Schema Binding, you are explicitly saying "Do not let me or anyone else override this."  The only way around Schema Binding is to undo it, and that's intentional.

A: I had the same issue , my problem was that i has a COMPUTED FIELD using the column i was trying to rename.
by running the query from the selected answer i was able to tell that had enforced dependencies, but i was not able to see exactly what was the problem

A: Try this:
/*
    Example 1: Rename a table dbo.MyTable -> dbo.YourTable
    EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=N'dbo', @EntityName=N'MyTable', @Debug=1;
    EXEC sp_rename N'dbo.MyTable', N'YourTable', N'OBJECT'

    Example 2: Rename a column dbo.MyTable.MyColumn -> dbo.MyTable.YourColumn
    EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=N'dbo', @EntityName=N'MyTable', @ColumnName=N'MyColumn' @Debug=1;
    EXEC sp_rename N'dbo.MyTable.MyColumn', N'YourColumn', N'COLUMN'

*/
CREATE Procedure dbo.USP_DROP_ENFORCED_DEPENDENCIES
(
    @SchemaName sysname = 'dbo',
    @EntityName sysname,
    @ColumnName sysname = NULL,
    @Debug      bit = 0
)
AS
BEGIN
    SET NOCOUNT ON;
    SET ROWCOUNT 0;

    DECLARE @ReferencingEntitySchema sysname, @ReferencingEntityName sysname, @ReferencingEntityType nvarchar(8), @SqlScript nvarchar(512);

    DECLARE ReferencingEntitiesCursor CURSOR LOCAL FORWARD_ONLY
    FOR
        SELECT OBJECT_SCHEMA_NAME(dep.referencing_id) AS [schema]
              ,referencing_entity.name
              ,CASE referencing_entity.type
                   WHEN 'V' THEN N'VIEW'
                   ELSE /*IF, FN, TF*/ N'FUNCTION'
               END as [type]
        FROM sys.sql_expression_dependencies AS dep
            INNER JOIN sys.objects AS referencing_entity
                ON dep.referencing_id = referencing_entity.object_id
        WHERE dep.referenced_entity_name = @EntityName
              AND dep.referenced_schema_name = @SchemaName
              AND is_schema_bound_reference = 1
              AND ((@ColumnName IS NULL AND dep.referenced_minor_id = 0) OR COL_NAME(dep.referenced_id, dep.referenced_minor_id) = @ColumnName)
    OPEN ReferencingEntitiesCursor

    FETCH NEXT FROM ReferencingEntitiesCursor
    INTO @ReferencingEntitySchema, @ReferencingEntityName, @ReferencingEntityType;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=@ReferencingEntitySchema, @EntityName=@ReferencingEntityName, @Debug=@Debug;
        --The goal is to produce the following script:
        /*
        DROP FUNCTION dbo.UFN_SOME_FUNCTION;
        OR
        DROP VIEW dbo.UFN_SOME_VIEW;
        */
        SET @SqlScript = N'DROP ' + @ReferencingEntityType + N' ' + @ReferencingEntitySchema + '.' + @ReferencingEntityName;
        IF(@Debug = 1)
            RAISERROR (@SqlScript, 0/*severity*/, 0/*state*/) WITH NOWAIT;
        EXEC (@SqlScript);

        FETCH NEXT FROM ReferencingEntitiesCursor
        INTO @ReferencingEntitySchema, @ReferencingEntityName, @ReferencingEntityType;
    END

    CLOSE ReferencingEntitiesCursor;
    DEALLOCATE ReferencingEntitiesCursor;
END
GO

A: In the SQL Server Object Browser, right-click on the table with the issue and select View Dependencies. Next in the view listed, Right-click (view) and select SCRIPT to CREATE VIEW in New SQL Query Editor window, then remove WITH SCHEMABINDING from the CREATE VIEW t-sql script and run the revised CREATE VIEW t-sql. This unlinks the schema dependency from the table. I was able to recreate the table at this point (DROP, RENAME, etc).

Note:
Schema binding can occur on functions and other objects in your db.
  Use of View Dependencies on the object throwing the error is essential
  to fix the issue.
BTW:
I originally added schema binding to enable view indexing. Keeping a
  good index on the underlying table(s) may mitigate the performance hit
  of not having one on the view.

*

*View Dependencies

*More on Schema Binding

A: I had an issue like this. I dropped constraints on this DB object, renamed the DB object then recreated these constraints. This solved my problem.

A: I used this script to get dependent view with schemabingings:
select distinct o.name, o.type from sys.sql_expression_dependencies dep inner join sys.objects o on dep.referencing_id=o.object_id where referenced_id = OBJECT_ID(<your dependency owner object>) and o.type = 'V'


text:
Q: Turn Pandas muti-Index into columns I have a similar dataframe:
 action_type            value
    0   0   link_click          1
        1   mobile_app_install  5
        2   video_view          181
        3   omni_view_content   2
    1   0   post_reaction       32
        1   link_click          124
        2   mobile_app_install  190
        3   video_view          6162
        4   omni_custom         2420
        5   omni_activate_app   4525
    2   0   comment             1
        1   link_click          53
        2   post_reaction       23
        3   video_view          2246
        4   mobile_app_install  87
        5   omni_view_content   24
        6   post_engagement     2323
        7   page_engagement     2323

I want to transpose so:

A: It looks like you can try:
(df.set_index('action_type', append=True)
   .reset_index(level=1, drop=True)['value']
   .unstack('action_type')
)


text:
Q: Enforcing an audio sampling rate in iOS I have an app that is using the RemoteIO Audio Unit to create sounds. However, due to latency and computational issues, the sampling rate of this system cannot be higher than 8 kHz. I use the following line to set the sampling rate.
AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareSampleRate,propSize,&hwSampleRate)

However, on certain runs I get back a sampling rate of 44.1 kHz. In this case, my app appears to not be working since it cannot handle the computations at that sampling rate. What is my best option to enforce the sampling rate to be 8 kHz? Quitting and opening the app again works but makes for bad UX.

A: As hotpaw2 noted, audio is a shared resource on iOS. You can't get exclusive access to the hardware. Calling AudioSessionSetProperty/kAudioSessionProperty_PreferredHardwareSampleRate sets the preferred hardware sample rate. As you note, you might end up with the hardware running at a different rate, that doesn't mean that your app can't run at 8kHz.
If you configure the RemoteIO format correctly then RemoteIO will perform the output sample rate conversion for you. The hardware will run at 44.1kHz but your application will output at 8kHz.
You can read about various ways to achieve this by searching for "sample rate" in this documentation:
http://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/AudioUnitHostingGuide_iOS/ConstructingAudioUnitApps/ConstructingAudioUnitApps.html
One option (as discussed in the docs) would be to set up a mixer with the correct output sample rate, then attach your render callback to the input of the mixer.


text:
Q: "undefined variable" error message in database form submission I have built a submit form my website. The information entered into the form gets stored in a database, and the photo gets stored in a folder on a server, and a link the image is stored in the database.
I based my code off of an example I have from class that works perfectly. However, when the form loads I get the following message

Notice: Undefined variable: Name in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: Photo in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: Bio in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: City in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: State in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: Zipcode in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: Genre in C:\HTML\mgertenbach\BAND\submitband.php on line 28
Notice: Undefined variable: Link in C:\HTML\mgertenbach\BAND\submitband.php on line 28

Nothing I've tried has been able to make the page work and I cannot figure out the issue with my code.
Thank You!
$dbc=mysql_connect('localhost', 'mgertenbach', 'mollyr');
mysql_select_db('mgertenbach', $dbc);

$problem = FALSE;
if (!empty($_POST['bandname']) && !empty($_POST['bandbio']) && !empty($_POST['bandcity']) && !empty($_POST['bandstate']) && !empty($_POST['bandzipcode']) && !empty($_POST['bandgenre']) && !empty($_POST['bandlink'])) {
    $Name = trim(strip_tags($_POST['bandname']));
    $Bio = trim(strip_tags($_POST['bandbio']));
    $City = trim(strip_tags($_POST['bandcity']));
    $State = trim(strip_tags($_POST['bandstate']));
    $Zipcode = trim(strip_tags($_POST['bandzipcode']));
    $Genre = trim(strip_tags($_POST['bandgenre']));
    $Link = trim(strip_tags($_POST['bandlink']));
}else {
if (!$problem) {
    $query = "INSERT INTO band_information (Name, Photo, Bio, City, State, Zipcode, Genre, Link)
            VALUES ('$Name', '$Photo', '$Bio', '$City', '$State', '$Zipcode', '$Genre', '$Link');";
    if($_SERVER['REQUEST_METHOD']=='POST'){
        if(move_uploaded_file($_FILES['thefile']['tmp_name'], "C:\\HTML\\mgertenbach\\BAND\\photos\\{$_FILES['thefile']['name']}") && @mysql_query($query, $dbc)){
            print '
Thanks for submitting your band!
';
        } else {
            print '
Could not submit band because:
' .
            mysql_error($dbc) . '
';
        }
    }
else {

?>

Please fill out the following information.

    <form action="submitband.php" method="post">
        <fieldset><legend>Who Are You?</legend>
            Band Name: <input type="text" id="bandname" name="bandname" size="10"/>

            Upload Photo*: <input type="file" id="bandphoto" name="bandphoto"/>

   *image must be a square file

            Enter a short bio:
<textarea id="bandbio" name="bandbio" cols="40" rows="10"></textarea>
        </fieldset>

        <fieldset><legend>Where Are You From?</legend>
            City: <input type="text" id="bandbio" name="bandcity" size="10"/>

            State:
                <select id="bandstate" name="bandstate">
                        <option value=""> </option>
                        <option value="AL">Alabama</option>
                        <option value="AK">Alaska</option>
                        <option value="AZ">Arizona</option>
                        <option value="AR">Arkansas</option>
                        <option value="CA">California</option>
                        <option value="CO">Colorado</option>
                        <option value="CT">Connecticut</option>
                        <option value="DE">Delaware</option>
                        <option value="DC">District Of Columbia</option>
                        <option value="FL">Florida</option>
                        <option value="GA">Georgia</option>
                        <option value="HI">Hawaii</option>
                        <option value="ID">Idaho</option>
                        <option value="IL">Illinois</option>
                        <option value="IN">Indiana</option>
                        <option value="IA">Iowa</option>
                        <option value="KS">Kansas</option>
                        <option value="KY">Kentucky</option>
                        <option value="LA">Louisiana</option>
                        <option value="ME">Maine</option>
                        <option value="MD">Maryland</option>
                        <option value="MA">Massachusetts</option>
                        <option value="MI">Michigan</option>
                        <option value="MN">Minnesota</option>
                        <option value="MS">Mississippi</option>
                        <option value="MO">Missouri</option>
                        <option value="MT">Montana</option>
                        <option value="NE">Nebraska</option>
                        <option value="NV">Nevada</option>
                        <option value="NH">New Hampshire</option>
                        <option value="NJ">New Jersey</option>
                        <option value="NM">New Mexico</option>
                        <option value="NY">New York</option>
                        <option value="NC">North Carolina</option>
                        <option value="ND">North Dakota</option>
                        <option value="OH">Ohio</option>
                        <option value="OK">Oklahoma</option>
                        <option value="OR">Oregon</option>
                        <option value="PA">Pennsylvania</option>
                        <option value="RI">Rhode Island</option>
                        <option value="SC">South Carolina</option>
                        <option value="SD">South Dakota</option>
                        <option value="TN">Tennessee</option>
                        <option value="TX">Texas</option>
                        <option value="UT">Utah</option>
                        <option value="VT">Vermont</option>
                        <option value="VA">Virginia</option>
                        <option value="WA">Washington</option>
                        <option value="WV">West Virginia</option>
                        <option value="WI">Wisconsin</option>
                        <option value="WY">Wyoming</option>
                    </select>

            Zipcode: <input type="text" id="bandzipcode" name="bandzipcode" size="10"/>
        </fieldset>

        <fieldset><legend>What's Your Music Like?</legend>
            Genre:
                <select id="bandgenre" name="bandgenre">
                        <option value="country">Country</option>
                        <option value="electronic">Electronic</option>
                        <option value="folk">Folk</option>
                        <option value="indie">Indie</option>
                        <option value="punk">Punk</option>
                        <option value="rock">Rock</option>
                </select>

            Share a link to where we can hear it: <input type="text" id="bandlink" name="bandlink" size="40"/>
        </fieldset>

        <input type="submit" value="submit"/>
    </form>
<?php
    }
}
}
?>

A: You're testing for the presence of various $_POST variables, and if you find them all you set some local variables against them.
If you don't find them all you go on to try and write the information to the database.
Look long and hard at how your if...then...else is supposed to work.
Side notes:

*

*mysql_*() functions are deprecated. Don't use them. Use mysqli_*() or PDO instead.

*You're using trim(strip_tags()) as some form of sanitization. This is nowhere near good enough. You should use mysql_real_escape_string() (for mysql), or consider moving to prepared statements.


text:
Q: Button "Click" issue with Rails/Capybara/Webkit (tests pass in Selenium) I'm working on a Rails App and we've started using capybara for our functional tests. Our tech lead has had us writing tests and using Selenium, but then wants to switch to webkit for final testing prior to a deploy.
I've written a set of functional tests that mimic a user clicking through a tree menu, clicking a button to open a modal, clicking a few buttons within the modal (eventually opening a form), and then submitting the button.
These tests pass with flying colors in selenium. Firefox pops open and it whips through the complete test suite.
Switch over to webkit, and there is a consistent point at which the tests fail. When the modal is open, and it attempts to "click" a button to switch from a "Interaction History Form" to a "New Interaction Form"
The following is a list of the various command attempts I've done at "clicking" the New Interaction Button.
With selenium, this is simple and works:
click_button('New Interaction')
and some of these work in selenium, some don't, but none of them work with WebKit.
# page.execute_script %Q{ $('.btn.btn-default.toggle-interaction').css('display, inline-block'); }
# page.execute_script %Q{ $('.fa.fa-plus').click(); }
# page.find('.btn.btn-default.toggle-interaction').click
# within('#interaction-history') { find_button('New Interaction').click }
click_button('New Interaction')
# find_button('New Interaction').trigger('click')
# within(".btn.toggle-interaction") do
#   click_on("New Interaction")
# end
# find('.btn.toggle-interaction').trigger('click')
# find_button('New Interaction').click
# within('.insight-wrapper') { find_button('New Interaction').click }
We decided to try and use the capybara-screenshot gem, so that we could get a snapshot of the HTML and the "rendered" page during headless test failure.
I don't have a good photo editing app so I can't scrub out the protected info to post a screenshot, but in the saved snapshots (and saved html files), the images look right.
One idiosyncrasy in the screenshots is the location of the mouse cursor in the screenshot. Sometimes it's on the button it attempted to click, and other's it isn't.
One other idea we entertained is the idea that it could be a timing issue, and that it's trying to click the button before it has been successfully rendered. To mitigate that we added a pause method that forced the tests to wait. That didn't resolve the issue.
We looked at switching to a headless selenium using poltergeist/phantomJS, but a lot of the comments on that route seem to indicate a higher quantity of "random JS errors" than with webkit. Would there be an alternative headless selenium solution that could be worth investigating?
Thank you for your time and help,
Alex


text:
Q: asp button created using c# isn't showing I created an asp:Button in MyAdoHelperSQL.cs which is supposed to appear in adminRiddles.aspx, but this button just isn't showing up. If I open the "Inspect" option while running the code in Google Chrome, I can see that this button does exist in the code, but it isn't showing up.
I also created in the adminRiddles.aspx another button with the exact same code (just for checking), and this one is visible.
What's the problem?  How can I fix it?
code:
MyAdoHelperSQL.cs
string printStr = "

";
printStr += "
  <asp:Button id='add"+idNum+ "' style='float:right; display:block;' runat='server' Text='confirm' Width='70px' OnClick='add_Click'></asp:button>

";
return printStr;

adminRiddles.aspx uses a c# function to call the MyAdoHelperSQL.cs above and prints the printstr string into a form.
 This is the code of the working button:
    <form runat="server">

        <asp:Button id='Button2' style='float:right; display:block;' runat='server' Text='confirm' Width='70px' OnClick='add_Click'></asp:button>

    </form>

Thanks!

A: You can't inject an asp control like that as raw text, this would work with raw HTML but not with a control the server side needs to know about.
The best approach would be to add this control dynamically as an actual control:
adminRiddles.aspx: Give the table row and td an ID and set to runat="server"

adminRiddles.aspx.cs: Add the control in code
Button addButton = new Button();
addButton.ID = "add" + idNum;
addButton.Text = "confirm";
addButton.Click += add_Click;
riddlestd.Controls.Add(addButton);

If you have multiple rows you may need to take this a stage further and dyamically add both table rows and their content.


text:
Q: C# OpenXML: Only getting first hyperlink in file in all files except for the last one I've been assigned with writing an application that can go into a directory, find files of a certain type, get any hyperlinks in the file and record them. So far, it's been going smooth. However, for some reason I I'm having an issue with only getting one of the two links in the file. Both links are to the same url. It just seems to ignore the second one of the first two files, but the third one is just fine.
        string pathtofolder = "C:\\Users\\Icmolreulf\\source\\repos\\FileSearch\\FileSearch\\powershelltesting";

        string[] files = System.IO.Directory.GetFiles(pathtofolder, "*.docx");
        Console.WriteLine(files.Length);

        for (int i = 0; i < files.Length; i++)
        {
            WordprocessingDocument word = WordprocessingDocument.Open(files[i], true);
            IEnumerable<HyperlinkRelationship>  link = from x in word.MainDocumentPart.HyperlinkRelationships where (x.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") select x;
            foreach (HyperlinkRelationship l in link)
            {
                if (isValidURL(l.Uri.ToString()))
                {
                    Console.WriteLine(l.Uri.ToString());
                }
            }
        }
    static bool isValidURL(string uriName)
    {
        Uri uriResult;
        bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
            && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

        return result;
    }

I'm at a loss for what the issue could be. The url I expect to find is the same one for all the files: http://burymewithmymoney.com/. I have ensured it is in all of them. I have also tried adding another .docx file to the directory, and it works, but it also ignores that file too. I'd really appreciate any help I can get.

A: The issue was with the files I was reading from. Code works fine. Sorry for taking up your time. Have a nice rest of your day.


text:
Q: Recover corrupted java script in visual studio 2013 I am working on ASP.net project. In evening while leaving the company I close the solution, at that time the code was perfect. But today when I open the solution the javascript was corrupted as in image:

I searched on google in lots of links. But I find solution in http://www.samnoble.co.uk/2014/11/30/visual-studio-crashes-and-a-corrupted-cs-file/ but I cant recover from this steps.
Anybody has idea regarding this?

A: Who ever runs in this problem:
I had the same issue and nothing worked for me, chrome cache recover, VS backup was not there looke in AppData folder... nothing!!
Remove the corrupted file, then remove it from windows recycling.
Install a program named Recuva. after this you search for files to recover. If you find your file, recover it.
This was the only thing that worked for me!!!


text:
Q: Create a counting variable which I can use to group my unemployment data in R I have data as below where i created the variable "B" with the function:
index <- which(Count$unemploymentduration ==1)
Count$B[index]<-1:length(index)

ID unemployment B
1    1          1
1    2          NA
1    3          NA
1    4          NA
2    1          2
2    2          NA
2    0          NA
2    1          3
2    2          NA
2    3          NA
2    4          NA
2    5          NA

And i want my data in this way and have no real idea how to get it like this.
Thought of an "if-function" but never used one in R.
ID unemployment B
1    1          1
1    2          1
1    3          1
1    4          1
2    1          2
2    2          2
2    0          2
2    1          3
2    2          3
2    3          3
2    4          3
2    5          3

Could someone help me out?

A: We can use na.locf from library(zoo)
library(zoo)
Count$B <- na.locf(Count$B)

But, this can be created directly without using an 'index'
Count$B <- cumsum(Count$unemployment==1)


text:
Q: vue.js - setup reactivity at runtime If have a situation where I want to setup my 'reactivity' programatically, at run time.
I want a function like:  dependsOn(dataValName, someOtherDataVal)  where if someOtherDataVal changes, then dataValName is updated.
  e.g.  dependsOn('a', 'b')
        if the value of b changes, then a is re-displayed/updated.
Does such a function exist?

A: Your question is vague, but what you probably need is a computed property. Vue will automatically detect the dependencies of computed properties. For example, there is no need to be explicit here:
new Vue({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
    }
  },
  computed: {
    fullName() {
      return `${ firstName } ${ lastName }`;
    }
  }
})

Any time firstName or lastName changes, the computed property fullName will also be re-evaluated.

A: Sounds like you're talking about watchers. For example
data: () => ({
  dataValName: 'a',
  someOtherDataVal: 'b'
}),
watch: {
  someOtherDataVal (newValue) {
    this.dataValName = 'c' // or whatever
  }
}

Keep in mind, computed properties are almost always a better option.


text:
Q: How to convert number 1 to a Boolean in python I have seen similar questions asked, but none have answered my question. I am relatively new to python, and have no idea what i'm doing.

A: Only the following values will return False when passed as a parameter to bool()

*

*None

*False

*Zero of any numeric type. For example, 0, 0.0, 0j

*Empty sequence. For example, (), [], ''.

*Empty mapping. For example, {}

*objects of Classes which has bool() or len() method which returns 0 or False

Everything else returns True
Source1
Source2

A: Use:
>>> bool(1)
True
>>> bool(0)
False
>>> int(bool(1))
1
>>> int(bool(0))
0

Can convert back too.
Or a clever hack that could be quicker would be:
>>> not not 1
True
>>> not not 0
False
>>>

Converting back:
>>> int(not not 1)
1
>>> int(not not 0)
0
>>>

A: Unless you don't want to explicitly use Boolean type variable you don't need to. Python accepts it as True in many expression:
print(True == 1)
print(False == 0)

Out:
True
True

In other cases you can use bool(1) of course.
print(bool(1))
print(bool(0))

Out:
True
False

A: Very simple:
bool(1)

Here are a few scenarios, to show:
print(bool(1))

Will return: True
print(bool(0))

Will return: False

A: To convert 1 to boolean type:
print(bool(1))

Which returns True.


text:
Q: Git pull resolving conflict, remote is one aheady I have introduced a conflict within my git repository local / remote.  Here is what I did, both my local and remote were synced, but then I edited the readme file from the Bitbucket GUI causing a new commit, without thinking about it, I then edited my local repository adding ton of code, now I can't push to the remote.  Sadly I have had this issue before and worked around it in a very inefficient way.  Is there a simple efficient way to resolve this, ensuring I don't lose my local changes?  The readme changes I made through the GUI I really don't give a darn about.
Thanks!

A: You can either:

*

*rebase your work on top of the upstream branch:
(It changes your local history, but only for the commit or commits that you didn't pushed yet, so it is ok)
git pull --rebase
git push

*or simply force the push (loosing the change on the readme, unless you copy said change locally first)
git push --force

A: You only need to
git fetch
git merge origin/master

Then you can push again


text:
Q: dask kubernetes aks (azure) virtual nodes Using the code bellow it is possible to create a dask kubernetes cluster in azure aks.
It uses a remote scheduler (dask.config.set({"kubernetes.scheduler-service-type": "LoadBalancer"})) and works perfectly.
To use virtual nodes, uncomment the line extra_pod_config=virtual_config (which follows this official example).
It doesn't work, with the following error:
ACI does not support providing args without specifying the command. Please supply both command and args to the pod spec.
This is tied to passing containers: args: [dask-scheduler]
Which containers: command:  should I supply to fix this issue?
Thank you
import dask
from dask.distributed import Client
from dask_kubernetes import KubeCluster, KubeConfig, make_pod_spec

image = "daskdev/dask"
cluster = "aks-cluster1"
dask.config.set({"kubernetes.scheduler-service-type": "LoadBalancer"})
dask.config.set({"distributed.comm.timeouts.connect": 180})
virtual_config = {
    "nodeSelector": {
        "kubernetes.io/role": "agent",
        "beta.kubernetes.io/os": "linux",
        "type": "virtual-kubelet",
    },
    "tolerations": [
        {"key": "virtual-kubelet.io/provider", "operator": "Exists"},
    ],
}

pod_spec = make_pod_spec(
    image=image,
    # extra_pod_config=virtual_config,
    memory_limit="2G",
    memory_request="2G",
    cpu_limit=1,
    cpu_request=1,
    threads_per_worker=1,  # same as cpu
)

# az aks get-credentials --name aks-cluster1 --resource-group resource_group1
# cp ~/.kube/config ./aksconfig.yaml
auth = KubeConfig(config_file="./aksconfig.yaml", context=cluster,)
cluster = KubeCluster(
    pod_spec, auth=auth, deploy_mode="remote", scheduler_service_wait_timeout=180
)
client = Client(cluster)

A: the reason comes from this virtual kubelet protection: in the pod configuration, dask uses args to start a scheduler or worker, but no command is supplied.
So I explicitly added the entrypoint command command_entrypoint_explicit and it works: pods are created sucessfully.
Second problem: network names resolution. workers fail to connect to the scheduler by network name: tcp://{name}.{namespace}:{port}
Although tcp://{name}.{namespace}.svc.cluster.local:{port} works. I edited this in  dask_kubernetes.core.Scheduler.start and it works.
Another option is the virtual_config bellow. Code bellow is a complete solution.
import dask
from dask.distributed import Client
from dask_kubernetes import KubeCluster, KubeConfig, make_pod_spec

dask.config.set({"kubernetes.scheduler-service-type": "LoadBalancer"})
dask.config.set({"distributed.comm.timeouts.connect": 180})
image = "daskdev/dask"
cluster = "aks-cluster-prod3"
virtual_config = {
    "nodeSelector": {
        "kubernetes.io/role": "agent",
        "beta.kubernetes.io/os": "linux",
        "type": "virtual-kubelet",
    },
    "tolerations": [
        {"key": "virtual-kubelet.io/provider", "operator": "Exists"},
        {"key": "azure.com/aci", "effect": "NoSchedule"},
    ],
    "dnsConfig": {
        "options": [{"name": "ndots", "value": "5"}],
        "searches": [
            "default.svc.cluster.local",
            "svc.cluster.local",
            "cluster.local",
        ],
    },
}

# copied from: https://github.com/dask/dask-docker/blob/master/base/Dockerfile#L25
command_entrypoint_explicit = {
    "command": ["tini", "-g", "--", "/usr/bin/prepare.sh"],
}

pod_spec = make_pod_spec(
    image=image,
    extra_pod_config=virtual_config,
    extra_container_config=command_entrypoint_explicit,
    memory_limit="2G",
    memory_request="2G",
    cpu_limit=1,
    cpu_request=1,
    threads_per_worker=1,  # same as cpu
)

# az aks get-credentials --name aks-cluster1 --resource-group resource_group1
# cp ~/.kube/config ./aksconfig.yaml
auth = KubeConfig(config_file="./aksconfig.yaml", context=cluster,)
cluster = KubeCluster(
    pod_spec,
    auth=auth,
    deploy_mode="remote",
    scheduler_service_wait_timeout=180,
    n_workers=1,
)
client = Client(cluster)


text:
Q: Conditional update in Elasticsearch: "Invalid op [none]" Elasticsearch 2.3. I am firing this query to update every doc in an index based on a condition.
{
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        }
      ]
    }
  },
  "script": {
    "inline": "if (ctx._source.url.endsWith('a=6')) ctx.op = 'none' else ctx._source.url = ctx._source.url + '&b=3'"
  }
}

As stated here, I am using ctx.op = 'none' to avoid updating the docs that do not match the condition.
I am getting

Invalid op [none]

Full error:
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Invalid op [none]"
}
],
"type": "illegal_argument_exception",
"reason": "Invalid op [none]"
},
"status": 400

Seems to be so simple that I am pretty lost. Thanks for your help.

A: The correct operation is noop, not none.
From the documentation:

Just as in Update API you can set ctx.op = "noop" if your script decides that it doesn't have to make any changes. That will cause _update_by_query to omit that document from its updates.

PR created: https://github.com/elastic/elasticsearch/pull/24613


text:
Q: How can I get Mathematica to show me how to integrate an integral? I tried using the free input to show me how to integrate the following integral but it didn't show me the steps.

Solve with steps the integral of x*(2*a^2)*arccos(x/(2*a))-(x^2/2)*sqrt(4a^2-x^2) in the interval [0,a]

How to make Mathematica show me the steps?

A: Not even Wolfram|Alpha called from Mathematica has a step-by-step solution.

Update
Mathematica has no problem with evaluating the integral.
Integrate[2 x a^2 ArcCos[x/(2 a)] - (x^2/2) Sqrt[4 a^2 - x^2], {x, 0, a}]

1/24 a^3 (-4 a + Sqrt[a^2]) (3 Sqrt[3] - 4 π)

It just isn't going to give you a step-by-step solution.


text:
Q: Cannot deploy asp.net core project? I published the asp.net core 2.0.6 to my server (IIS 7.5) and it runs the homepage and other pages fine except trying to get in the Admin route https://example.com/admin/home/dashboard
On the stdout logs: it shows
    fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: No service for type 'Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet' has been registered.
System.InvalidOperationException: No service for type 'Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.<>c__DisplayClass8_0.<CreateActivateInfo>b__1(ViewContext context)
   at Microsoft.Extensions.Internal.PropertyActivator`1.Activate(Object instance, TContext context)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.Activate(Object page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageCoreAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderLayoutAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: No service for type 'Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet' has been registered.
System.InvalidOperationException: No service for type 'Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.<>c__DisplayClass8_0.<CreateActivateInfo>b__1(ViewContext context)
   at Microsoft.Extensions.Internal.PropertyActivator`1.Activate(Object instance, TContext context)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.Activate(Object page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageCoreAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderPageAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderLayoutAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.<RenderAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.<ExecuteAsync>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()

On my Startup.cs - Configure
 app.UseMvc(routes =>
            {
                routes.MapRoute(
                   name: "areaRoute",
                   template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
              ///
}

Program.cs:
 public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .UseDefaultServiceProvider(options =>
        options.ValidateScopes = false)
    .Build();
}

A: The view being used to render /admin/home/dashboard/ or some view involved in rendering that view is injecting the client-side component of Application Insights. Generally speaking, you're looking for an @inject line in some view. It should be easy enough to search for. Find the offending line(s) and remove them, since you're not actually using Application Insights.

A: Add "UseApplicationInsights()" to the WebHostBuilder in Program.cs
   public class Program
    {

        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
             WebHost.CreateDefaultBuilder(args)
                 .UseApplicationInsights()
                 .UseIISIntegration()
                 .UseStartup<Startup>();

    }


text:
Q: Independent collections of sets whose generated $\sigma$-fields are not independent
Let $\Omega= \{ 1, 2, 3, 4\}$, $\mathcal{F} =$ all subsets of $\Omega$
  , and $P(\{ i\}) = 1/4$. Give an example of two collections of sets $\mathcal{A_1}$ and $\mathcal{A_2}$ that are independent but whose generated $\sigma$-fields are not.

I took $\mathcal{A_1}=\{ \{1,2\}\}$ and $\mathcal{A_2}=\{ \{3,4\}\}$, then they are independent but note that $\sigma$ field of $\mathcal{A_1}$ contains $\{3,4\}$, then $\sigma (\mathcal{A_1})$ and $\sigma (\mathcal{A_1})$ are not independent.
But I could do this to any $\mathcal{A_1}$ and $\mathcal{A_2}$ that are subset of $\Omega$. So what is special about $P(\{ i\}) = 1/4$? Am I doing anything wrong?

A: Take $\mathcal{A}_1=\{\{1,2\},\{1,4\}\}$ and $\mathcal{A}_2=\{\{2,4\}\}$ and note that $\{2,4\}\in\sigma(\mathcal{A}_1)$.


text:
Q: HashMap -> Json -> Print - Without Creating file -> using fasterxml API I'm having a hash map with set of keys and values.
I would like to convert it to a json format and print the entire string.
I don't like to create a file and need to dynamically print the string in the screen. i'm using fasterxml api. (http://wiki.fasterxml.com/JacksonInFiveMinutes)
Please let me know how to do it.

A: Please look at the following:
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

public static void main(String[] args) throws JsonProcessingException {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put( "language", "Java" );
    map.put( "year", 2016 );
    map.put( "isObjectOriented", true );
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = mapper.writeValueAsString(map);
    System.out.printf( "JSON: %s", jsonInString );
}

}

I have used following jars:
jackson-core-2.7.4.jar, jackson-databind-2.7.4.jar and jackson-annotations-2.7.4.jar. Hope it helps.


text:
Q: Kafka Stream from JSON to Avro I try to use Kafka Stream to convert a topic with String/JSON messages to another topic as Avro messages.
Stream main method:
    streamsConfiguration.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    streamsConfiguration.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);

    final KStreamBuilder builder = new KStreamBuilder();

    final Serde<String> stringSerde = Serdes.String();

    builder.stream(stringSerde, stringSerde, "testin")
            .mapValues(value -> AvroUtil.transform(value))
            .to("testout");

    final KafkaStreams streams = new KafkaStreams(builder, streamsConfiguration);
    streams.start();

Transformation:
public static GenericRecord transform(Object value) {

    // ... parse string/json and generate Avro object

    String userSchema = "{\"type\":\"record\"," +
            "\"name\":\"myrecord\"," +
            "\"fields\":[{\"name\":\"f1\",\"type\":\"string\"}]}";
    Schema.Parser parser = new Schema.Parser();
    Schema schema = parser.parse(userSchema);
    GenericRecord avroRecord = new GenericData.Record(schema);
    avroRecord.put("f1", "value1");

    return avroRecord;
}

And get an exception like this:
Exception in thread "StreamThread-1" java.lang.NoSuchMethodError: com.fasterxml.jackson.annotation.JsonProperty.access()Lcom/fasterxml/jackson/annotation/JsonProperty$Access;
at com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector.findPropertyAccess(JacksonAnnotationIntrospector.java:229)
at com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$9.withMember(POJOPropertyBuilder.java:545)
at com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$9.withMember(POJOPropertyBuilder.java:542)
at com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder.fromMemberAnnotationsExcept(POJOPropertyBuilder.java:996)
at com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder.findAccess(POJOPropertyBuilder.java:542)
at com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder.removeNonVisible(POJOPropertyBuilder.java:623)
at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector._removeUnwantedAccessor(POJOPropertiesCollector.java:697)
at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.collectAll(POJOPropertiesCollector.java:298)
at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getJsonValueMethod(POJOPropertiesCollector.java:169)
at com.fasterxml.jackson.databind.introspect.BasicBeanDescription.findJsonValueMethod(BasicBeanDescription.java:222)
at com.fasterxml.jackson.databind.ser.BasicSerializerFactory.findSerializerByAnnotations(BasicSerializerFactory.java:355)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:210)
at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:153)
at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1203)
at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1157)
at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:481)
at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:679)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:107)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3559)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2927)
at io.confluent.kafka.schemaregistry.client.rest.entities.requests.RegisterSchemaRequest.toJson(RegisterSchemaRequest.java:76)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:232)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:224)
at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:219)
at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.registerAndGetId(CachedSchemaRegistryClient.java:58)
at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:90)
at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:72)
at io.confluent.kafka.serializers.KafkaAvroSerializer.serialize(KafkaAvroSerializer.java:54)

Is this the right approach? I'm new to Kafka Streams and Avro

A: Just the jackson dependencies were missing:
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.7.8</version>
    </dependency>

Now it works


text:
Q: perl String::Approx on Arrays I'm using String::Approx to find the most alike match for a two-item array out of a list of others.  I was pleasantly surprised to find that you can use amatch() to compare an array to an array although that feature is not documented; I was prepared to write my own function to do that.  I was further surprised to see that the order of the elements doesn't matter.  But, even though amatch() works flawlessly, I'm having a difficult time with adist().  Consider the following program:
#! /usr/bin/perl

use String::Approx qw (amatch adist);

@matches = qw();
%matchhash = qw();
@matchstr = qw(cat dog);
@poss = (['rat', 'hog'],
     ['gnat', 'frog'],
     ['giraffe', 'elephant'],
     ['dig', 'bat'],
     ['catatonic', 'doggone'],
     ['care', 'dog'],
     ['care', 'ding'],
     ['hawk', 'shark']);

@matches = grep { amatch (@matchstr, @$_) } @poss;

foreach $k (@matches)
{
    $dist = adist( @matchstr, @$k );
    print "@matchstr has a difference from @$k of $dist \n";
}

And here's what it outputs:
cat dog has a difference from rat hog of 3
cat dog has a difference from gnat frog of 3
cat dog has a difference from dig bat of 3
cat dog has a difference from catatonic doggone of 3
cat dog has a difference from care dog of 3
cat dog has a difference from care ding of 3

So, it appears to be picking the right answers (it ignored ['giraffe', 'elephant'] and ['hawk', 'shark']), but it can't tell me the distance.  The end goal is to order the matches by distance and pick the one most like @matchstr.  Is amatch() actually working as well as I think it is, or am I just using too simple of input?  Why isn't amatch() working?

A: You can not pass an array as the first argument to amatch or adist and have it work as you are expecting.
Arrays are unpacked into lists, so what amatch sees is something like amatch( 'cat', 'dog', 'rat', 'hog' ) which is of course not what you intended.
You will have to create new versions of amatch and adist that support an array reference as the first argument.  You will then need to call the subs as my_amatch(\@matchstr, @$_)

A: amatch isnt' doing what you think it is.
If you change qw(cat dog) to qw(cat zzz) you get the same results.
Then, if you change "hawk", "shark" to "hawk", "zzz" you still get the same results.
It looks like it's only doing the comparison with "cat".


text:
Q: apt-get complains about untrusted packages Since installing Kubuntu 13.04, apt-get (and all other packaging tools) complain about untrusted packages. As an example, when I try to install ruby1.9.1-dev:
# aptitude install ruby1.9.1-dev
The following NEW packages will be installed:
  gcc{a} gcc-4.7{a} libc-dev-bin{a} libc6-dev{a} libgcc-4.7-dev{a}
  libitm1{a} libquadmath0{a} linux-libc-dev{a} manpages-dev{a}
  ruby1.9.1-dev
0 packages upgraded, 10 newly installed, 0 to remove and 3 not upgraded.
Need to get 15,8 MB of archives. After unpacking 41,0 MB will be used.
Do you want to continue? [Y/n/?]
WARNING: untrusted versions of the following packages will be installed!

Untrusted packages could compromise your system's security.
You should only proceed with the installation if you are certain that
this is what you want to do.

  ruby1.9.1-dev gcc-4.7 libgcc-4.7-dev libquadmath0 gcc libc6-dev libitm1
  linux-libc-dev manpages-dev libc-dev-bin

Do you want to ignore this warning and proceed anyway?
To continue, enter "Yes"; to abort, enter "No":

I'm pretty sure gcc is an official package :-)
What's causing this and how can I get rid of it?


text: Q: file running with no assertion at release but shows assertion at debug mode I'm working a project which work fine at release mode but through an debug assertion at debug mode. I already look into the project properties of both mode but they is no change  in them + the path which the debug assertion occurred doesn't exists in my PC didn't understand the unrealistic behavior of this app any possible solution and guidance  this is there assertion but the path D:\a.... dose not exists in my PC . and if possible how can we disable the assertion box


text:
Q: CountIf Function does not count in Excel VBA in Every cell in a Selection I need to replace a combination of characters. But before a replacement I want to count every combination.
The problem is that CountIf function won't count at all. Though replacement performs.
Here is a code:
Option Explicit

Sub sdfsdf()
Dim rng As Range
Dim i As Integer
Dim Cell As Range
Dim Counter As Variant

'Application.Run "Personal.xlsb!Main"

Set rng = Selection
Set Cell = Cell
Let i = 1

For Each Cell In Selection
Let Counter = Application.WorksheetFunction.CountIf(Cell, i & "&")
Cell.Replace What:=i & "&", Replacement:=""
i = i + 1
Next Cell

MsgBox Counter
End Sub

A snippet of a column with combinations to delete. I need to delete 1&, 2&, 3& and so on.

A: Remove Characters
Sub RemoveChars()

    Const Criteria As String = "&"

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    Dim rg As Range
    Set rg = ws.Range("U2", ws.Cells(ws.Rows.Count, "U").End(xlUp))
    ' Or:
    'Set rg = Selection

    Dim Cell As Range
    Dim Position As Long
    Dim cCount As Long
    Dim cString As String

    For Each Cell In rg.Cells
        cString = CStr(Cell.Value)
        Position = InStr(1, cString, Criteria)
        If Position > 0 Then ' criteria found; replace with chars to the right
            Cell.Value = Mid(cString, Position + 1, Len(cString) - Position)
            cCount = cCount + 1
        'Else ' criteria not found; do nothing
        End If
    Next Cell

    MsgBox "Cells processed: " & cCount, vbInformation

End Sub


text:
Q: How to make breakpart two (black and blue) same height?  %==================================================================
%Compilation --------------------------------------> txs:///xelatex
%==================================================================
\documentclass[10pt,a4paper]{book}
\usepackage{amsmath, amsfonts, amssymb}
\usepackage{booktabs, bookmark, blindtext}
\usepackage{calculator, color, calc, environ, fancyhdr, float, fontawesome, frcursive, comicneue, colortbl}
\usepackage{incgraph, ifthen, ifpdf}
\usepackage[margin=1cm]{geometry}
\usepackage{graphicx, hyperref}
\usepackage{lipsum, lmodern, longtable, ltablex, mathrsfs, mdframed, multicol, multirow}
\usepackage{paracol, pgf, pgffor, polyglossia, pspicture}
\usepackage{pstricks-add, pstricks, pythontex}
\usepackage{scrextend, shapepar, siunitx, spreadtab, supertabular}
\usepackage{tabu, tabularcalc, tabularx, tcolorbox, tikz, tikzpagenodes,array}
\usepackage{titlesec}
\usepackage{titletoc, tocloft, tocvsec2, type1cm}
\usepackage{varwidth, xcolor, xparse}
\pagestyle{empty}
%==================================================================
%==================================================================
\tcbuselibrary{breakable, external, fitting,
    hooks, , magazine, most, poster,
    raster, skins, theorems, vignette,
    %xprase, documentation,
    %listings, minted
}

\usetikzlibrary{decorations.pathmorphing, patterns}
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\newtcolorbox[]{boxe}[1][]{enhanced,
    breakable,
    #1}

%\NewTColorBox[init options]{envname}{specification}{options}

\begin{document}

\newtcolorbox[]{mybox}[1][]{enhanced jigsaw, breakable,
    equal height group=mybox, colframe=red,
    watermark color=yellow!25!white,
    watermark text=\arabic{tcbbreakpart},
}

\begin{paracol}{2}
    \begin{mybox}
        \blindtext[5]
    \end{mybox}
    \switchcolumn
    \begin{mybox}
        \blindtext[6]
    \end{mybox}
\end{paracol}

%==================================================================
%==================================================================
\newpage
%==================================================================
%==================================================================

\end{document}


text:
Q: Implementing interface with class members and functions that need access to them in C# I have this class:
public class Node
{
    public int Data;
    public Node Next;
}

and this interface:
public interface IMyList
{
    Node Head { get; set; }

    void Add(int elm);   // add new element
    void PrintAll();   //print all list
    void Reverse(); // reverse list, implement without using helpers collection\arrays
}

and I need to implement the interface to use all it's inner functions
this is my class that implements the interface:
public class MyCustomizedList : IMyList
{
    Node IMyList.Head { get; set ; }

    public void Add(int elm) { /*something goes here*/ }  // add new element
    public void PrintAll() { /*and here*/ }   //print all list
    public void Reverse() { /*and also here*/ }
    // reverse list, implement without using helpers collection\arrays
}

but I don't understand how do I gain access to the fields of class Node
for example If I want to Implement the function Add()
how do I set the fields of the inner Node Class to attach pointer to the Next Node and the elm value to it's data?

A: Right now, you are implementing the property Head explicitly:
Node IMyList.Head { get; set ; }

To access it, the left hand side of the . must be IList. One simple way to do that is ((IList)this).Head.
For example, to print it to the console:
Console.WriteLine(((IList)this)Head);

Alternatively, if there is no reason for you to implement Head explicitly, don't. Implement it implicitly instead, just like the other members:
public Node Head { get; set; }

A: Try this:
public class MyCustomizedList : IMyList
{
    public Node Head { get; set; }

    public void Add(int elm)
    {
        var newNode = new Node { Data = elm };
        if (this.Head == null)
        {
            this.Head = newNode;
        }
        else
        {
            var node = this.Head;
            while (node.Next != null)
            {
                node = node.Next;
            }

            node.Next = newNode;
        }
    }

    public void PrintAll()
    {
        var builder = new StringBuilder();

        var node = this.Head;
        while (node.Next != null)
        {
            builder.AppendLine(node.Data.ToString());
            node = node.Next;
        }

        var text = builder.ToString();
        Console.WriteLine(text);
    }

    public void Reverse()
    {
        if (this.Head?.Next != null)
        {
            var node = this.Head;
            this.Head = Reverse(node, node.Next);
            node.Next = null;
        }
    }

    private static Node Reverse(Node node1, Node node2)
    {
        if (node2.Next != null)
        {
            var lastNode = Reverse(node2, node2.Next);
            node2.Next = node1;
            return lastNode;
        }

        node2.Next = node1;
        return node2;
    }
}

I think isn't not an efficient data structure. What is the purpose of this class?
To Add an item you must iterate all elements.
You haven't any remove method.
Head is public and their properties too: is not protected from outside mistakes, is not encapsulated...


text:
Q: Using Regex to replace special character I'm trying to get some code in c# to check the start or end of a string and see if it has "\r\n" in one of these locations and if it does I want these characters removed.
I do not want to remove these characters if they are not at the start or end though.
ex:
string tempStringA = "\r\n123\r\n456\r\n";
string tempStringB = "\r\n123\r\n456";
string tempStringC = "123\r\n456\r\n";

tempStringA, tempStringB, and tempStringC  would all become "123\r\n456"

A: string str = @"\r\n123\r\n456\r\n";
str = Regex.Replace(str, @"^(\r\n)+|(\r\n)+$", "");

This works for your example and also works for "\r\n\r\n123\r\n456\r\n\r\n" if there are ever times where there is more than one of those characters.
Edit: Also works for "\r\n123\r\n456" and "123\r\n456\r\n"

A: var str1 = "\r\n123\r\n456\r\n";
var str2 = Regex.Replace(str1, @"^\r\n|\r\n$", "");

This just removes the \r\n at the start and end of the string

A: This is not regex, but regex might be overkill here.
string.Join( "\r\n", "\r\n123\r\n456\r\n".Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries))