text:
Q: How to store Sparql query results into array? I want to store my sparql query results into array. How can i store it? This is my java code. Is it possible using datareader in java?
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.util.FileManager;

public class emotion{
public static void main(String[] args) {
    // TODO Auto-generated method stub

sparqltest();}

static void sparqltest()
{

FileManager.get().addLocatorClassLoader(emotion.class.getClassLoader());
Model model= FileManager.get().loadModel("C:/Users/avg/workspacejena32/Jena/bin/emotion.rdf");
//System.out.println("Connected...");
String queryString="PREFIX  xsd:  <http://www.semanticweb.org/avg/ontologies/2016/2/untitled-ontology-5#>" +
                   "PREFIX  owl:  <http://www.w3.org/2002/07/owl#>" +
                   "PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" +
                   "SELECT  * " +
                   "WHERE" +
                   "{ xsd:angry xsd:says ?x}";

 Query query= QueryFactory.create(queryString);
 QueryExecution qexec=QueryExecutionFactory.create(query, model);

 try {
 ResultSet rs = qexec.execSelect();
for ( ; rs.hasNext() ; )
{
  QuerySolution soln = rs.nextSolution() ;
  RDFNode a = soln.get("x") ;
 // avg = a.asNode().getLocalName();
  System.out.println(a.asNode().getLocalName());
}
}
 finally {

 qexec.close();
    }}}

i am getting results as follows which i want to store in array or something else from where i can call that one by one for future use.
selfish
mad

A: Something like this should do it.
List<RDFNode> result = new ArrayList<RDFNode>();
ResultSet rs = qexec.execSelect();
for ( ; rs.hasNext() ; )
{
  QuerySolution soln = rs.nextSolution() ;
  RDFNode a = soln.get("x") ;
 // avg = a.asNode().getLocalName();
  System.out.println(a.asNode().getLocalName());
  result.add(a);
}


text:
Q: PHP if file_exists() statement fails on file_get_content() from URL I have a very simple function to read URL image file and save it on server.
function o99_download_shot_binary(){

        $url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
        $img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
        file_put_contents($img, file_get_contents($url));
    }

IT works ok, but sometimes , o99_get_content_link() returns an invalid URL, so an empty image is saved , so I made a simple check with if statement and separated the one liner:
function o99_download_shot_binary(){

    $url = esc_url_raw( o99_get_content_link() ); // function returns http:// url
    $img = $uploads['basedir'] . '/tmp/' . uniqid() . '.jpeg'; // name and location
    $file = file_get_contents($url);
     if (file_exists($file)) {
        file_put_contents($img, $file);
     }
}

But doing so, NO image is saved .
So I tried to change the if statement to
if ( $file) { file_put_contents($img, $file); }

..and now it works .
As everything is OK now, you might be wondering why did I posted this question , well,
since I want also to UNDERSTAND what I am doing - My Question is simply :
why does the file_exists($file) check fails ?
I assumed to myself (maybe wrongly) that it is because the file_exists() only checks LOCAL filesystem. If this is the case , then is there a dedicated function to check the existence over URL ? or any other better solutions for future references ?
EDIT I (as per comments request )
Var_dump() is a binary string :
string(51238) "����JFIF��������BZ�|su��{��3�_�R��[J��z���K�^��g�/��9���|*�F��W~�>tχ�>��� �&��?�~0�f�����[��i���R��_���g~�_��Ɵ�#����.5�x+�_ u��-�ٿ�L����ƺV��  ... ... ...

But this is predictable, like I said in original question, the file IS being saved OK, it is just a question of WHY the file_exists() check fails, and if there is a better way to perform that check on a binary remote file from URL...

A: $file = file_get_contents($url) means that $file contains a string, the contents of the file. Unless the file's contents happens to be a path to a file that exists, you won't save anything.
You want to check if( file_exists($url)) and keep the one-liner you had before.

A: file_exists() expects a path, like /home/user/foo.txt, or C:\foo.txt.  You are supplying it with the contents of the file, not the local path to the file, so it will not return a true value (unless, of course, the contents of the file are a valid file path to an existing file... not to muddy the waters but it had to be said :) ).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material ui: change duration of Skeleton animations mui's <Skeleton> components use pulse or wavy animations.
Is there a way to speed up this animation a bit, e.g. by changing the duration?

A: Yes, fairly easily actually! Assuming you're using the latest version of MUI.
<Skeleton width={400} height={100} sx={{ animationDuration: "0.3s" }} />

Read more about the SX prop here.


text:
Q: Can one FCM token be used for multiple devices of same user? I am working on implementing Notification System using Firebase Cloud Messaging. I want to know if the FCM token that is used by Firebase to send notifications can be the same for multiple devices of the same user? Is it possible to do so?
For example, we have an user. I want to generate a single token and store it with the user's profile and send notification to the user on that user's each device using the same token. If the user is logged in on web, as well as app, I want to send notification on both devices using the same token.
Is it possible, if yes then please share any link/doc that may be helpful for me.
Thank you in advance!

A: Each device has diffirent FCM token. If you want to send notification to multi devices, you can send by topic


text:
Q: Order statistics in R? I'm looking for a function to compute order statistics from normal distributions.  Not a ranking or index but the expectation of a given rank or index, given a distribution and a sample size (ie. expected min, median, max).  I am familiar with the analytical solution, but would not be able to solve/approximate the integrals for a normal distribution.  Does anyone know of a package that has implement order statistics in R?

A: You are asking for a package. I don't know of any, but I don't see why you can't "solve/approximate the integrals for a normal distribution" in R. It's actually quite straightforward.
The relevant expression is Equation (1) in this paper:

Where ϕ is the PDF of N[μ, σ] and Φ is the CDF of N[μ, σ]. These functions are built into R as dnorm(...) and pnorm(...) respectively.
f <- function(x, mu=0, sigma=1) dnorm(x, mean=mu, sd=sigma)
F <- function(x, mu=0, sigma=1) pnorm(x, mean=mu, sd=sigma, lower.tail=FALSE)

integrand <- function(x,r,n,mu=0, sigma=1) {
  x * (1 - F(x, mu, sigma))^(r-1) * F(x, mu, sigma)^(n-r) * f(x, mu, sigma)
}

E <- function(r,n, mu=0, sigma=1) {
  (1/beta(r,n-r+1)) * integrate(integrand,-Inf,Inf, r, n, mu, sigma)$value
}

E(1,1000)       # expected value of the minimum
# [1] -3.241436
E(1000,1000)    # expected value of the maximum
# [1] 3.241436
E(500.5,1000)   # expected value of the median
# [1] -6.499977e-18

EDIT Response to OP's comment.
Yes, averaging sample max's from a large number of random draws will approximate E(n,n). There are two differences, though. First, the answer will be approximate, whereas the result above is exact (at least to the accuracy to the numerical integration). Second, the first approach runs about 30 times faster.
E.max <- function(n) mean(sapply(1:100,function(i)max(rnorm(n))))
E.max(1000)
# [1] 3.267614

library(microbenchmark)
microbenchmark(E(1000,1000),E.max(1000))
# Unit: milliseconds
#           expr       min        lq    median       uq       max neval
#  E(1000, 1000)  1.027536  1.169674  1.333428  1.50429  1.905828   100
#    E.max(1000) 23.889773 28.882058 32.642485 37.37952 39.830501   100

A: Not a direct answer, but you can simply use a computer algebra system to compute the closed form densities rather trivially. Then sample such density t get your estimate for min/max/median.
See here: http://www4.stat.ncsu.edu/~hzhang/st522/08Chapter5_order.pdf


text:
Q: Split number and put each digit to separate html element The problem is that I do not know how to break the loop for the first number and start again for the next one. Currently, one span.nNumber has a total digits of the two numbers (123456) and the next span.nNumber contains digits only from another number (456).
Goal is to create sequence 123 and 456:
Markup:

 1
 2
 3

 4
 5
 6

JavaScript (example):
$('div .number').each(function(){
    var number = $(this).text();
    var i = 0;

    $(this).parent().prepend($(""));
    while(i<number.length)
    {
        $(this).closest('span').hide();
        var nChar = number.charAt(i);
        i++;
        $('.nNumber').append(''+nChar.split(" ").join(", ")+'');
    }
});

A: In your while loop, use the following;
$(this).parent().find('.nNumber').append(''+nChar+'');

This way, you'll always modify the nNumber class inside the div you are iterating over. If you use $(".nNumber") you'll get all elements whose class is nNumber, even the ones that are not in your current div. That's why the second iteration of .each() adds the extra digits 456 to the first span.
DEMO.


text:
Q: Design patterns for chaining data transformations methods using pandas I receive monthly a csv file that has some columns. Regardless of what columns I receive, I should output a csv with column C1, C2, C3, ... C29, C30 if possible + a log file with the steps I took.
I know that, the order of my data transformations should be t1, t2, t3, t4, t5.
t1 generates columns C8, C9, C12, C22 using C1, C2, C3, C4
t2 generates columns C10, C11, C17 using C3, C6, C7, C8
t3 generates columns C13, C14, C15, C16 using C5, C8, C10, C11, C22
t4 generates columns C18, C19, C20, C21, C23, C24, C25 using C13, C15
t5 generates columns C26, C27, C28, C29, C30 using C5, C19, C20, C21

I cannot control what columns I get in my input data.
If my input data has C1, C2, C3, C4, C5, C6, C7 columns I can generate all the C1 ... C30 columns.
If my input data has C1, C2, C3, C4, C5, C6, C7, C8, C10, C11, C17 columns I can generate all the C1 ... C30 columns, but I should skip t2, as it is not necessary
If my input data has C1, C2, C3, C4, C6, C7 I can only do t1, t2, t3, t4. I cannot run t5, therefore I should create C26, C27, C28, C29, C30 columns with NaN values only and I should add in the log "Cannot perform t5 transformation because C5 is missing. C26, C27, C28, C29, C30 are filled with NaN values"
My t1, t2, t3, t4, t5 are already created, but I don't know how to organize the code in an elegant manner such that the code repetitions are minimal.
I had to develop my code in a very short amount of time. Consequently, all my t1, t2, t3, t4, t5 methods look like
def ti(df):
    output_cols = get_output_cols()
    if output_cols_already_exist(df, output_cols):
        return df, "{} skipped, the output cols {} already exist".format(inspect.stack()[0][3], output_cols)
    else:
        input_cols = get_required_input_cols()
        missing_cols = get_missing_cols(df, input_cols):
        if missing_cols == []:
            // do stuff
            log = "Performed {} transformation. Created {} columns".format(inspect.stack()[0][3], input_cols)
        else:
            for col in input_cols:
                df[col] = np.NaN
            log = "Cannot perform {} transformation because {} columns are missing. {} are filled with NaN values".format(inspect.stack()[0][3], missing_cols, output_cols)

Also, I use the functions in the following way:
text = ""
df = pd.read_csv(input_path)
df, log_text = t1(df)
text = text + log_text + "\n"
df, log_text = t2(df)
text = text + log_text + "\n"
df, log_text = t3(df)
text = text + log_text + "\n"
df, log_text = t4(df)
text = text + log_text + "\n"
df, log_text = t5(df)
text = text + log_text + "\n"
df.to_csv("output_data.csv", index = False)
logging.info(text)

As you can see, my code is ugly and repetitive. Now I have time to refactor it, but I don't know what would be the best approach. I also want my code to be extensible, as I am also thinking about adding a t6 transform. Can you help me giving some directions / design patterns I could follow? (I am also open using other python libraries beyond pandas)

A: Since, in Python, functions are first-class objects, you could refactor your code in order to generalize your t[i] functions by extracting what seems to differentiate them (the do stuff part), make it a helper function and treat it as a parameter.
You can also avoid repetitions when calling the functions (either the t1, t2, etc. or the refactored helper versions hereafter) by iterating on a list.
Lastly, use of f-strings help make your code a little more readable.
Something like this:
# t function takes a dataframe and a function as parameters
def t(df, do_stuff_func):
    output_cols = get_output_cols()
    if output_cols_already_exist(df, output_cols):
        return (
            df,
            (
                f"{inspect.stack()[0][3]} skipped, "
                f"the output cols {output_cols} already exist",
            ),
        )
    else:
        input_cols = get_required_input_cols()
        missing_cols = get_missing_cols(df, input_cols)
        if missing_cols == []:
            # Call the helper function
            do_stuff_func()
            log = (
                f"Performed {inspect.stack()[0][3]} transformation."
                f"Created {input_cols} columns"
            )
        else:
            for col in input_cols:
                df[col] = np.NaN
            log = (
                f"Cannot perform {inspect.stack()[0][3]} transformation"
                f"because {missing_cols} columns are missing. "
                f"{output_cols} are filled with NaN values"
            )

# Define the five new 'do_stuff' functions
def do_stuff1():
    pass
...
def do_stuff5():
    pass

# Store the functions
do_stuff_funcs = [do_stuff1, do_stuff2, do_stuff3, do_stuff4, do_stuff5]

# Call t function in combination with df and do_stuff_funcs helpers
for do_stuff_func in do_stuff_funcs:
    df, log_text = t(df, do_stuff_func)
    text = text + log_text + "\n"

# Save the results
df.to_csv("output_data.csv", index = False)
logging.info(text)


text:
Q: change default email client for xubuntu 18.04 My "Settings/Preferred Application" is set to Evolution, yet when there is an email link in a web page Thunderbird is activated. I did some Internet research but could not find solution. I do not have 'Activities/Details' menu or similar. This is xubuntu 18.04 with Firefox as web browser and Evolution as email client. I abandoned Thunderbird because Lightning started to loose home calendar and I had to remove and re-install Lightning. Fortunately, my calendar entries were still there.

A: Change the preference in Firefox.  type about:preferences in the address bar and scroll down.  Then type mail in the box.

I don't have Evolution installed so I can't show exactly how to do it, but when you click on Use Thunderbird Mail (default) you will get a dropdown menu with other choices. Hopefully Evolution will be one of the choices.


text:
Q: Functions in custom theme We are a group of 4 who is making a website for a school project. One of the criterias was that we had to script our own theme from scratch. Since we had no experience or knowledge of scripting we followed tutorials we found. The theme kind of works but we are missing most of the basic wordpress functions. We have tried to add the functions.php to our theme, because we did not have it, but we either didn't get any changes or the website crashed.
We can't find a way to make this work and we would love to get some help.
Link to all our scripts: https://gist.github.com/anonymous/8a9f44a2218f1e40ec2d760d15b608f0

A: Using functions.php
Unlike style.css, the functions.php of a child theme does not override its counterpart from the parent. Instead, it is loaded in addition to the parent's functions.php. (Specifically, it is loaded right before the parent's file.)
In that way, the functions.php of a child theme provides a smart, trouble-free method of modifying the functionality of a parent theme. Say that you want to add a PHP function to your theme. The fastest way would be to open its functions.php file and put the function there. But that's not smart: The next time your theme is updated, your function will disappear. But there is an alternative way which is the smart way: you can create a child theme, add a functions.php file in it, and add your function to that file. The function will do the exact same job from there too, with the advantage that it will not be affected by future updates of the parent theme. Do not copy the full content of functions.php of the parent theme into functions.php in the child theme.
https://codex.wordpress.org/Child_Themes


text:
Q: Filling a pandas dataframe column with data between two indexes I have a dataframe:

event
job_id_num

JOB_START
12345

---
---

JOB_END
12345

RETOOL
99999

JOB_START
12346

---
---

JOB_END
12346

Between the JOB_START and JOB_END events there can be x number of rows depending on what job steps take place for a given job.  The JOB_START and JOB_END events are marked with the job_id_number, but the rows between are not.  I need to fill the rows in between the existing job_id_nums.
I started  with this solution, but this solution is for a multi-index Dataframe, whereas mine is not.  I can ffill() the values in I need, but I have to know how many rows I need to fill in as the number of rows to be filled will change job_id_num to job_id_num.

A: I found my problem.  .ffill() will not work if the column data is an empty string '', it needs NaN.  Once I converted empty strings to NaN the rows I wanted filled were filled.


text:
Q: order by problem in date type Same like date_format(ExpenditureDate,'%d-%m-%Y') between '01-01-2011' AND '31-01-2011' ,
Also i cant able to check cond with between, ????
ExpenditureDate  --  DATE type
Below query Displaying correctly , latest dates are coming top and one by one
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC

but if i add date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate
Then loose my proper order, it displaying inordered
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC

A: I don't have a box running mysql to test, but I try to avoid naming the string formated displayable 'expenditure date' the same as the one you sort by.

A: They probably come sorted, but by lexicographical order of the dates rather than chronological order. It's normal since you sort on the ExpenditureDate alias, which is a string containing the formatted date.
Use another alias :
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as FormattedExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY ExpenditureDate DESC

If you really want to keep the same alias, you might also try this :
SELECT ExpenditureName,ExpenditureAmount,ExpenditurePlaceTypeWhome,date_format(ExpenditureDate,'%d-%m-%Y') as ExpenditureDate FROM tblexpenditure WHERE Status=1 AND EntryUser=2 ORDER BY tblexpenditure.ExpenditureDate DESC

A: MySQL seems to sort on the formatted value.  Try writing
...,date_format(ExpenditureDate,'%d-%m-%Y') as FormattedExpenditureDate ...

but leave the ORDER BY clause with the column name.


text:
Q: Easiest way to create drop down with database generated options I'm trying to build a multi-level "game".  A randomly generated option (Option1) will trigger other options in a drop down (Option2)...the options in the new drop down will be directly related the to Option1.  Option2 will then trigger another drop down with info directly related to Option2 and so forth until reaching OptionEnd...any suggestions, preferably SQL and PHP.
Thanks...yeah, I'm a n00b.

A:
Table: option
id int
parent_id int
option_name varchar

When an option is selected $id = that option's id. Then:
SELECT * FROM option WHERE parent_id = $id;
And use those results to populate the new drop down.

A: You'll also probably want to use AJAX to dynamically populate the further options once each one is selected - otherwise you'll need a page refresh every time.

A: the easiest way is probably to use a library or plugin. check out this jQuery dependent select plugin; it looks pretty solid: http://plugins.jquery.com/project/DependentSelect


text:
Q: Uninstaller trouble with standard Windows user I am wondering if I am encountering the same bug with Windows 10 discussed in this post.
I am having a problem with uninstalling a program installed by a standard user without elevation.
I am using INNO Setup, so I have PrivilegesRequired=lowest, and INNO does not prompt for elevated privilege, and installs for the current user, and creates an uninstaller, e.g. uninst000.exe, in my application folder, and I have INNO put an icon for the uninstaller in a Start Menu group for my app (all this done for the current user). INNO also adds an item in the Settings/Apps & Features applet of Windows 10 (this is where the problem comes in).
If the uninstaller is launched from the Start menu icon, there is no prompt for elevated privilege, and my app uninstalls with no trouble.
If the uninstaller is launched from the Apps & Features, a prompt for elevated privilege appears, and if admin credentials are entered (which they must be), the app is not uninstalled correctly. Some things are uninstalled, but not everything. App files are removed, and the start menu group is removed, but additional cleanup actions in INNO's [UninstallRun] section are not getting done. Also, the Uninstall item is not removed from the list in Apps & Features.
So my question is, is this caused by the Windows 10 bug mentioned in the earlier post?

A: I have followed the suggestion of @MartinPrikryl to have the uninstaller (i.e. InitializeUninstall) check the privilege it is running under, and check if the uninstall key is in HKLM or HKCU area of registry.  So far my testing shows this works well.
function IsRegularUser(): Boolean;
begin
    Result := not (IsAdminLoggedOn or IsPowerUserLoggedOn);
end;

function WasInstalledAsStandardUser(): Boolean; //return true if uninstall key is in Current User area of registry
var
    sUnInstPath: String;
    sUnInstallString: String;
begin
    sUnInstPath := ExpandConstant('Software\Microsoft\Windows\CurrentVersion\Uninstall\{#emit SetupSetting("AppName")}_is1');
    sUnInstallString := '';
    Result := True;
    { only one of these keys should be present, but if both are, return True for nonadmin }
    if RegQueryStringValue(HKLM, sUnInstPath, 'UninstallString', sUnInstallString) then Result:=False;
    if RegQueryStringValue(HKCU, sUnInstPath, 'UninstallString', sUnInstallString) then Result:=True;
end;

function InitializeUninstall: Boolean;
begin
    if WasInstalledAsStandardUser() and (Not IsRegularUser) then begin
        MsgBox( MyApp was installed with standard user rights, so it must be uninstalled with stardard user rights.'#13'  So use Start/All Programs/MyApp/Uninstall.', mbInformation, MB_OK);
        Result:=False; exit;
    end;
    Result := True;
end;


text:
Q: Maplex issues with "vbnewline" in ArcMap I'm trying to stack labels using an expression I wrote using VBScript.
I can get them to stack using "vbnewline" but it is a no go when using Maplex's label stacking options.
Using ArcGIS for Desktop Standard 10.3.1. The layer in question is a shapefile and not a geodatabase feature class. The label being used is a banner to call out the feature. I tried to "force split" using spaces in the label expression.
Anybody else have this issue?

A: I use the vbnewline command in the expression field, I have had minor trouble in the past with the overall display of some labels, but the majority would display correctly. I do believe it is one of two things, you either need to double check that the VB code you entered is entered correctly or your settings in your placement properties are interfering with your vb code in your expression.
Here's what I have for my expression:
[NAME] & VBNEWLINE & [PID] & VBTAB & "(" & [ACREAGE] & ")"  & VBNEWLINE & [file_as_na]

You also want to make sure this checkbox is unchecked! see below:

Then in your placement properties you need to make sure the options for stacked labels are on.

Lastly it produces a labeling system like this:

With the maplex options under placement properties you can assign the 'force split' to create new lines in a label. This typically works well if you have attribute fields that are very long and need to be broken up, or if you have merged fields like addresses that can be be broken down at comma points. Most of my data is contained in fields with shorter text entries, therefore I like using the VBScript option so that I can tell it to separate by parenthesis and add four or five different fields. There may be equivocal options in the Maplex tables. The Maplex options may be quicker to assign and set up, but offer less overall control or customization than the VBScript expressions, a mix of both might be best in the long run.
Hope this is what you were looking for, and I hope it helps,


text:
Q: Correct way to update Admin favicon What is the correct way to update the admin favicon? I assume copying over skin/adminhtml/default/default/favicon.ico is incorrect.

A: The correct location for the Admin favicon is indeed "skin/adminhtml/default/default/favicon.ico".
You can confirm this by viewing your Admin page's source code and you'll see something like this:-
<link rel="icon" href="{BASE URL}/skin/adminhtml/default/default/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="{BASE URL}/skin/adminhtml/default/default/favicon.ico" type="image/x-icon" />

Please make sure to clear your Magento cache and browser cache after you change it.

A: Yes location of admin favicon icon occupies here skin/adminhtml/default/default/favicon.ico, unless you are not using any custom theme for admin side and it uses another favicon.ico.
So you can replace this default favicon.ico with yours. But make sure it also should name as favicon.ico
This is because, the favicon for admin side is included through this template app\design\adminhtml\default\default\template\page\head.phtml as like this
<link rel="icon" href="<?php echo $this->getSkinUrl('favicon.ico') ?>" type="image/x-icon"/>

So if you want to give another name for your favicon or need to put to any other folder, you can do it here.


text:
Q: join 2 tables with different column names into 1 without repeating usuarios
--------
nombre

contactos
---------
nombre

I have an insert page where I can select who is responsible for the task. It can either be a client (contactos) or a registered employee (usuarios). The clients can also be registered in usuarios later on, so they can login.
I need to display in a select (for further insert in db) all the values of usuarios.nombre and contactos.nombre without repeating (in case the clients are also registered).
I'm working on PHP and MYSQL. Thank you!

A: This is exactly what a UNION query is built for. In your case the query would look like:
SELECT nombre FROM usuarios
UNION
SELECT nombre FROM contactos

By default this will only return unique hits between the two tables. It will return in a single column.
If, by chance, you didn't want the values to be unique, you would just change it to:
SELECT nombre FROM usuarios
UNION ALL
SELECT nombre FROM contactos

Now MySQL will deliver every nombre record it finds in both tables.


text:
Q: Sanity Data in React JS I am working on a React JS project and using Sanity CMS in backend for data but it does not show my data on screen and throw an error.

How I am able to remove this error and show my data.
I am expecting to remove this error and show my all data from sanity backend to screen


text:
Q: Check whether a test case already exists before creating it - TFS 2018 I am creating a test case in TFS 2018 using postman like this:
curl -X POST \
  'https://TFSURL:443/DefaultCollection/PROJECT/_apis/wit/workitems/$Test%20Case?api-version=4.1' \
  -H 'Authorization: Basic MYKEY' \
  -H 'Content-Type: application/json-patch+json' \
  -d '[
    {
        "op": "add",
        "path": "/fields/System.AreaPath",
        "from": null,
        "value": "TEST\\Automation"
    },
    {
        "op": "add",
        "path": "/fields/System.IterationPath",
        "from": null,
        "value": "TEST\\Sprint 8"
    },
    {
        "op": "add",
        "path": "/fields/System.Title",
        "from": null,
        "value": "Sample task"
    },
    {
        "op": "add",
        "path": "/fields/Microsoft.VSTS.TCM.Steps",
        "value": "<steps id=\"0\">
        <step id=\"1\" type=\"ValidateStep\"><parameterizedString isformatted=\"true\">Input step 1</parameterizedString><parameterizedString isformatted=\"true\">Expectation step 1</parameterizedString><description/></step>
        <step id=\"2\" type=\"ValidateStep\"><parameterizedString isformatted=\"true\">Input step 2</parameterizedString><parameterizedString isformatted=\"true\">Expectation step 2</parameterizedString><description/></step>
        <step id=\"3\" type=\"ValidateStep\"><parameterizedString isformatted=\"true\">Input step 3</parameterizedString><parameterizedString isformatted=\"true\">Expectation step 3</parameterizedString><description/></step>
        <step id=\"4\" type=\"ValidateStep\"><parameterizedString isformatted=\"true\">Input step 4</parameterizedString><parameterizedString isformatted=\"true\">Expectation step 4</parameterizedString><description/></step></steps>"
    }
]'

How can I check before sending this request that this test exist so that I can update it instead of creating a new one every time?
I was expecting to do it by :

*

*searching the name of the automation which should be unique in tfs (method name from automation script) and see if it returns something

It seems like in tfs there is a way to do a request to get all work items but I am not sure if you can return based on the title field of the item. (Help page on how to do this request)
I tried to use the search api to return the results if anything with that name exists in tfs but I am getting an error message which I don't know how to resolve
  curl -X POST \
      'https://TFSURL:443/DefaultCollection/PROJECT/_apis/search/workitemsearchresults?api-version=4.1-preview' \
  -H 'Authorization: Basic MYKEY' \
  -H 'Content-Type: application/json' \
  -d '[
    {
        "searchText": "Sample task",
        "$skip": 0,
        "$top": 1,
        "filters": {
            "System.AreaPath": [
                "TEST\\Automation"
            ]
        },
        "$orderBy": [
            {
                "field": "system.id",
                "sortOrder": "ASC"
            }
        ],
        "includeFacets": true
    }
]'
'

Response:
{
    "count": 1,
    "value": {
        "Message": "An error has occurred."
    }
}

A: Just to answer my own question in case someone else needs it, as I have read you can't do this with just a single or two different API calls. for the following solution i have created multiple REST API request to TFS and called/processed them with Python >3.
What I have done in order to update a test case if it exist or create a new one it if it is not:

*

*Create in tfs a query which returns all test cases

*Update query using an API request and the key of the query you have created (i specified iteration and team specifically in the body of the request) (help)

*Create an API request to get the result of that query (help)

*In a loop i was iterating over all the test case ids the query has returned

*In the same loop I have used the test case id to access with a request that specific work item (help)

*I then compared the title of the returned item versus the title that i want to create from my automate script (ClassName_MethodName)

*If those titles where the same I do a request to update that test case using the test id i got and then break from the loop

*If the titles were different i create a new test case and then break from the loop

I know this is not the fastest solution but at least it is working!
If there is another way which is easier and faster I am more than happy to follow it.


text:
Q: Java XStream cannot find class in Maven directory I am using XStream and when I run my application for a module called Webserver directory: org/westbank/webserver
But if I have it in certain other modules, it parses fine without the error.. I am confused. Even if i make a new module and try it, I get the error, but most of the other modules I have work if I add TestService to it and load it from that path.
My XML:
<XML>
 <service class = "org.westbank.webserver.authentication.TestService">
    <name>Test</name>
    <identifier>14</identifier>
    <vital>true</vital>
 </service>
</XML>

The Error:
Exception in thread "main"
com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     :     com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : org.westbank.webserver.authentication.TestService
class               : org.westbank.configuration.XMLConfiguration
required-type       : org.westbank.configuration.XMLConfiguration
converter-type      :     com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path                : /XML/service
line number         : 2
version             : 1.4.9
-------------------------------
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException:     org.westbank.webserver.authentication.TestService

A: When using the XStream library you need to add your Maven module as a Dependency from the module you are trying to call the other modules' class from.
IE:
I use Configuration module to call TestService from Webserver module, I need to make sure Configuration module has Webserver module added as a dependency.


text:
Q: Activity restarted when i press home button in android I am afraid that my activity is restarted when i open it through TaskManager....
and my DefaultHttpClient object treated as fresh one..so here i am loosing the
session.
I tried by overriding the onSaveInstanceState() method..but no use..
@Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState); // the UI component values are saved here.
        }

How i can get rid of this one...

A: You could subclass Android Applications: You can init the HttpClient there and hold the reference.
Look here
Than you can access from activity your Application object with activity.getApplication()
If your session works with cookies than you may need a persistent cookie storeage (like database or shared preferences):
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * A persistent cookie store which implements the Apache HttpClient
 * {@link CookieStore} interface. Cookies are stored and will persist on the
 * user's device between application sessions since they are serialized and
 * stored in {@link SharedPreferences}.
 * <p>
 */
public class PersistentCookieStore implements CookieStore {
    private static final String COOKIE_PREFS = "CookiePrefsFile";
    private static final String COOKIE_NAME_STORE = "names";
    private static final String COOKIE_NAME_PREFIX = "cookie_";

    private final ConcurrentHashMap<String, Cookie> cookies;
    private final SharedPreferences cookiePrefs;

    /**
     * Construct a persistent cookie store.
     */
    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new ConcurrentHashMap<String, Cookie>();

        // Load any previously stored cookies into the store
        String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE,
                null);
        if (storedCookieNames != null) {
            String[] cookieNames = TextUtils.split(storedCookieNames, ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX
                        + name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        cookies.put(name, decodedCookie);
                    }
                }
            }

            // Clear out expired cookies
            clearExpired(new Date());
        }
    }

    @Override
    public synchronized void addCookie(Cookie cookie) {
        String name = cookie.getName() + cookie.getDomain();

        // Save cookie into local store, or remove if expired
        if (!cookie.isExpired(new Date())) {
            cookies.put(name, cookie);
        } else {
            cookies.remove(name);
        }

        // Save cookie into persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(COOKIE_NAME_STORE,
                TextUtils.join(",", cookies.keySet()));
        prefsWriter.putString(COOKIE_NAME_PREFIX + name,
                encodeCookie(new SerializableCookie(cookie)));
        prefsWriter.commit();
    }

    @Override
    public synchronized void clear() {
        // Clear cookies from persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        for (String name : cookies.keySet()) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);
        }
        prefsWriter.remove(COOKIE_NAME_STORE);
        prefsWriter.commit();

        // Clear cookies from local store
        cookies.clear();
    }

    @Override
    public synchronized boolean clearExpired(Date date) {
        boolean clearedAny = false;
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

        for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
            String name = entry.getKey();
            Cookie cookie = entry.getValue();
            if (cookie.isExpired(date)) {
                // Clear cookies from local store
                cookies.remove(name);

                // Clear cookies from persistent store
                prefsWriter.remove(COOKIE_NAME_PREFIX + name);

                // We've cleared at least one
                clearedAny = true;
            }
        }

        // Update names in persistent store
        if (clearedAny) {
            prefsWriter.putString(COOKIE_NAME_STORE,
                    TextUtils.join(",", cookies.keySet()));
        }
        prefsWriter.commit();

        return clearedAny;
    }

    @Override
    public synchronized List<Cookie> getCookies() {
        return new CopyOnWriteArrayList<Cookie>(cookies.values());
    }

    //
    // Cookie serialization/deserialization
    //

    protected synchronized String encodeCookie(SerializableCookie cookie) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (Exception e) {
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    protected synchronized Cookie decodeCookie(String cookieStr) {
        byte[] bytes = hexStringToByteArray(cookieStr);
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(is);
            cookie = ((SerializableCookie) ois.readObject()).getCookie();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cookie;
    }

    // Using some super basic byte array <-> hex conversions so we don't have
    // to rely on any large Base64 libraries. Can be overridden if you like!
    protected synchronized String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (byte element : b) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }

    protected synchronized byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}

Do something like this:
httpClient.setCookieStoreage(new PersistentCookieStore(this)) in your application subclass where you init the httpclient

A: when you press button Home, activity will pause and resume when reopen.
you shout put code to onCreate().
see activity lifecryde:

A: You are probably seeing a nasty, long-standing Android bug that causes the symptoms you are describing. Have a look at my answer here: https://stackoverflow.com/a/16447508/769265

A: You probably have to add following code inside the onCreate() event of launcher Activity.
if (!isTaskRoot()) {
    final Intent intent = getIntent();
    final String action = intent.getAction();
    if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
        finish();//Launcher Activity is not the root. So,finish it instead of launching
        return;
    }
}

A:     android:launchMode="singleInstance"
    android:alwaysRetainTaskState="true"

Try adding this two attributes to your Activity in manifest, this will make sure newIntent is called when activity is resumed from background.


text:
Q: edited-- if statement vba -- how to skip a cell if it has a value I've edit my original post and given you more details. Basically I have this code:
For x = 1 To 1000
If track.Cells(x, 1) = Date Then
    If track.Cells(x, 2) = "EU" Then
        If track.Cells(x, 3) = "ABCDE" Then
           ST.Range("ABCDE").Copy
           EU.Cells(41, 2).PasteSpecial
           Call ActivateSheet
           track.Range(Cells(x, 4), Cells(x, 9)).Copy
               **For i = 42 To 1000
                  If EU.Cells(42 + i, 2) Then
                     EU.Cells(42 + 1, 2).PasteSpecial
                  End If
               Next i**
        End If
    End If
End If Next x

And I'm having problems with this specific part of the code:
For i = 42 To 1000
                  If EU.Cells(42 + i, 2) Then
                     EU.Cells(42 + 1, 2).PasteSpecial
                  End If
               Next i

What this basically does is copy a range of cells from another worksheet on the same workbook and it should place it on another worksheet. Now, what happens with the code i'm having problems is, I want it to paste to the row below AFTER it pastes the first one. Are there any other ways I can achieve this? I'm only starting to self teach myself in VBA coding. Any advice would be greatly appreciated.

A: You don't need to loop the values to find the bottom row, you can simply come from the bottom up in one go.
replace this:
**For i = 42 To 1000
   If EU.Cells(42 + i, 2) Then
      EU.Cells(42 + 1, 2).PasteSpecial
   End If
Next i**

With this:
Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial

How it works:
Cells(rows.count,2) is the very last row in the sheet and column 2 (B1048576 nowadays or B65536 in the old days)
.End(XLup) tells it to go up until data, exactly like CTRL-UP in Excel
This tells us the last row that contains data, we don't want to paste here because you will overwrite your last row so:
.offset(1,0) tells it to go ONE row and zero columns away from where it is.
This has worked out the address of where you need to paste, then we pastespecial.
Hope that helps
To actually see how this works go to the immediate window in the VB editor using CTRL-G and paste the following code:
?Cells(Rows.Count, 2).address
?Cells(Rows.Count, 2).End(xlUp).address
?Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).address

Hit enter after each line and you will see how each added portion of code to the line alters the results

A: If you mean you just want to alter cells that are empty you can use IsEmpty(), such as:
For Each cell In rng
    If IsEmpty(cell) Then 'To alter cells containing value use If Not IsEmpty...
    ' Do something
    End If
Next

Or if their is the possibility of the cell values containing spaces you can use
If trim(cell & vbnullstring) = vbnullstring Then
' Do something
End If

To Skip cells that's value is of type Text use IsText
If Not Application.IsText(cell) Then
' Do Something
End If

To only alter values that contain only numbers use IsNumeric
If IsNumeric(cell) Then
' Do something
End If


text:
Q: Inaccurate Location Android Yesterday I happen to test my GPS tracking app on moving device I was being tracked well but suddenly I started getting wrong location Exactly 282 km from actual location Any idea why this may happen?

A: You were using getLastKnownLocation(). Acctually getLastKnownLocation start giving the last updated location of your devices. So may be this be the reason. Happen with me. As due to cloud i was not able to get Lat long so getLastKnownLocation give the address where It was updated last.
So this may be the reason...else you have to check for Log.

A: Can be three main possibilities -

*

*You have wifi hotspot, which was moved from one location to another. Then google have "remember" location of this access point, but point was moved.

*Some problem with GPS driver

*There was some bug in GPS retranslator (which is located on earth), located near your device.


text:
Q: Vuejs http interceptors fails I am trying to setup vuejs http interceptors but they dont work.
Vue.use(VueResource)
Vue.http.options.root = 'http://127.0.0.1:8000/api' //this works

Vue.http.interceptors.push({
  request: (request) => {
    console.log("we have a request")
    return request
  },
  response: (response) => {
    console.log('we got a response', response)
    return response
  },
  error: (err) => {
    console.log('error is', err)
  }
})

Now in my components
this.$http.get('user/profile/')

THe interceptors dont console.log
Where am i going wrong?

A: You don't have the interceptors configured properly, you should be pushing a function with 2 arguments request and next.
Vue.use(VueResource)
Vue.http.options.root = 'http://127.0.0.1:8000/api' //this works

Vue.http.interceptors.push(function (request, next) {
  console.log(request)
  request.headers.set('Authorization', 'Bearer ' + sessionStorage.getItem('token'))
  next()
})

Vue.http.interceptors.push(function (request, next) {
  next(function (response) {
    console.log(response)
    if (response.status === 401) {
      // handle error or logout
      return response
    }
  })
})


text:
Q: Android: Is it possible to create an unsigned debug build? It is my understanding that debug builds are automatically signed with the debug keystore by default.
I'd like a debug build that is unsigned, for various reasons. I am aware of various solutions to sign debug builds, but that is not what I am looking for.
We are using gradle.
I am aware that creating another release type/flavors will result in an unsigned apk, but that is not what I am asking for.
Again, I am asking, is it possible to create the default debug build, but simply unsigned?

A: Maxim G's comment referencing another question:

Export unsigned apk from a Gradle Project in Android Studio

lead me to a comment to one of the answers:

The output folder only had debug signed apk for me. This post is how I got a truly unsigned apk: entzeroth.com/export-unsigned-android-apk – Keith Entzeroth

The linked site lead me to the answer, which I suppose I should've figured out myself:
debug {
    signingConfig null
}

Hopefully it is self explaning why this yields an unsigned debug build.
I think it is redundant to specify this for other builds, as there is no default signing configuration, only for debug, I think.
In practice, I am doing something slightly different:
if (project.hasProperty('debug_force_unsign') &&
                property('debug_force_unsign') == 'true') {
    debug {
        signingConfig null
    }
}

The property 'debug_force_unsign' simply allows me to specify exactly when I want the debug build to be unsigned, which is typically only for debug builds created on my build machine. I execute:
gradlew clean assembleDebug -Pdebug_force_unsign=true

to force the debug build to be unsigned. I then sign it at a later step.
If I didn't do this, my debug builds would be unsigned on my dev machine, and I wouldn't be able to easily install them. Basically, it would break the process that happens when I press the RUN button on my IDE, and slow things down.
There are perhaps easier ways to do this entire process, but this solves my current predicament.


text:
Q: How to check if the response Body has a string for a nested JSON in POSTMAN To check if the Respondy Body has a string, I can use this:
tests["Body matches string"] = responseBody.has("string_you_want_to_search");

But I have a responseBody like this:
{
 "total": 20000,
 "amount": {
   "total": 10000,
   "fees": 0,
   "refunds": 0,
   "liquid": 10000,
   "currency": "BRL"
 },
}

How can I check the field amount.total?

A: Use dot operator to test to access the nested value:
var data = JSON.parse(responseBody);
tests["10000"] = data.amount.liquid === "10000";
tests["BRL"] = data.amount.currency === "BRL";

Hope it helps!


text:
Q: NodeJS Parse error: SyntaxError: Unexpected end of input at Object.parse (native) I have a problem with my script and I'm beginner in Node.JS. I run Ubuntu Linux.
Problem details:
I have a script that writes a file (mini.json) many times per second. And another script that reads that file(mini.json) when the file changes. The problem is with the second script that reads the file.
This is the app that reads the file
var fs = require('fs');

app.locals.config.RandomData.forEach(function(item) {

fs.exists(item.random, function (exists) {
    if (exists) {

        var current_random_adress = item.random + '/mini.json';
        // console.log(current_random_adress);

        fs.watchFile(current_random_adress,{ persistent: true, interval: 1 }, function(curr,prev) {  // in ms
            // console.log("current mtime: " +curr.mtime);
            // console.log("previous mtime: "+prev.mtime);
            if (+curr.mtime === +prev.mtime) {

                // Do nothing because the file didn't change

            } else {
                console.log("The file have changes");

                var brute_data = fs.readFileSync(current_data, 'utf8');

                var object_parsed_from_file = JSON.parse(brute_data);

             //   console.log(object_parsed_from_file.random_string1);
                var datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');

            }
        });
        console.log("Route or file exists");
    } else {
        console.log("Route or file doesn't exist");
    }
});

});
This is the file (readed with readFileSync)
  {
"data1" : "random_string1",
"data2" : "random_string2",
"parities" : [
                {
                    "data3" : "random_string3",
                    "data4" : "random_string4",
                    "data5" : "random_string5"
                }
            ]
 }

And this is the error.I outputed just the last 30 lines of the console
Note: The error occures after few thousand executions.
The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes

undefined:0

^
SyntaxError: Unexpected end of input
at Object.parse (native)
at StatWatcher.<anonymous> (/media/idz/01D02FC315F350A0/Dev-    Node/microapp3/app.js:318:56)
at StatWatcher.emit (events.js:98:17)
at StatWatcher._handle.onchange (fs.js:1115:10)
idz@idz-ThinkPad-Edge-E531:/media/idz/01D02FC315F350A0/Dev-Node/microapp3$


text:
Q: Why does this binary tree search take so much longer than an insertion? I'm trying to learn/understand some basic algorithms, and today I decided to write a binary tree in Go. This is what the structure looks like:
type Node struct {
  Value int
  Left  *Node
  Right *Node
}

Here's my function to check if the tree contains an int:
func (tree *Node) Contains(val int) bool {
  if val == tree.Value {
    return true
  } else if val > tree.Value {
    if tree.Right != nil {
      return tree.Right.Contains(val)
    } else {
      return false
    }
  } else if val < tree.Value {
    if tree.Left != nil {
      return tree.Left.Contains(val)
    } else {
      return false
    }
  } else { // huh
    return false
  }
}

I wrote a test function to test how long different operations on the tree take. It takes my Insert() function 34ms to insert 100,000 random integers, and it takes my Contains() function 33ms to check if the tree contains 100,000  random integers. If I bump the number of random integers up to 1,000,000, it takes my Insert() function 34ms to run, but my Contains() function suddenly takes 321ms to run.
Why does Contains() run time increase so drastically, while Insert() stays practically the same?

A: The Insert function should periodically rebalance the tree, as an imbalanced tree may lead to very uneven traversal times.  As a result, Insert should generally be slower that Contains.
If your Insert function does not rebalance the tree, then the time required for any given function become O(n) worst case instead of O(log n) and fairly unpredictable.
In addition, when talking about O(...) time complexity, we're generally talking about worst case behavior.  If you time single calls, then any given call may take (much) less time than the worst case -- for example, Contains looking for the node that happens to be the root will return immediately regardless of the size.


text:
Q: Azure Service Fabric : how to find the end point after deployment I am new to Azure Service Fabric and trying to deploy the first stateless web API app to cloud.
the publishing was successful and showing up in the fabric Service explorer.
Under All Applications menu, it is showing
fabric:/Application1
How to find the endpoint to access the application now.
Any help greatly appreciated.
thanks

A: Check the ServiceManifest.xml file for the endpoint configuration. It should specify a
port to access the service in.


text:
Q: Parse Azure search query filter My server works as a proxy for a user's search request. Before requesting data on Azure we need to ensure everything is secure. For this we add certain filters into the query filter.
Let's say my server receives this query:
search=&$top=10&$filter=customer/customerId gt 1 and customer/customerId lt 5

I want to break it apart, investigate it's filter piece by piece and inject a security filter into it.
First thing I do is I get the filter:
var parsed = HttpUtility.ParseQueryString(query);
var filter = parsed["$filter"];

Next, I want to process it in order to verify and make changes.
After reading this post I am trying to utilize ODataUriParser like so:
// 1. Create a dummy model
public static IEdmModel GetEdmModel()
{
    var model = new EdmModel();

    EdmEntityType customer = new EdmEntityType("Namespace", "Customer");
    customer.AddKeys(customer.AddStructuralProperty("CustomerId", EdmPrimitiveTypeKind.Int32));
    model.AddElement(customer);

    return model;
}

// 2. Utilize it
static void Foo()
{
    var query = "search=&$top=5001&$filter=Customer/CustomerId eq 1";

    var parsed = HttpUtility.ParseQueryString(query);
    var filter = parsed["$filter"];

    var result = new ODataUriParser(HardCodedTestModel.TestModel, new Uri(filter, UriKind.Relative));
    var parsedFilter = result.ParseFilter();
}

This throws an exception to me, saying:

Unhandled exception.
Microsoft.OData.UriParser.ODataUnrecognizedPathException: Resource not
found for the segment 'Customer

*

*What am I doing wrong?

*Is there more easier way to achieve what I want?

A: Your EDM model doesn't appear to include an entity set, so it's not clear what the filter is filtering. Azure Cognitive Search defines an EDM model for each index that includes an entity set "docs", the type of which corresponds to the index definition. The property path Customer/CustomerId in the filter would be interpreted by Azure Cognitive Search as the CustomerId sub-field of a top-level Edm.ComplexType field named Customer (Using OData terminology, the document is the entity, Customer is a Complex property, and CustomerId is a property of Customer). Your EDM model will have to include all this schema information if you want to use ODataUriParser or ODataQueryOptionParser to obtain a semantic AST from the filter text.
That said, you probably don't need a full semantic AST to verify the security of the filter expression (assuming you're trying to defend against things like injection attacks). It might be simpler to use the lexical stage of the OData filter parser by itself. Then you can process the syntactic AST.
If you want maximum control, you can always roll your own parser. The full BNF for OData is here.


text:
Q: Formatting files - C++ I have hit a brick wall trying to format one of my files. I have a file that I have formatted to look like this:
 0          1          2          3          4          5
 0.047224   0.184679  -0.039316  -0.008939  -0.042705  -0.014458
-0.032791  -0.039254   0.075326  -0.000667  -0.002406  -0.010696
-0.020048  -0.008680  -0.000918   0.302428  -0.127547  -0.049475
 ...
 6          7          8          9          10         11
 [numbers as above]
 12         13         14         15         16         17
 [numbers as above]
 ...

Each block of numbers has exactly the same number of lines. What I am trying to do is basically move every block (including the headers) to the right of the first block so in the end my output file would look like this:
 0          1          2          3          4          5              6         7         8        9          10         11     ...
 0.047224   0.184679  -0.039316  -0.008939  -0.042705  -0.014458   [numbers]    ...
-0.032791  -0.039254   0.075326  -0.000667  -0.002406  -0.010696   [numbers]    ...
-0.020048  -0.008680  -0.000918   0.302428  -0.127547  -0.049475   [numbers]    ...
 ...

So in the end I should basically get a nxn matrix (only considering the numbers). I already have a python/bash hybrid script that can format this file
exactly like this BUT I've switched the running of my code from Linux to Windows and hence cannot use the bash part of the script anymore (since my code has to be compliant will all versions of Windows). To be honest I have no idea how to do it so any help would be appreciated!
Here's what I tried until now (it's completely wrong I know but maybe I can build on it...):
 void finalFormatFile()
 {
 ifstream finalFormat;
 ofstream finalFile;
 string fileLine = "";
 stringstream newLine;
 finalFormat.open("xxx.txt");
 finalFile.open("yyy.txt");
 int countLines = 0;
 while (!finalFormat.eof())
 {
     countLines++;
     if (countLines % (nAtoms*3) == 0)
     {
       getline(finalFormat, fileLine);
       newLine << fileLine;
       finalFile << newLine.str() << endl;
     }
     else getline(finalFormat, fileLine);
 }
 finalFormat.close();
 finalFile.close();
}

A: For such a task, I would do it the simple way. As we already know the number of lines and we know the pattern, I would simply keep a vector of strings (one entry per line of the final file) that I would update as I'm parsing the input file. Once it's done, I would iterate through my strings to print them into the final file. Here is a code that's doing it :
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

int main(int argc, char * argv[])
{
  int n = 6; // n = 3 * nAtoms

  std::ifstream in("test.txt");
  std::ofstream out("test_out.txt");

  std::vector<std::string> lines(n + 1);
  std::string line("");
  int cnt = 0;

  // Reading the input file
  while(getline(in, line))
  {
    lines[cnt] = lines[cnt] + " " + line;
    cnt = (cnt + 1) % (n + 1);
  }

  // Writing the output file
  for(unsigned int i = 0; i < lines.size(); i ++)
  {
    out << lines[i] << std::endl;
  }

  in.close();
  out.close();

  return 0;
}

Note that, depending of the structure of your input/ouput files, you might want to adjust the line lines[cnt] = lines[cnt] + " " + line in order to separate the columns with the right delimiter.


text:
Q: Javascript and CSS file compression techniques with some Third Party Tools We are in a urgency to implement fileaggregation for Javascript and css files
We hav 12 javascript files and 8 css files.
There are lot of experienced people , can you please suggest which tool should i use to compress them into one js and css file.
If i compress them , how can i change in the code , right now they are inserted in the msater page. All css and js files are included in the master file of the website.
Thanks in advance.

A: Yahoo's YUI compressor: here for javascript. But I am not 100% sure if you can simply merge all the javascript files into one, because I suspect that would be depending on the way how people program in those scripts.
And here is CSS compressor, you can always use tools like Firebug to detect unused CSS rules so to remove duplicated/unnecessary CSS rules.
I highly recommend Google's Page Speed as an add-on for Firefox, this would reveal the "bottleneck" of your website's performance.

A: Based on the fact that you mentioned master page, I assume that you are working with ASP.NET. In that case, there's a built-in tool to do that. You can use  and  in order to notify ASP.NET engine that you want to combine javascript files. It will take care of the rest for you. This is for ASP.NET 3.0 or above, or ASP.NET 2.0 with MSAJAX installed. Here's an example of how to use it:
<asp:ScriptManager runat="server">
 <Scripts>
  <CompositeScript>
   <Scripts>
    <asp:ScriptReference Name="MicrosoftAjax.js"/>
    <asp:ScriptReference Name="Custom.Extender.1.js" Assembly="Custom" />
    <asp:ScriptReference Path="~/Scripts/Custom2.js" />
    <asp:ScriptReference Name="Custom.Extender.2.js" />
   </Scripts>
  </CompositeScript>
 </Scripts>
</asp: ScriptManager>

For more information, see this link: ScriptManager


text:
Q: Error : java.util.ArrayList cannot be cast to java.lang.String when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "
and this is my code :
 textField_1 = new JTextField();
       textField_1.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
           Object selected = list_1.getSelectedValue();
            Connection conn = null;
            PreparedStatement stmt = null;
            String a =null;
         try{

   conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
   String query= " INSERT INTO flyer_item (discount)  SELECT price * ? FROM `item` WHERE item_name = `?` ";
   Statement st= conn.createStatement();

   java.sql.PreparedStatement ps = conn.prepareStatement(query);
                        ps.setString(1,a);
                        ps.setString(2,(String) selected);
                        ps.executeUpdate();
                        st.executeUpdate(query);

                    } catch (SQLException se){
                        System.out.println(se.getMessage());

                    } }} );

Any help please ?

A: Here Selected is an array-list and you are trying to convert it into string which is not possible:
ps.setString(2,(String) selected);

What you should do?
ps.setString(2, selected.tostring());

A: Are you sure about this line ?
       Object selected = list_1.getSelectedValue();

Make sure selected is a String before casting . You can use instanceof operator to check the Object type.


text:
Q: C++ Syntax error in header using class from another header EDIT: My IDE was giving me a bad error message and because I was going through a major refactor, there were so many error messages on compile that I didn't read through them all, naively assuming that my IDE would know the problem.
The problem was that the Font and Text headers referenced each other, and the compiler threw a syntax error on the Text token in the Font header. This was fixed by writing class Text; at the top of the Font header file, as @molbdnilo correctly answered.
I apologize for my haste in ignoring compilation errors. I'd like to leave this as a message to future readers: CLion 2021.1.1 Build #CL-211.7142.21 was unable to detect this error and semi-incorrectly highlighted the line mentioned below saying the constructor did not exist. The Text constructor could not be parsed because it circularly referenced the Font header.

The compiler is telling me that a constructor I have declared and defined does not match arguments that seem to match. My IDE recommends using the default constructor, but I have intentionally not defined one.
I have the following declarations and every member is implemented:
class Font {
private:
  static Shader* fontShader;
  std::map<char, Character> characters;
  unsigned int VAO, VBO, EBO;
public:
  static void GLYPH_VAO_REGISTER();
  static Shader* getFontShader();
  Font(const std::string &name, int size);
  ~Font();
  Text *drawText(std::string text, float x, float y, float scale, glm::vec3 color);
};

class Text: public Renderable {
private:
  Font *font;
  const std::string &text;
public:
  Text(Font* font, const std::string &text);
};

When I try to create a new instance of both, I am able to create an instance of the Font class, but not the Text class:
Text* Font::drawText(std::string text, float x, float y, float scale, glm::vec3 color) {
  Text *target = new Text(this, text);
                     ^^^^ No matching constructor for initialization of 'Text'
  return target;
}

The definition of the Text constructor is:
Text::Text(Font *font, const std::string &text) : Renderable(
    ("text-" + text),
    true,
    GLYPH_VERTEX_COUNT,
    nullptr,
    GLYPH_INDEX_COUNT,
    nullptr,
    true,
    &Font::GLYPH_VAO_REGISTER,
    Font::getFontShader()), font(font), text(text) {}

My IDE shows the definition in the header file as existing, and I cannot figure out why the compiler doesn't seem to recognize the constructor. Any help is greatly appreciated :)
EDIT: I think it's important to mention both of the class declarations are in different header files, and I think the problem is that neither is able to get the definition because they reference each other (I'd excluded functions which I now realize are crucial to reproducing the error). The error I got was a syntax error on the line Font *font; in the text.h file. Adding class Font; to the top seemed to stop the syntax error, but I'm unsure if it's actually solving the problem. I've added the function which references the Text class. I guess now I'm wondering why, even though the headers include each other, they are not able to see the declarations.
On compilation the errors are text.h(17,8): error C2143: syntax error: missing ';' before '*' (line 17 being the Font *font; line) and text.h(20,7): error C2061: syntax error: identifier 'Font' (line 20 being the constructor).

A: You have a problem because the headers include each other, not despite it.
Remember that #include is a very primitive mechanism that literally only inserts the contents of a file in a certain place.
Take this simplified example:
A.h:
#ifndef A_H
#define A_H
#include "B.h"

class A { B* b; };

#endif

B.h:
#ifndef B_H
#define B_H
#include "A.h"

class B { A* a; };

#endif

Now, when compiling "A.h", it looks like this after preprocessing:
class B { A* a; };
class A { B* b; };

and A is unknown in that definition of B.
The #include "A.h" from "B.h" becomes nothing, since it is included inside the A_H include guard.
The same thing happens with "B.h", but in the other order.
The solution is to use forward declarations - since you're using pointers, you only need the class names, and you can just declare that they exist somewhere.
Then you include the headers in the source files that need them, and everything will be worked out by the compiler.
A.h:
#ifndef A_H
#define A_H

class B;
class A { B* b; };

#endif

B.h:
#ifndef B_H
#define B_H

class A;
class B { A* a; };

#endif

B.cpp:
#include "A.h"
#include "B.h"

// Use A and B freely


text:
Q: Open template file in Pop Up I am trying to load a HTML5 Audio player in a popup but am having no luck. The staging site is here
The audio player works but not after you click the Listen In Pop Up button/link. Here is my code to call the template file which contains the same code as the on page audio section.
<a class="popup" href="<?php echo get_template_directory_uri(); ?>/assets/inc/modules/module-audio-popup.php"
onclick="javascript:void window.open('<?php echo get_template_directory_uri(); ?>/assets/inc/modules/module-audio-popup.php',
'1418242983717','width=500,height=300,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=1,left=0,top=0');
return false;">
Listen in PopUp

Any advice would be most welcome.
Code for the popup file here

A: There is a fatal error in your source (module-audio-popup.php) :

Fatal error: Call to undefined function the_field() in /home/website/public_html/sites/fm/wp-content/themes/trickstarfm/assets/inc/modules/module-audio-popup.php on line 11

I will remove this answer later on, but posting this as a comment wouldn't make a readable post.

A: the_field() function need a field name parameter and it must inside a loop.

A: I got my answer here with this snippet:
if(!defined(ABSPATH)){
    $pagePath = explode('/wp-content/', dirname(__FILE__));
    include_once(str_replace('wp-content/' , '', $pagePath[0] . '/wp-load.php'));
}

I included this before any other HTML/PHP.


text:
Q: How to properly loop through these external URLs to get them into the sitemap using this hook I have filtered Urls that I would like to add to push into a sitemap. I am using one of the sitemap plugins, which has hooks to further modify it.
my code:
// add to theme's functions.php
add_filter('bwp_gxs_external_pages', 'bwp_gxs_external_pages');
function bwp_gxs_external_pages($pages)
{
    return array(
        array('location' => home_url('www.example.com/used-cars/location/new-york/model/bmw'), 'lastmod' => '27/03/2017', 'frequency' => 'auto', 'priority' => '1.0'),
        array('location' => home_url('www.example.com/used-cars/location/los-angeles/model/aston-martin'), 'lastmod' => '27/03/2017', 'frequency' => 'auto', 'priority' => '0.8')
                array('location' => home_url('www.example.com/used-cars/model/mercedes-benz'), 'lastmod' => '27/03/2017', 'frequency' => 'auto', 'priority' => '0.8')
    );
}

So as you can see in my code that I have these kind of URLs www.example.com/used-cars/location/new-york/model/bmw & www.example.com/used-cars/model/mercedes-benz
So my issue is that, there are thousands of these URLs and I to push them all into this sitemap.
So my question is that, isn't there a way to perhaps loop them over? than to insert them into the code one by one like so
array('location' => home_url('www.example.com/used-cars/model/aston-martin'), 'lastmod' => '27/03/2017', 'frequency' => 'auto', 'priority' => '0.8')

A: Here's a stab at it. I'm not sure exactly what in your URL's are taxonomies, or even what your taxonomies are, but basically you'd just have to loop through everything adding to the pages array with the arrays. You'd need to either define all your models in an array, or grab them from the database using something like get_option();
add_filter( 'bwp_gxs_external_pages', 'bwp_gxs_external_pages', 10, 1 );
function bwp_gxs_external_pages($pages)
{
    $models = array( 'aston-martin', 'bmw', 'mercedes-benz' /*...*/ );
    $locations = get_terms( array(
        'taxonomy' => 'location',
        'hide_empty' => true,
    ) );

    // Loop through the search terms
    foreach ( $models as $model ) {
        foreach ( $locations as $location ) {
            $pages[] = array(
                'location' => home_url( '/used-cars/location/' . $location->slug . '/model/' . $model ),
                'lastmod' => '27/03/2017',
                'frequency' => 'auto',
                'priority' => '0.8'
            );
        }
        $pages[] = array(
            'location' => home_url( '/used-cars/model/' . $model ),
            'lastmod' => '27/03/2017',
            'frequency' => 'auto',
            'priority' => '0.8'
        );
    }

   return $pages;
}

Hope this gets you started.


text:
Q: VueJS не обновляет стили элемента Пишу drag-and-drop с возможностью поворота и ресайза на VueJs. Суть работы простая: отслеживаю перемещения мышкой, в соответствии с ними обновляю модель, в которой хранится положение элемента и которая потом отправляется на сервер. Эта модель успешно обновляется при перемещениях мышки, но стили, которые я к ней прикрепил, не обновляются.

console.log при этом пишет, что модель обновляется.
Что я делаю не так? В чём может быть причина?
Заранее спасибо
PS. Попробовал вывести в консоли модель при перемещении мышью - всё норм. Выводит это:

Но watch его не видит (точнее, не видит при перемещении, хотя видит при вставке фото в макет)(на проверку if(this.pageKey === 'photo_cover_main') не обращайте внимания):
layout: function (val) {
    if(this.pageKey === 'photo_cover_main')
        alert()
}

Соответственно, из-за этого не перемещается сама фотка. Почему даже watch не видит - не понимаю
Модель передаётся в этот компонент свойством, а при перемещении фото вызывается $emit на родителя, который обновляет данные
Layout получается запросом к API
$.get('/api/users/order-layout', data => {
     this.layout = data;
});

В родительском компоненте следующий код шаблона:
<hole-view
    v-for="(hole, holeKey) in page.holes_coordinats"
    :hole="hole"
    :hole-key="holeKey"
    :layout="layout.content[pageKey] && layout.content[pageKey][holeKey] ? layout.content[pageKey][holeKey] : {}"
    :page-key="pageKey"
    @moved="movedHoleImageBind"

/>
В дочернем компоненте при перетаскивании объекта мышью после вычисления всех координат вызывается $emit:
this.$emit('moved', top, left, x, y);

В родительском компоненте на событие moved вешается такой обработчик:
movedHoleImageBind(top, left, x, y){
            try{
                this.$set(this.layout.content[this.editingHoleImage.pageKey][this.editingHoleImage.holeKey], 'top', top);
                this.$set(this.layout.content[this.editingHoleImage.pageKey][this.editingHoleImage.holeKey], 'left', left);
            }catch (e) {}
        }

HTML получается такой (сама фотка - div.image-in-layout-slider и img в нём):

A: Убедитесь, что дочерний компонент отправляет необходимые данные:
console.log({top, left, x, y});

this.$emit('moved', top, left, x, y);

Убедитесь, что родительский компонент принимает их, а также, что свойства top и left изначально были прописаны в объектах:
movedHoleImageBind(top, left, x, y){
  console.log({top, left, x, y});

  this.layout.content[this.editingHoleImage.pageKey][this.editingHoleImage.holeKey].top = top;
  this.layout.content[this.editingHoleImage.pageKey][this.editingHoleImage.holeKey].left = left;
}

Общие рекомендации
1 Возможно, что вы не передаёте единицы измерения и обращаетесь к не существующему CSS свойству rotate. Как бы там ни было, свойства лучше перенести в поле computed.

// Отключим ненужные для примера
// сообщения в консоли.
Vue.config.productionTip = false;
Vue.config.devtools = false;

// Дочерний компонент.
const HoleView = {
  props: ['layout'],
  computed: {
    dragStyle() {
      return {
        'top': this.layout.top + 'px',
        'left': this.layout.left + 'px',
        'width': this.layout.width + 'px',
        'transform': 'rotate(' + this.layout.rotate + 'deg)'
      }
    }
  },
  template: `<div class="block" :style="dragStyle">Содержимое блока</div>`
}

new Vue({
  el: '#app',
  components: {
    'hole-view': HoleView
  },
  data: {
    layout: {
      top: 0,
      left: 0,
      width: 288,
      rotate: 0
    },
  }
});
.container {
  max-width: 800px;
  margin: 50px auto;
  position: relative;
}

.form {
  max-width: 800px;
  margin: 50px auto;
  position: relative;
  display: flex;
  flex-wrap: wrap;
}

.label {
  display: block;
}

.block {
  height: 188px;
  box-sizing: border-box;
  border: 1px dashed #888;
  background: rgb(178, 214, 60);
  position: absolute;
}

  <form class="form">

      Слева {{ layout.left }}
      <input type="range" v-model="layout.left">

      Сверху {{ layout.top }}
      <input type="range" v-model="layout.top">

      Ширина {{ layout.width }}
      <input type="range" v-model="layout.width" min="120" max="400">

      Поворот {{ layout.rotate }}
      <input type="range" v-model="layout.rotate" min="0" max="360">

  </form>

    <hole-view :layout="layout"></hole-view>

2 Укажите уникальный атрибут key для каждого элемента, вот так:
<hole-view v-for="(hole, holeKey) in page.holes_coordinats" :key="holeKey" ...>

3 Указывайте глубину слежения за объектом в поле watch:
// ... остальной код

watch: {
  // Коллбэк будет вызываться каждый раз,
  // когда изменяется любое из свойств наблюдаемого объекта.
  layout: {
    handler: 'layoutWatcher',
    deep: true, // независимо от глубины их вложенности.
    immediate: true // коллбэк будет вызван сразу же после начала наблюдения.
  },
}

// ... остальной код

methods: {
  layoutWatcher(newVal, oldVal) {
    // Реализация метода для наблюдателя.
    // ... code
  }
}


text:
Q: pandas not found with python3 command but able to run with python command I have a simple script to read a data and a model and compute score on it.
import pandas as pd
import pickle
from sklearn import metrics
from sklearn.metrics import f1_score

with open('samplemodel.pkl', 'rb') as file:
    model = pickle.load(file)

testdata=pd.read_csv('testdata_l3demo.csv')
X = testdata[['bed','bath']].values.reshape(-1,2)
y = testdata['highprice'].values.reshape(-1,1)

predicted=model.predict(X)

f1score=metrics.f1_score(predicted,y)
print(f1score)

If I run the above script with python3 script.py, it shows me this error:
ModuleNotFoundError: No module named 'pandas'. But if I run python script.py, it works perfectly fine.
I tried to pip list and am able to see pandas 1.4.3.
I am on MacOS and not in any virtual env.
This does not affect anything so far, but I would love to know why and how to fix this.
thank you

A: There are 2 major versions of the Python programming language - python 2 and python 3 - you can find more information here.
Python 2 has been officially discontinued, but stays around for legacy reasons (to support software that has been built on and uses python 2). It also stays on on some OS'es as the default version of python.
Python 3 is where all the latest and greatest developments are happening.
If you do not have a specific, compelling reason to use Python 2 - you should stick with Python 3.
On Operating Systems where both Python 2 and Python 3 are installed, you can distinguish between the two versions with the 3 suffix - e.g. python3 or pip3 or ipython3 etc. In other words, pip install xx would install a python 2 version of the package whereas a pip3 install xx would install a python 3 version.


text:
Q: On the 'Derivation' of line integrals The line integral wikipedia page https://en.wikipedia.org/wiki/Line_integral#Derivation gives derivations for both the formulas of a line integral over a scalar field and a vector field.
Is it really correct to call these derivations? I.e. isn't it the case that line integrals are inherently definitions? That is to say there is no way to prove or derive these formulas, as we just define certain integrals to themselves be what we refer to as 'line integrals'.
In the derivation on wikipedia, am I correct in my understanding that actually the Riemann sum they are deriving is the definition of the line integrals? (and it just so happens that these Riemann sums can be expressed neatly in other equivalent forms)
Is it the case that line integrals are useful definitions rather than important theorems? I am wondering mostly because this is a recent example that came up that highlights my confusion sometimes over what people refer to as proofs or derivations. Is there not an important distinction between what definitions yield important theories vs what can be deduced from those theories? I am not sure if I am reading too much into it or if I am possibly missing something key so that in fact line integrals come from some more fundamental maths; but I don't see this from the derivations given.

A: Of course there are various kinds of line integrals. They all involve a "field" $f$ defined in some region $\Omega\subset{\mathbb R}^d$, $\>d\in\{2,3\}$ in many cases, or $\Omega\subset{\mathbb C}$,  and a curve $\gamma\subset\Omega$. The line integral
$$\int_\gamma f\>d?$$
then wants to capture the "total effect" this $f$ has along $\gamma$.
To arrive at the final definition of such an integral one considers partitions of $\gamma$ into tiny "line elements", the field $f$ (considered constant along such a line element), and is arguing geometrically or physically what the total effect of $f$ along this line element should be. At the end of the discussion (via Riemannian sums) one arrives at a certain integral involving $f$ and a parametric representation of $\gamma$. The whole thing is not a proof, but a motivation why one would consider, e.g., the integral
$$\int_\gamma ds:=\int_a^b\bigl|\gamma'(t)\bigr|\>dt $$
an interesting thing. A posteriori then one would actually prove that this integral is in many interesting cases equal to the length of $\gamma$, the latter defined in geometric terms.
For many such integrals there are indeed theorems that say, these integrals are equal to $2$-dimensional integrals of some derivative of the vector field $f$ over a surface, or they are equal to some "potential difference". But this comes after the setup.
To sum it up: In an article about "line integrals"  a half dozen different line integrals are defined, and their definitions motivated, but there are no proofs of mathematical theorems, like the FTC, or Stokes' theorem.


text:
Q: Getting error while using -c option in mailx command I'm running a script to send a mail with few lines. Requirement is I need to add few people  in cc.
So I have created below scripts. For people who needs to be in TO and CC , I have created 2 separate files as you can see below :

echo Reminder mail sending date!!!
CC_LIST=cat cc_list.maillist
TO_LIST=cat to_list.maillist
echo "$CC_LIST"
echo "$TO_LIST"
cat test_mail.txt |  mailx -r abc@xyz.com -s "subject" "$TO_LIST" -c "$CC_LIST"
So without -c "$CC_LIST", my script running fine but while using -c option it gives error as below :
-c... User unknown
As it seems considering -c as another mailed.
Please help

A: The mailx utility assumes that the operands at the end of the command line are all addresses to send the email to.
Just make sure that all options are specified before any of the recipients' addresses. In other words, swap -c "$CC_LIST" with "$TO_LIST".


text:
Q: How do you set an auth header on an image in react-native? I have images in my react-native application that require authentication.  I have a token that I add to all of my server calls but I don't know how to set it for an Image.  Can I override the loading calling for an image?  Do I have to preload the image using fetch and then provide the result to the Image component?

A: Yes, it is
<Image source={{ uri: 'http://...', headers: {} }} />


text:
Q: How to substrat two timedate columns in python dataframe These are two columns(A & B) in a python data frame
column df['A']
0         2021-05-19 11:21:29.463
1         2021-05-19 11:21:39.127
column df['B']
0         2021-05-19 11:19:27.217
1         2021-05-19 11:19:40.000
by subtracting these two columns df['A'] - df['B'] I need to get minutes and seconds
02:02
01:59
or at least below format
00:02:02
00:01:59

A: This should do it:
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
def date_string(a,b):
    td = (a - b)/np.timedelta64(1, 's')
    td = str(datetime.timedelta(seconds=td))
    return(td[:-7])
df['diff'] = df.apply(lambda x: date_string(x.A, x.B), axis=1)


text:
Q: sitemap on a website only shows one link I have a little issue concerning the sitemap of a website.
The website is : http://parmemarin.com.
If I go on http://www.xml-sitemaps.com/ and try to generate a sitemap for my website I end up with only one link in my sitemap which is _inc/conditions.php
There is no index.php or other of my links (index.php?page=...)
Can someone help me on this one ?
Thanks

A: Well, that could be a problem with xml-sitemaps.com, it could be a problem with your site, or it could be a combination of both. I don't know that service, so I can't tell how it really works and what it does.
Skimming through your markup, I noticed that you linked to some URLs without encoding the ampersand. & (if used for parameters) should be & if you link it in HTML.
I wonder: Why don't you build your sitemap yourself? You are the only one who knows for sure which pages exist on your site. Collect all your URLs and put them in a file, like http://www.sitemaps.org/ describes.

A: thanks, for your answer.
I had totally forgot to delete the meta : no index, no follow ... That clearly didn't helped :)


text:
Q: Visual Studio 2013 Freezes on debug I had problems with visual studio 2013 which was freezing when try to debug the application, I thought this was due to the fact that i have installed visual studio 2012 after vs 2013. So during the troubleshooting i uninstalled vs 2012 and repaired vs 2013 but no luck.
So therefore i decided finally to install fresh windows 8.1 on a new partition on the same drive, then followed by vs 2013 but here as well no luck.
The problem : As soon as i attach the process (w3wp.exe) and refresh the page and once all symbols loaded. Now i have 5 breakdown points on different projects or files. so when i try to double click on the breakpoint and go to that part of the code, visual studio freeze (not responding) for few seconds sometimes it takes up 10 - 15sec to move to the code.
Also before installing the fresh copy windows 8.1, i have upgraded my PC ram to 32GB (Max supported)
I have done the following on my PC.

*

*Ran windows memory test and found no errors.

*Ran memtest86 for 15 hours with 3 passes and no errors.

I am not sure what it could be causing the freezing of the application.
Any help will be appreciated.

A: In my case this happened after I installed Desktop Earth. I've also read that installing Google Earth can cause the same issue.


text:
Q: A recursive function that determines whether the digits of a number are in ascending order I'm practicing recursion and my solution to the problem doesn't seem to work.
I'm trying to write a recursive code that will determine if the digits of a number are in ascending order or not. here's my code:
#include <stdio.h>
int isAscending(int num);
int main(){
    int result;
    result = isAscending(123);//Should print "The number is in ascending order!"
    if (result == 0) {
        printf("The number is in ascending order!\n");
    }
    else {
        printf("The number is not in ascending order!\n");
    }
}
int isAscending(int num) {
    int new = num / 10;
    int result = 0;
    if ((num % 10) == 0) {
        return 0;
    }
    else if ((num % 10) > (new % 10)) {
        result += isAscending(num / 10);
        return result;
    }
    else {
        return 1;
    }
}

A: Here's another (bare-bones) way to go about it. The basic idea is that if we have a single digit, we return affirmative, else we check if the rightmost number is greater than the one just to it's left. And we do this for the remaining digits.
#include <stdio.h>

int isAsc(int i)
{
    int rem = i % 10;    // remainder
    int quo = i / 10;    // quotient

    if (rem == i)
        return 1;
    else if (rem <= (quo % 10))
        return 0;
    else
        return 1 && isAsc(quo);
}

int main(void)
{
    int i = 123123;
    if (isAsc(i))
        printf("%s\n", "Ascending");
    else
        printf("%s\n", "Not ascending");

    return 0;
}

A: Can you please try below recurrsive code:
`
boolean isascending(int num){

if(num == 0) return true;
if(num%10>num%100) return isascending(num/10);
else return false;
}`

or you can use while loop:
while(num>0){
if(num%10 > num%100){
   num = num/10;
   continue;
} return false;
} return true;

A: It would be better to use another parameter to store the last digit, which is going to be "dropped" in the current iteration.
So I came up with the following recursive logic:

*

*use a parameter which stores the last digit dropped

*base case: if the number is 0, return 0 (true)

*calculate the current last digit of the number (number%10)

*if the current last digit is greater than the last digit dropped: is this case, return 1 (false)

*if not, return isAscendingRecursive() on the new number dropping the current last digit and pass it as the next iteration last digit.
Code:
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** args){
    int num=0;
    printf("Insert a number:\n");
    scanf("%d",&num);
    if(isAscending(num)==0)
        printf("Ascending\n");
    else
        printf("Not ascending\n");
}

int isAscending(int num){
    return isAscendingRecursive(num,9);
}

int isAscendingRecursive(int num, int lastDigit){
    if(num == 0)
        return 0;

    int temp = num%10;
    if(temp > lastDigit)
        return 1;
    else
        return isAscendingRecursive(num/10, temp);
}

A: This solution returns 0 on failure otherwise some other integer on success.  It seems that isDescending() is easier to write when returning 0 as a failure value but I contorted this accordingly:
#include <stdio.h>
#include <stdlib.h>

int isAscending(int num) {
    int quotient = num / 10;
    int remainder = num % 10;

    if (quotient != 0) {

        int result = isAscending(quotient);

        if (result == 0 || result >= remainder) {
            return 0;
        }
    }

    return remainder;
}

int main(int argc, char **argv) {
    if (isAscending(atoi(argv[1]))) {
        printf("The number is in ascending order!\n");
    } else {
        printf("The number is not in ascending order!\n");
    }

    return 0;
}

TESTS
% ./a.out 123
The number is in ascending order!
% ./a.out 321
The number is not in ascending order!
% ./a.out 101
The number is not in ascending order!
%

No, it doesn't handle negative numbers!  It also doesn't handle '0' correctly as an input -- other single digit numbers are fine.
Again, isDescending() is easier to write but unfortunately, !isDescending() != isAscending()

A: Your tests are incorrect.  You should return true for numbers with a single digit, false if the last digit is less or equal to the previous one and recurse for the rest:
int isAscending(int num) {
    int new = num / 10;

    if (new == 0) {
        return 1;
    } else
    if (num % 10 <= new % 10) {
        return 0;
    } else {
        return isAscending(new);
    }
}

This kind of recursion is called tail recursion as you return the result of the recursive call.  Good compilers will generate iterative code equivalent to this:
int isAscending(int num) {
    for (;;) {
        int new = num / 10;

        if (new == 0) {
            return 1;
        }
        if (num % 10 <= new % 10) {
            return 0;
        }
        num = new;
    }
}

A: I fixed my code and it works, thanks for the help!:
#include <stdio.h>
int isAscending(int num);
int main(){
    int result;
    result = isAscending(2589);//Should print "The number is in ascending order!"
    if (result == 0) {
        printf("The number is in ascending order!\n");
    }
    else {
        printf("The number is not in ascending order!\n");
    }
}
int isAscending(int num) {
    int new = num / 10;
    int result = 0;
    if ((num % 10) == 0) {
        return 0;
    }
    else if ((num % 10) > (new % 10)) {
        return isAscending(num / 10);
    }
    else {
       return 1 + isAscending(num / 10);
    }
}


text:
Q: JavaScript form value with variable field name simple javascript but can't seem to get it to work.
var number = 5;
var netiteration = "net"+number;  // makes netiteration now equal net5

var formvalue = document.forms.myformname.netiteration.value;

why doesn't this get the value of the form field with the name/id of "net5", in the form "myformname"?
also, I'm working from a 10 year old javascript book, so maybe the syntax has changed?
thanks

A: Try:
var number = 5;
var netiteration = "net"+number;  // makes netiteration now equal net5

var formvalue = document.forms.myformname[netiteration].value;

Your original code was looking for a field called "netiteration" but you want the field that has a name equal to the evaluated value of netiteration.

A: This will not work as netiteration is a variable and you cannot use variable name within the DOM structure of the HTML.
something like following should work....
var form_elements = document.forms.myformname.getAllChildren();
var net_elements = new Array[10];
for(var i=0;i<form_elements.length;i++)
{
   var name = form_elements[i].name;
   if(name.indexOf('net') != -1)
    net_elements[i] = form_elements[i];
}

now, the arraynet_elements has all the elements with the name 'net' in it...
hopes this solves your problem...

A: Came across this and thought I'd enhance it with some extra info in case someone finds it useful.
If you are using id in your form fields, you can reference that way also:
<input type='text' id='myfield1' onclick="Example(1)">
<input type='text' id='myfield2' onclick="Example(2)">

then in your Javascript you reference the field with a variable by:
function Example(myvar){
    var myvalue=document.getElementById('myfield'+myvar);
    console.log('The value is '+myvalue);
}


text:
Q: Gaussian integral $\int_{-\infty}^\infty \exp(-(x+\mathrm iY)^2)\,\mathrm d x$ along $[-R,R]+\mathrm i[0,Y]$
Use integration along $\partial Q$ of $Q=[-R,R]+\mathrm i[0,Y]$ to show that for all $Y\geq 0$ it holds that
$$\int_{-\infty}^\infty \exp(-(x+\mathrm iY)^2)~\mathrm dx = \int_{-\infty}^\infty \exp(-x^2)~\mathrm dx.$$

Similiar to one of my other questions referring to a rectangle I was going to rewrite $\partial Q$ as four curves but the integrands became really complicated. Using the bottom curve of the rectangle I got $\require{cancel}\cancel{\gamma(t)=(1-t)(-R)+tR=R(2t-1)}$ hence
$$\cancel{\int_\gamma\exp(-(x+\mathrm iY)^2)~\mathrm dx =\int_0^1 \exp(-(R(2t-1)+\mathrm iY)^2)\cdot 2R~\mathrm dt}$$
which seems like a very tough integral. I was thinking of a similiar (and more simple) curve $\hat{\gamma}$ using another parametrisation to get easier integrals.
What would be your suggested approach for this problem?

Results of some attempts after getting some help
After much help of πr8 I have the following results for all four curves thus far
$$
\begin{align*}
 \gamma_1(t) &= (1-t)(-R) + tR = R(2t-1)\\
 \gamma_1'(t) &= 2R\\
 \int_{\gamma_1}\exp(-(x+\mathrm iY)^2)\,\mathrm dx
 &= \int_0^1 \exp(-(\underbrace{R(2t-1)}_{u}+\mathrm iY)^2)\cdot 2R\,\mathrm dt\\
 &= \int_{-R}^R \exp(-(u+\mathrm iY)^2)\,\mathrm du
\end{align*}
$$

$$
\begin{align*}
 \gamma_2(t) &= (1-t)R + t(R+\mathrm iY) = R+t\mathrm iY\\
 \gamma_2'(t) &= \mathrm iY\\
 \int_{\gamma_2}\exp(-(x+\mathrm iY)^2)\,\mathrm dx
 &= \int_0^1 \exp(-(\underbrace{R+t\mathrm iY}_{u}+\mathrm iY)^2)\cdot \mathrm iY\,\mathrm dt\\
 &= \int_{R}^{R+\mathrm iY} \exp(-(u+\mathrm iY)^2)\,\mathrm du
\end{align*}
$$

$$
\begin{align*}
 \gamma_3(t) &= (1-t)(R+\mathrm iY) + t(-R+\mathrm iY) = R(1-2t)+\mathrm iY\\
 \gamma_3'(t) &= -2R\\
 \int_{\gamma_3}\exp(-(x+\mathrm iY)^2)\,\mathrm dx
 &= \int_0^1 \exp(-(\underbrace{R(1-2t)+\mathrm iY}_{u}+\mathrm iY)^2)\cdot (-2R)\,\mathrm dt\\
 &= \int_{R+\mathrm iY}^{-R+\mathrm iY} \exp(-(u+\mathrm iY)^2)\,\mathrm du
\end{align*}
$$

So far I could rewrite all integrals to have the same boundaries as the curves used to deduce them. For the last curve however this wasn't as straight-forward as for the other ones (I was eager to have four identical integrands) and I had to use another substitution yielding
$$
\begin{align*}
 \gamma_4(t) &= (1-t)(-R+\mathrm iY) + t(-R) = -R-(t-1)\mathrm iY\\
 \gamma_4'(t) &= -\mathrm iY\\
 \int_{\gamma_4}\exp(-(x+\mathrm iY)^2)\,\mathrm dx
 &= \int_0^1 \exp(-(\underbrace{-R-t\mathrm iY+\mathrm iY}_{u})^2)\cdot \mathrm iY\,\mathrm dt\\
 &= \int_{-R+\mathrm iY}^{-R} \exp(-u^2)\,\mathrm du.
\end{align*}
$$

Is there anything salvageable in the above equations?

A: Since $z\mapsto \exp(-z^2)$ is an entire function, by Cauchy's theorem the integral $\int_{\partial Q} \exp(-z^2)\, dz$ is zero. On the other hand,
$$\int_{\partial Q} \exp(-z^2)\, dz = \left(\int_{-R}^R + \int_R^{R + iY} - \int_{-R + iY}^{R + iY} - \int_{-R}^{-R + iY}\right)\exp(-z^2)\, dz$$
Thus
$$\int_{-R + iY}^{R + iY} \exp(-z^2)\, dz = \int_{-R}^R \exp(-x^2)\, dx + \int_R^{R + iY} \exp(-z^2)\, dz - \int_{-R}^{-R + iY} \exp(-z^2)\, dz\tag{1}$$
Now, the integral along the vertical edges of $Q$ are $O\!\left(\exp(-R^2)\right)$ as $R\to \infty$. Indeed, consider the vertical edge from $R$ to $R + iY$, parametrized by $z = R + it, 0 \le t \le Y$.
$$\left\lvert \int_R^{R + iY} \exp(-z^2)\, dz\right\rvert = \left\lvert\int_0^Y \exp\{-(R + it)^2\}i\, dt\right\rvert \le \int_0^Y \exp\{-(R^2 - t^2)\}\, dt = Ce^{-R^2}$$
where $C = \int_0^Y \exp(t^2)\, dt$. Similarly, $\left\lvert\int_{-R}^{-R + iY} \exp(-z^2)\, dz\right\rvert \le Ce^{-R^2}$. Hence, by $(1)$,
$$\int_{-R+iY}^{R + iY} \exp(-z^2)\, dz = \int_{-R}^R \exp(-x^2)\, dx  + O\!\left(\exp(-R^2)\right) \tag{2}
$$
Parametrizing the horizontal edge $[-R + iY,R + iY]$ via $z = x + iY$, $-R\le x \le R$, we have $\int_{-R + iY}^{R + iY} \exp(-z^2)\, dz = \int_{-R}^R \exp(-(x + iY)^2)\, dx$. Therefore, $(2)$ becomes
$$\int_{-R}^R \exp(-(x + iY)^2)\, dx = \int_{-R}^R \exp(-x^2)\, dx + O\!\left(\exp(-R^2)\right)\tag{3}$$ Letting $R \to \infty$ in $(3)$, the result is established.