text:
Q: INSERT statement works only once I asked something like this earlier, but now I ran better tests, and tried to analyze what the problem was.
This is the ajax request:
  //start ajax request here//
   $.post('purchaseitem.php',{itemAmount:itemAmount, itemId:itemId}, function(data){
    $('.savestatus_'+itemId).text(data);
   });
  //end it here

I echo out all the items in the items table, along with an ahref link and an input field to allow the user to type in the quantity and click buy.
<?php
    $shop_query = mysql_query("SELECT * FROM sector0_item WHERE item_location = '$chapter'");
    while(($shop_row = mysql_fetch_array($shop_query))){
        $itemid = $shop_row['item_id'];
        $item_name = $shop_row['item_name'];
        $item_price = $shop_row['item_price'];
        ?>

<?php echo $item_name; ?>

<?php echo $item_price; ?>

        <input type = 'text' class = "purchaseAmount_<?php echo $itemid;?>" name = "purchaseAmount" />
        <a id = "purchaseButton_<?php echo $itemid; ?>" href = "prevent default();" class = "purchase_button" onclick = "buy(); return false;">Buy
        <div class = 'savestatus_<?php echo $itemid; ?>'>

        <?php
    }
?>

This is a test version of my code, so I know that it is messed up...
The php part:
$user_inventory_query = mysql_query("SELECT * FROM sector0_inventory WHERE id = '$dbid' AND item_id = '$item_id'");
                        $checking_item_inventory = mysql_num_rows($user_inventory_query);
                        if($checking_item_inventory === 0){
                            /*^*/  $insertion_into_inventory = mysql_query("INSERT INTO `sector0_inventory`(`id`, `item_id`, `username`, `item_name`, `quantity`) VALUES ('$dbid','$item_id','$dbuser','$item_name','$purchase_amount')");
                                if($insertion_into_inventory === true){
                                mysql_query("UPDATE sector0_players SET cash = cash-'$total_cost' WHERE id = '$dbid'");
                                echo "Purchase complete";
                                }
                        }else if ($checking_item_inventory === 1){
                            $update_inventory_quantities = mysql_query("UPDATE sector0_inventory SET quantity = quantity+'$purchase_amount' WHERE id = '$dbid' AND item_id = '$item_id'");
                            if($update_inventory_quantities===true) {
                                mysql_query("UPDATE sector0_players SET cash = cash-'$total_cost' WHERE id = '$dbid'");
                                echo "Purchase complete, quantity updated.";
                                }
                        }

The above is the query. the /^/ part is the part that fails.
When I Truncate the table, and click buy, the insertion is completely successful. But for any other item, insertion fails. It's a php, I guess, I am really confused.
relative table to the insert and update queries
CREATE TABLE `sector0_inventory` (
 `id` bigint(20) NOT NULL COMMENT 'The input in this field will be php code exclusive. No increment allowed.',
 `item_id` bigint(20) NOT NULL COMMENT 'The input is also code exclusive',
 `username` varchar(250) NOT NULL COMMENT 'This value will be used to search for the user inventory information. Admin privileges only',
 `item_name` varchar(250) NOT NULL COMMENT 'This value will be used to identify (user side) the item. It will be used by admins to query out when a removal of a specific item is needed',
 `quantity` bigint(20) NOT NULL COMMENT 'This value will be 0 by default BIG int is to allow calculations',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

A: Show the output of CREATE TABLE sector0_item to get more help, but my guess is that your primary key on that table is id and you're trying to specify that manually in your INSERT statement:
INSERT INTO `sector0_inventory`(`id`, `item_id`, `username`, `item_name`, `quantity`) VALUES ('$dbid','$item_id','$dbuser','$item_name','$purchase_amount')

Your primary key must be unique for each row. Try:
INSERT INTO `sector0_inventory`(`item_id`, `username`, `item_name`, `quantity`) VALUES ('$item_id','$dbuser','$item_name','$purchase_amount')

That will work if your id column is set to AUTO INCREMENT.
EDIT: After you posted the table structure, your problem is the database table design. Right now the primary key is id which means you can only have one row per PHP session ID. I don't know your application, but that seems wrong.
If you can delete the table and start from scratch, then DROP the table and re-create it using:
CREATE TABLE `sector0_inventory` (
 `transaction_key` INT NOT NULL AUTO INCREMENT COMMENT 'The unique ID for each row',
 `id` bigint(20) NOT NULL COMMENT 'The input in this field will be php code exclusive.     No increment allowed.',
 `item_id` bigint(20) NOT NULL COMMENT 'The input is also code exclusive',
 `username` varchar(250) NOT NULL COMMENT 'This value will be used to search for the     user inventory information. Admin privileges only',
 `item_name` varchar(250) NOT NULL COMMENT 'This value will be used to identify (user     side) the item. It will be used by admins to query out when a removal of a         specific item is needed',
 `quantity` bigint(20) NOT NULL COMMENT 'This value will be 0 by default BIG int is to     allow calculations',
 PRIMARY KEY (`transaction_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

then restore your PHP back to the way you had it.
Note that this will forfeit all of your data in that table...


text:
Q: compacts subsets of $\mathbb{C}$ can be achieved by compact operators? If $B \subset \mathbb{C}$ compact. Is it true that given a hilbert space H we can find a bounded operator L on H such that Im(L) = B ? I have a feeling that statement is correct?

A: Im (L) is a vector space and $B$ is not a vector spaen (except when it is $\{0\}$. So  this is impossible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix "Expression type '@lvalue CGRect/CGSize' is ambiguous without more context"? I have an existing codebase that was written in Swift 3 and Xcode 9 that I am having trouble migrating to Xcode 10 and Swift 4.2 due to build errors within the code.
The problem I am running into now is this:
"Expression type '@lvalue CGRect' is ambiguous without more context"
I am getting this error in 3 different areas of my code. The fourth one is related but different in that it says:
"Expression type '(CGSize) -> CGSize' is ambiguous without more context"
I have tried changing all values within the expression to explicitly use the data type CGFloat to remove any inferred data type errors, and this still did not fix the problem.
 override func sizeThatFits(_ size: CGSize) -> CGSize {
    let adjustedHeight = 8.0 + titleLabel.frame.height + 2.0 + underlineView.frame.height
    adjustedHeight += 16.0 + mapImageView.frame.height + 16.0
    return CGSize(width: bounds.width, height: adjustedHeight)
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    let adjustedHeight = 10.0 + titleLabel.frame.height + 15.0 + daysRoundedView.frame.height
    adjustedHeight += daysTextLabel.frame.height + 10.0 + logoImageView.frame.height + 20.0
    return CGSize(width: size.width, height: adjustedHeight)
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    let adjustedHeight = 8.0 + titleLabel.frame.height + 2.0
    adjustedHeight += underlineView.frame.height + 16.0 + flyerImageView.frame.height + 16.0
    return CGSize(width: bounds.width, height: adjustedHeight)
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    let adjustedHeight = 8.0 + titleLabel.frame.height + 2.0 +  underlineView.frame.height + 16.0
    adjustedHeight += descriptionTextView.sizeThatFits(CGSize(width: size.width - 40, height: size.height)).height + 16.0
    return CGSize(width: bounds.width, height: adjustedHeight)
}

The issue is with the adjustedHeight variable. I'm not sure if a different function or syntax is used in Swift 4.2 for this but I cannot seem to fix this error.

A: One of the issues is that adjustedHeight is a let, but it's being modified in the next line with the += operator. Does the issue get fixed after you change adjustedHeight to var?


text:
Q: redirect logger output to a textpane in java how to redirect org.apache.commons.logging output to a JTextArea??
I successfully redirected sys.err and sys.out using MessageConsole. its working fine. but I am not getting log output in textarea

A: Since it seems that you know how to redirect standard streams where you want them, one possible action is to make a PrintWriter in your logger, redirect the PrintWriter to the MessageConsole, and have the logger print any output to the PrintWriter so it will get redirected.


text:
Q: Coin tossing game - probabilities of $(K,K,K)$ and $(Z,K,Z)$
Let's consider the following game of two players:
A fair coin is tossed as long as no one has won. Player $A$ wins if the sequence $(Z,K,Z)$ appears and player $B$ wins if $(K,K,K)$ appears. What is the probability that $A$ wins?

(Note: To solve this problem we are only allowed to use the notion of conditional probability, law of total probability and bayes theorem!)

My approach:
Let be $P(A)$ the probability that $A$ wins. I am not sure how to tackle this problem in a rigorous way because I am not able to find an appropriate probability space. What I could do is assume that we are at some stage of the game where nobody has won. Then, we define two sets
\begin{align*}
&B_{K}:=\{\omega_1=K,\omega_2\in\{Z,K\},\omega_3\in\{Z,K\},\dots\}\\
&B_{Z}:=\{\omega_1=Z,\omega_2\in\{Z,K\},\omega_3\in\{Z,K\},\dots\}.
\end{align*}
Those two sets are obviously disjoint and all future sequences are either member of $B_{K}$ or $B_{Z}$. Further, we can easiliy see that there exists a bijection between both sets.
Is it correct if I simply define a sample space $\Omega$ which consists of all future sequences that either start with $K$ or $Z$? This would mean that $P(B_{K})+P(B_{Z})=1$ and $P(B_{K})=P(B_{Z})=0.5$ and allows us to apply the law of total probability
$$
P(A)=P(A\mid B_{K}) P(B_{K})+P(A\mid B_{Z}) P(B_{Z})=0.5\cdot(P(A\mid B_{K}) +P(A\mid B_{Z})).
$$

Is this the way to go? It doesn't feel rigorous because of two things.
1.) The sample space is only valid for some arbitrary stage of the game - not the whole game.
2.) How do I know that there exists a probability function which I can use? The sample space I have defined is not countable, so I don't know if I can assign a probability to each element of $\Omega$?

A: Following Lulu's suggestion, let us first define the states  on last toss(es):
$S$ = starting toss, $\,A1\equiv$ first $Z$, $A2\equiv$ $ZK$, $\,B1\equiv$ first $K$, $\,B2\equiv KK$,
Then tracing movement step-by-step from one state to another, we have
$S =  .5A1+.5B1$
$A1=  .5A2 +.5A1$
$A2= .5*1 +.5B2\quad$ [Either we get ZKZ and are done, or go to $B2$]
$B1= .5B2+.5A1$
$B2= .5*0 +.5A1\;$ [We bar $KKK$ as we compute for $A$'s win ]
Note that these equations involve using conditional probabilities
Solving these equations, we get $S = P(A\;wins)=\frac7{12}$
As a countercheck,
if we exchange the multiplier $1$ and $0$ in the equations for $A2$ and $B2$,
we get P(B wins) $= \frac5{12}$


text:
Q: How can I add and modify shapes in an Excel file using Python Does anyone know a way of getting around the fact that shapes are not supported in openpyxl?
Is there a different library or code that I can use to achieve this??
I tried manipulating an excel file that had shapes and when my app saved the file, the shapes were gone.

A: Try xlwings library. It has the ability to add and modify shapes.
For example:
import xlwings as xw

wb = xw.Book('example.xlsx')
sht = wb.sheets[0]
sht.shapes.add_shape(1, 1, 2, 2, 'circle')
wb.save()

More information here https://docs.xlwings.org/en/stable/api.html#shapes


text:
Q: CSS3 dropdown menu not working anymore Ive been making a website with a CSS3 menu. However during the validating process to check if i made no mistakes i broke my CSS3 menu. The menu itself works but theres no drop down menu when hovering "Categorieen" like it did before.
Heres the HTML:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<title>Website Ronald</title>

<link rel="stylesheet" href="style.css"/>

Home

Categorieën

Vliegvelden

Landschappen

<a href="Sub/Auto`s.html" target="frame_a">Auto`s

Over

And this is the CSS im using:
     #menu, #menu ul {
margin: 0;
padding: 0;
list-style: none;
}
#menu {
width: 960px;
margin: 10px auto;
border: 1px solid #222;
background-color: #111;
background-image: linear-gradient(#444, #111);
border-radius: 6px;
box-shadow: 0 1px 1px #777;
}
 #menu:before,
 #menu:after {
content: "";
display: table;
}

#menu:after {
clear: both;
}

#menu {
zoom:1;
}
#menu li {
float: left;
border-right: 1px solid #222;
box-shadow: 1px 0 0 #444;
position: relative;
}

#menu a {
float: left;
padding: 12px 30px;
color: #999;
text-transform: uppercase;
font: bold 12px Arial, Helvetica;
text-decoration: none;
text-shadow: 0 1px 0 #000;
}

#menu li:hover > a {
color: #fafafa;
}

*html #menu li a:hover { /* IE6 only */
color: #fafafa;
}
#menu ul {
margin: 20px 0 0 0;
_margin: 0; /*IE6 only*/
opacity: 0;
visibility: hidden;
position: absolute;
top: 38px;
left: 0;
z-index: 1;
background: #444;
background: linear-gradient(#444, #111);
box-shadow: 0 -1px 0 rgba(255,255,255,.3);
border-radius: 3px;
transition: all .2s ease-in-out;
}

#menu li:hover > ul {
opacity: 1;
visibility: visible;
margin: 0;
}

#menu ul ul {
top: 0;
left: 150px;
margin: 0 0 0 20px;
_margin: 0; /*IE6 only*/
box-shadow: -1px 0 0 rgba(255,255,255,.3);
}

#menu ul li {
float: none;
display: block;
border: 0;
_line-height: 0; /*IE6 only*/
box-shadow: 0 1px 0 #111, 0 2px 0 #666;
}

#menu ul li:last-child {
box-shadow: none;
}

#menu ul a {
padding: 10px;
width: 130px;
_height: 10px; /*IE6 only*/
display: block;
white-space: nowrap;
float: none;
text-transform: none;
}

#menu ul a:hover {
background-color: #0186ba;
background-image: linear-gradient(#04acec, #0186ba);
}
#menu ul li:first-child > a {
border-radius: 3px 3px 0 0;
}

#menu ul li:first-child > a:after {
content: '';
position: absolute;
left: 40px;
top: -6px;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid #444;
}

#menu ul ul li:first-child a:after {
left: -6px;
top: 50%;
margin-top: -6px;
border-left: 0;
border-bottom: 6px solid transparent;
border-top: 6px solid transparent;
border-right: 6px solid #3b3b3b;
}

#menu ul li:first-child a:hover:after {
border-bottom-color: #04acec;
}

#menu ul ul li:first-child a:hover:after {
border-right-color: #0299d3;
border-bottom-color: transparent;
}

#menu ul li:last-child > a {
border-radius: 0 0 3px 3px;
}

A: Since your submenu must appear while hovering "Categorieen" and since your css to make it visible look like #menu li:hover > ul
The
 element containing your submenu must be inside the
 representing "Categorieen"
So instead of

    Categorieën

Vliegvelden

Landschappen

<a href="Sub/Auto`s.html" target="frame_a">Auto`s

You should have

    Categorieën

Vliegvelden

Landschappen

<a href="Sub/Auto`s.html" target="frame_a">Auto`s

Here is the jsfiddle representing your corrected menu


text:
Q: Incorrect rows returned by webshop filter I have a table called products with the fields ID, NAME, URL, BRAND
Then I have a field called product_filter with the fields ID, PRODUCT_ID, TYPE, VALUE
Lets assume I have the following products table
1  |  PRODUCT 1  |  product-1  |  Brand 1
2  |  PRODUCT 2  |  product-2  |  Brand 2
3  |  PRODUCT 3  |  product-3  |  Brand 1
and the product_filter table
1  |  1  |  material  |  wool
2  |  1  |  material  |  cotton
3  |  2  |  material  |  cotton
4  |  3  |  material  |  wool
5  |  1  |  season    |  fall
5  |  2  |  season    |  fall
5  |  1  |  season    |  all
etc etc
Now when a customer is on the webpage and trying to filter on
material : wool, cotton
season   : fall
That my result is product 1 (has both materials and correct season) and product 2 (has 1 material and the correct season).
I tried this with a join
SELECT DISTINCT(shop_product.product_number), `shop_product`.`color_count`, `shop_product`.`category_id`, `shop_product`.`in_stock`, `shop_product`.`url_image`, `shop_product_description`.* FROM (`shop_product`) JOIN `shop_product_description` ON `shop_product`.`id` = `shop_product_description`.`product_id` JOIN `shop_category_description` ON `shop_product`.`category_id` = `shop_category_description`.`category_id` INNER JOIN `shop_filters` ON `shop_product`.`id` = `shop_filters`.`product_id` WHERE `shop_product`.`status` = 1 AND `shop_product_description`.`language_id` = '1' AND `shop_category_description`.`language_id` = '1' AND ( (shop_filters.type = '1' AND shop_filters.keyword = 'cotton') OR (shop_filters.type = '1' AND shop_filters.keyword = 'wool') ) AND (shop_filters.type = '2' AND shop_filters.keyword = 'fall') ORDER BY shop_product`.`url_image` asc, `shop_product_description`.`name` desc LIMIT 36

I used Distinct to get 1 oer product back (because of product 1 having both materials).
But I get no results until I change
( (shop_filters.type = '1' AND shop_filters.keyword = 'cotton') OR (shop_filters.type = '1' AND shop_filters.keyword = 'wool') ) AND (shop_filters.type = '2' AND shop_filters.keyword = 'fall')

to
( (shop_filters.type = '1' AND shop_filters.keyword = 'cotton') OR (shop_filters.type = '1' AND shop_filters.keyword = 'wool') ) OR (shop_filters.type = '2' AND shop_filters.keyword = 'fall')

However my results are then products with Cotton or Wool OR fall.
If someone have suggestions, idea's then please ...

A: You need to match up multiple times against the filters table, to check against each filter. Easiest it probably to do multiple joins.
SELECT DISTINCT(shop_product.product_number), shop_product.color_count, shop_product.category_id, shop_product.in_stock, shop_product.url_image, shop_product_description.*
FROM (shop_product)
JOIN shop_product_description ON shop_product.id = shop_product_description.product_id
JOIN shop_category_description ON shop_product.category_id = shop_category_description.category_id
INNER JOIN shop_filters sf1 ON shop_product.id = sf1.product_id
INNER JOIN shop_filters sf2 ON shop_product.id = sf2.product_id
WHERE shop_product.status = 1 AND shop_product_description.language_id = '1'
AND shop_category_description.language_id = '1'
AND ( (sf1.type = '1' AND shop_filters.sf1 = 'cotton') OR (sf1.type = '1' AND sf1.keyword = 'wool') )
AND (sf2.type = '2' AND sf2.keyword = 'fall')
ORDER BY shop_product.url_image asc, shop_product_description.name desc LIMIT 36


text:
Q: class is-a-JPanel when it should have-a When Netbeans extends JPanel, does that create problems when referencing instances of the auto-generated class because it uses inheritance rather than composition?
Because Netbeans declares JPanels as private javax.swing.JPanel overview; the instance then has a type of JPanel, when it should have a type of Overview.
How can I invoke the setGroup method and yet keep Overview as an autogenerated JPanel?  I try as so:
Main.java
private void groupsPropertyChange(java.beans.PropertyChangeEvent evt) {
    String s = evt.getNewValue().toString();
    LOG.fine("new group: " + s);
    overview.setGroup(s);
}

with Overview.java:
public class Overview extends javax.swing.JPanel {

...

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

}

but get this compile error:
init:
Deleting: /home/thufir/NetBeansProjects/SwingNNTP/build/built-jar.properties
deps-jar:
Updating property file: /home/thufir/NetBeansProjects/SwingNNTP/build/built-jar.properties
Compiling 1 source file to /home/thufir/NetBeansProjects/SwingNNTP/build/classes
warning: [options] bootstrap class path not set in conjunction with -source 1.5
/home/thufir/NetBeansProjects/SwingNNTP/src/net/bounceme/dur/nntp/view/Main.java:59: error: cannot find symbol
        overview.setGroup(s);
  symbol:   method setGroup(String)
  location: variable overview of type JPanel
1 error
1 warning
/home/thufir/NetBeansProjects/SwingNNTP/nbproject/build-impl.xml:628: The following error occurred while executing this line:
/home/thufir/NetBeansProjects/SwingNNTP/nbproject/build-impl.xml:285: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)

A: A JPanel with a suitable layout is a convenient Container for one or more JComponent instances. It provides a (basic) UI delegate and double buffering, but little else. Custom components should probably extend JComponent directly. The infrastructure for an (optional) UI delegate is shown here. You can add such custom components to the designer palette as discussed here.

A: Well, I guess Netbeans doesn't have such an option of declaring a JPanel created with the GUI as any type other than JPanel, which is kinda odd. Why extend JPanel if, staying with the Netbeans GUI builder, you can't instantiate a sub-class of JPanel with that extended type?  Not that extending JPanel is intrinsically a good idea...
solution code:
package net.bounceme.dur.nntp.view;

import java.util.logging.Logger;
import javax.swing.JTabbedPane;

public class MyTabs extends JTabbedPane {

    private static final Logger LOG = Logger.getLogger(MyTabs.class.getName());
    private Overview overview = new Overview();
    private Detail details = new Detail();
    private Groups groups = new Groups();

    public MyTabs() {
        this.add("groups", groups);
        this.add("overview", overview);
        this.add("detail", details);

        groups.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String s = evt.getNewValue().toString();
                LOG.fine(s);
                overview.setGroup(s);
            }
        });

    }
}

I'm just curious if there's some better way of doing this, other than not using the GUI builder.


text:
Q: VS 2012 Cannot generate dependency graph due to apostrophe I've inherited an existing project for which I'm trying to generate some useful documentation- at this point, a dependency graph.  It's a Visual Studio project, so I'd like to take advantage of the built-in architecture and analysis tools.
Unfortunately, the graph generator isn't working.  Apparently it uses SQLServer Express on the back end.  I'm blessed to be Irish, with an apostrophe in my name.  Punctuation inside names has never occurred to the Visual Studio team, so the dependency database creation fails due to a parse error- it's treating the apostrophe as a string delimiter.
I'm not quite sure why my real name matters to creating this graph.  Nor am I sure how to change it for just this purpose.  I certainly don't want to rename myself.  Is there a hack around this problem?  The error screen mentions "Open the XML Editor to fix these errors", but that just presents an unpopulated XML structure.
The exact error (name redacted):
Invalid usage of the option (NAME AFTER APOSTROPHE) in the CREATE/ALTER DATABASE statement.
Call Stack:
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.Repository.SqlInteraction.InternalExecuteBatch(SqlConnection connection, SqlTransaction transaction, String script, Int32 timeoutInSec)
   at Microsoft.Repository.SqlInteraction.<>c_DisplayClass16.b_15()
   at Microsoft.Repository.SqlInteraction.ExecuteRepositoryAction(Action action)
   at Microsoft.Repository.SqlInteraction.ExecuteBatch(SqlConnection connection, SqlTransaction transaction, String script, Int32 timeoutInSec)
   at Microsoft.Repository.DatabaseCreator.CreateEmptyDatabase(SqlConnection masterConnection)
   at Microsoft.Repository.RenamingDatabaseCreator.CreateEmptyDatabase(SqlConnection masterConnection)
   at Microsoft.Repository.DatabaseCreator.b_0(SqlConnection masterConn)
   at Microsoft.Repository.SqlInteraction.<>c_DisplayClass9.b__7()
   at Microsoft.Repository.SqlInteraction.ExecuteRepositoryAction(Action action)
   at Microsoft.Repository.SqlInteraction.UsingConnection(SqlConnection sqlConnection, Action1 act)
   at Microsoft.Repository.SqlInteraction.UsingMasterConnection(String connectionString, Action1 act)
at Microsoft.Repository.DatabaseCreator.Microsoft.Repository.IDatabaseCreator.CreateDatabase(String connectionString)
   at Microsoft.VisualStudio.Progression.CacheUtilities.InternalCreateCache(String cacheConnectionString, String localCacheDirectory, ActionContext context)
   at Microsoft.VisualStudio.Progression.CacheUtilities.EnsureCacheExists(String cacheConnectionString, String localCacheDirectory, ActionContext context)
   at Microsoft.VisualStudio.ArchitectureTools.ProgressiveReveal.CheckSizeThenPopulateCommand.Execute(ActionContext context, IGraphStatus statusReporter, IProgressionCacheSettings settings)
   at Microsoft.VisualStudio.ArchitectureTools.ProgressiveReveal.ProgressiveRevealProvider.PopulateCodeRepositoryHandler(ActionContext context)
   at Microsoft.VisualStudio.Progression.ActionManager.CallNormalActions(Action action, ActionContext actionContext)
   at Microsoft.VisualStudio.Progression.ActionManager.InternalExecuteAction(Object context)


text:
Q: Checking proxies with python I want to check if a proxy is alived or not using python. To do that, my approach was to use request like:
import requests

proxies = []

for i in proxies:
    prox = {"prox": f"http://{i}"}
    r = requests.get("http://google.es", proxies=prox, timeout=5)

    latency = r.elapsed
    latency = int(latency.total_seconds() * 1000)
    print(r.status_code)

So I was happy with this solution, but then I found out that using a different approach the result was different. With this request code I obtain status_code = 200 and latencies < 100 for a list of 10 proxies. However, if I use ProxyChecker which is based on pycurl:
from proxy_checker import ProxyChecker

for i in proxies:
    print(i)
    a = checker.check_proxy(i)
    print(a)

for the same list only 3 out of 10 are working. My question is: Why is there this difference? What's wrong with my request approach? or why requests says it found google using these proxies?
EDIT
Do not use ProxyChecker version 0.6. It's outdated and 50% of the time does not work. Check this version https://github.com/Scolymus/proxy-checker-python

A: As I was told, the reason is the following:
The proxy-checker is using a custom header, which has a specific value (lel). Requests is not using this header by default.
Here is the proxy-checker code:
def check_proxy(self, proxy):
    if not proxy:
        return None
    try:
        #if self.headers:
        #    curl.setopt(pycurl.HTTPHEADER, self.headers.items())
        curl.setopt(pycurl.PROXY, proxy)
        curl.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13')
        curl.setopt(pycurl.URL, self.check_url)
        curl.perform()

        if curl.getinfo(pycurl.HTTP_CODE) == 200:
            return True
        else:
            return False
    except pycurl.error as e:
        return False

You can test the same proxies with the same custom header by adding it to your headers dictionary:
    ...
    headers = {'lel': 'lel'}
    r = requests.get("http://google.es", headers=headers, proxies=prox, timeout=5)
    ...


text:
Q: How to select first alphabet of a word using SQL? If the word spells let's say Doctor. How can I return the alphabet D enclosed within parenthesis as follows:
(D)
I managed to find: SELECT LEFT(<column_name>, 1) FROM <table_name>
but it only returns D (not enclosed within parenthesis)

A: You may use string concatenation here:
SELECT CONCAT('(', LEFT(col, 1), ')')
FROM yourTable;


text:
Q: (MySQL) Greatest Number By group Inner join , performance problems 2 tables are still very small compared on how they will be in the future.
Already on doing tests on some regular queries , performance problems arise.
Could someone enlighten me on a better table structure or query ?
====
Table 1 : tv_show    ( currently 117 rows)
Table 2 : tv_episodes ( currently 43,000 rows ).
tv_show contains an id , which we call t_id on tv_episodes.
tv_episodes contains this t_id and a field called episodes_num.
each episode has an episode number and a season number , episodes_num is the total episode number regardless of the season.
for example : all seasons have 10 episodes: Season 2 episode 1 = episodes_num: 11
Now for the query :
 I want for each tv show the latest episodes_num.
SELECT tv.*,ep.* FROM tv_show tv
INNER JOIN tv_episodes ep ON ( tv.id = ep.t_id )
LEFT OUTER JOIN tv_episodes ep2
ON ( tv.id = ep2.t_id AND ep.episode_num < ep2.episode_num )
WHERE ep2.t_id is NULL

This works , but gives the server a very hard time   ( query above 10 sec!)
Please help.
Edit : MySQL version: *5.1.47
Update : Thanks for al the solutions , this is the one which is the fastest.
    SELECT tv_episodes.* ,tv_show.*

    FROM tv_episodes
    INNER JOIN
    (
        SELECT t_id, MAX(episode_num) AS episode_num

        FROM tv_episodes
        GROUP BY t_id
    ) max_eps
    ON tv_episodes.t_id = max_eps.t_id AND tv_episodes.episode_num = max_eps.episode_num
  INNER JOIN
 tv_show ON tv_show.id=tv_episodes.t_id

CREATE TABLE `tv_show` (
 `id` int(255) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `specification` varchar(50) NOT NULL,
 `year` int(4) NOT NULL,
 `status` varchar(100) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `name` (`name`),
 KEY `specification` (`specification`),
 KEY `year` (`year`),
 KEY `status` (`status`)
) ENGINE=MyISAM AUTO_INCREMENT=118 DEFAULT CHARSET=latin1

CREATE TABLE `tv_episodes` (
 `id` int(255) NOT NULL AUTO_INCREMENT COMMENT 'e_id',
 `t_id` int(200) NOT NULL,
 `season` int(2) NOT NULL,
 `episode` int(4) NOT NULL,
 `episode_num` int(10) NOT NULL,
 `airing` date NOT NULL,
 `online` enum('1','2') NOT NULL COMMENT '1=yes 2=no',
 `added` int(15) NOT NULL,
 `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`),
 KEY `t_id` (`t_id`),
 KEY `season` (`season`),
 KEY `episode` (`episode`),
 KEY `season_num` (`episode_num`),
 KEY `airing` (`airing`),
 KEY `added` (`added`)
) ENGINE=MyISAM AUTO_INCREMENT=43420 DEFAULT CHARSET=latin1

A: Query performance is not just a function of how the query is structured but also what indexes have been defined on the underlying tables.

A: Update: Based on your latest comments and my own tweaking, I've edited my answer.
This should return the tv_episode records for each tv_id having the maximum episodes_num
SELECT tv_episodes.*
FROM tv_episodes
INNER JOIN
(
    SELECT t_id, MAX(episodes_num) AS episodes_num
    FROM tv_episodes
    GROUP BY t_id
) max_eps
ON tv_episodes.t_id = max_eps.t_id AND tv_episodes.episodes_num = max_eps.episodes_num;

A: If you use MSSQL 2005 of higher (you did not specify the database system and version), you can use "APPLY" clausule:
SELECT
    tv.*,ep.*
FROM tv_show tv
CROSS APPLY (
    SELECT TOP 1 * FROM tv_episodes
        WHERE t_id = tv.id
        ORDER BY episode_num DESC
) ep

A: UPDATE : Try This -
Select tv.name as Tv_Show_Name,Max(episode_num) as Latest_Episode_Number from tv_show tv inner join tv_episode te
on tv.id=te.t_id
group by te.t_id,tv.name,episode_num

A: Try this:
SELECT tv.*,ep.* FROM tv_show tv
INNER JOIN episodes ep ON ( tv.id = ep.t_id )
WHERE ep.episode_num > ALL(SELECT x.episode_num FROM tv_episodes x WHERE x.episode_num != ep.episode_num)


text:
Q: Managed Object Context and data fetch order When I perform executeFetchRequest(NSFetchRequest) on the managed object context, does it always return the NSManagedObjects in the same order or not? What's the default return order?

A: Collections in Core Data are always stored as unordered (NS)Set type for performance reasons.
If you need a specific order provide a sort descriptor in the fetch request.


text:
Q: change values of column to consecutive integers I have a CSV where the first column is my subject ID number,
there's a total of 311 subjects, and on average 1000 values per subject.
The subject ID numbers are quite random (although integers only) ranging from 72 to 2265988.
What I would like to do is neatly rename them to numbers 1-311.
What would be the quickest way to do this in R, preferably, or in excel?

A: OK. Here is your solution. You just replace with your names:
df <- data.frame(ID = c(1,3,5,3,6,7),
             var = c(3,6,8,5,7,8))

temp <- data.frame(old_id = sort(unique(df$ID)),
              new_id =seq(1,5))

replace_ID <-  temp$new_id[match(df$ID, temp$old_id)]
df$ID <- replace_ID
df


text:
Q: How to have 2 arrays of variables in one document I've used an example from
Create an array of variables
By adding a new \newcommand as in the code below:
\documentclass{article}
\usepackage{etoolbox}

\newcounter{cnt}
\newcommand\textlist{}
\newcommand\settext[2]{%
  \csdef{text#1}{#2}}
\newcommand\addtext[1]{%
  \stepcounter{cnt}%
  \csdef{text\thecnt}{#1}}
\newcommand\gettext[1]{%
  \csuse{text#1}}

\newcounter{newcnt}
\newcommand\newtextlist{}
\newcommand\setnewtext[2]{%
  \csdef{text#1}{#2}}
\newcommand\addnewtext[1]{%
  \stepcounter{newcnt}%
  \csdef{text\thenewcnt}{#1}}
\newcommand\getnewtext[1]{%
  \csuse{text#1}}

\begin{document}

\addtext{one}
\addtext{two}
\addtext{three}
\settext{100}{one hundred}

 This is text \gettext{1} and \gettext{3}, that is text \gettext{2}.
 100 is \gettext{100}.\\

 Add new info into newtext.
\addnewtext{four}
\addnewtext{five}
\addnewtext{six}
\setnewtext{100}{seven hundred}

 This is newtext \getnewtext{1} and \getnewtext{3}, that is newtext \getnewtext{2}.

 100 is \getnewtext{100}.\\

 This is text \gettext{1} and \gettext{3}, that is text \gettext{2}.
 100 is \gettext{100}.\\

\end{document}

The first call of gettext will give a correct answer: One, two, three.
But the second gettext will get data same as getnewtext above it: Four, Five, six.
How can I make it back as before which is One, Two, Three?
Thank You.

A: Use newtext#1 etc. rather than text#1 etc. in the second list. These are defining macro names. You want them to be unique or you'll overwrite the old definitions.
Oh, and don't use \\ to break lines in ordinary contexts (outside tabular, array etc.).
\documentclass{article}
\usepackage{etoolbox}

\newcounter{cnt}
\newcommand\textlist{}
\newcommand\settext[2]{%
  \csdef{text#1}{#2}}
\newcommand\addtext[1]{%
  \stepcounter{cnt}%
  \csdef{text\thecnt}{#1}}
\newcommand\gettext[1]{%
  \csuse{text#1}}

\newcounter{newcnt}
\newcommand\newtextlist{}
\newcommand\setnewtext[2]{%
  \csdef{newtext#1}{#2}}
\newcommand\addnewtext[1]{%
  \stepcounter{newcnt}%
  \csdef{newtext\thenewcnt}{#1}}
\newcommand\getnewtext[1]{%
  \csuse{newtext#1}}

\begin{document}

\addtext{one}
\addtext{two}
\addtext{three}
\settext{100}{one hundred}

 This is text \gettext{1} and \gettext{3}, that is text \gettext{2}.
 100 is \gettext{100}.

 Add new info into newtext.
\addnewtext{four}
\addnewtext{five}
\addnewtext{six}
\setnewtext{100}{seven hundred}

 This is newtext \getnewtext{1} and \getnewtext{3}, that is newtext \getnewtext{2}.

 100 is \getnewtext{100}.

 This is text \gettext{1} and \gettext{3}, that is text \gettext{2}.
 100 is \gettext{100}.

\end{document}

A: You can maintain as many arrays (actually property lists) as you want, with a consistent interface with expl3.
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

% 1. The user interface
% 1a. \additem[<name>]{<text>}
\NewDocumentCommand{\additem}{ O{default} m }
 {
  \ramiza_array_add:nnn { #1 } { } { #2 }
 }
% 1b. \setitem[<name>]{<slot>}{<text>}
\NewDocumentCommand{\setitem}{ O{default} m m }
 {
  \ramiza_array_add:nnn { #1 } { #2 } { #3 }
 }
% 1c. \getitem[<name>]{<slot>}
\DeclareExpandableDocumentCommand{\getitem}{ O{default} m }
 {
  \ramiza_array_get:nn { #1 } { #2 }
 }

% 2. The internal functions
\cs_new_protected:Nn \ramiza_array_add:nnn
 {% if the array doesn't exist yet, allocate it with its related counter
  \prop_if_exist:cF { g_ramiza_array_#1_prop }
   {
    \prop_new:c { g_ramiza_array_#1_prop }
    \int_new:c { g_ramiza_array_#1_int }
   }
  \tl_if_empty:nTF { #2 }
   {% with \additem we step the counter and set the next slot
    \int_gincr:c { g_ramiza_array_#1_int }
    \prop_gput:cvn { g_ramiza_array_#1_prop } { g_ramiza_array_#1_int } { #3 }
   }
   {% with \setitem we set the requested slot
    \prop_gput:cnn { g_ramiza_array_#1_prop } { #2 } { #3 }
   }
 }
\cs_generate_variant:Nn \prop_gput:Nnn { cv }

\cs_new:Nn \ramiza_array_get:nn
 {% retrieve the requested item
  \prop_item:cn { g_ramiza_array_#1_prop } { #2 }
 }
\ExplSyntaxOff

\begin{document}

\additem{one}
\additem{two}
\additem{three}
\setitem{100}{one hundred}

This is text \getitem{1} and \getitem{3}, that is text \getitem{2}. 100 is \getitem{100}.

Add new info into newtext.
\additem[new]{four}
\additem[new]{five}
\additem[new]{six}
\setitem[new]{100}{seven hundred}

This is newtext \getitem[new]{1} and \getitem[new]{3}, that is newtext \getitem[new]{2}.

100 is \getitem[new]{100}.

This is text \getitem{1} and \getitem{3}, that is text \getitem{2}. 100 is \getitem{100}.

\end{document}

There is a "default" array, which you access without the optional argument to \additem, \setitem or \getitem; as soon as you use the optional argument to \additem or \setitem, a new array is allocated, to be used with \getitem.


text:
Q: Find peaks (notch & diastole peak) I have the following plot from some data using Python:
Plotted max-min peak:

I'm trying to find another peak between below threshold (maximum of peaks) and up from minimum of peaks. Which is 'o' an 'x' in the picture. By the way, I've filtered the noise and use SciPy.signal find_peak for both (maximum and minimum peak). I was wondering if I can use the same method but looking the peak between below threshold (maximum of peaks) and up from minimum of peaks. Is it possible?


text:
Q: Extracting blocks of text from RST documents,files by :ref:? I have a rst file SWAP.rst and i need to extract some specific data and put in a dictionary.
the file looks like this:
:baseID: SWAP_DF

The current used for the force ...

.. requirement::SWAT_FD_AR_Force.432
   :c_This_is_a: functional
   :c_Release: AR_V2.RC
   :c_Maturity: accepted
   :c_Implementation: implemented

   text text text text
   tables

.. comment:: SDASD.471
   :c_This_is_a: functional
   :c_Release: adm_28.1
   :c_Implementation: implemented

   text tables etc

.. requirement:: SWAT_FD_AR_Force.231
   :c_This_is_a: non-functional
   :c_Release: AP_V1_RD1
   :c_Maturity: accepted
   :c_Implementation: implemented

   text, tables ,etc

And i need to extract all the requirement sections and put in a dictionary using python, docutils

A: You will have to implement Directive classes for comment and requirement directives, so that you can translate the rst document into a doctree, which you can then translate into desired dictionary form.


text:
Q: Is there a better way to get only numeric value in php array without using for loop Here's the an example of array that has non-numeric value.
$categoryRating =

 array:3 [
  1 => 60.0
  2 => 50.0
  5 => "in-progress"
]

And the result should be:
array:3 [
  1 => 60.0
  2 => 50.0
]

Here's my code:
array_filter($categoryRating[$category->id]
but the result is the same as unfiltered.
$category is just a collection where I assigned id as new key for the filtered result.

A: edit: I included the oneliner from Kevin:
$array = [1 => 60.0, 2 => 50.0, 5 => 'in-progress'];
$array = array_filter($array, 'is_numeric');
var_dump($array);

Have you tried something like:
array_filter($categoryRating, function($v, $k) {
    return is_numeric($v);
}, ARRAY_FILTER_USE_BOTH));

It should return an array with all numeric values in your input array, but I haven't tested it.
Maybe you just have to play around with the $callback function of array_filter.

A: Without Loop:
array_walk_recursive($categoryRating, function(&$value,$key){
    $value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
});

Loop is here:
$categoryRating = [60.0,50.0,6.5,'in-progress'];
    foreach ($categoryRating as $key => $val){
        $categoryRating = array_filter($categoryRating, function($val){
            return $val != is_string($val);
        });
    }
print_r($categoryRating);

If the array in an array:
$categoryRating =
        array([
            1 => 60.0,
            2 => 50.0,
            5 => "in-progress"
        ]);
    foreach ($categoryRating as $key => $val) {
        $categoryRating = array_filter($categoryRating[0], function ($val) {

            return $val != is_string($val);
        });
    }
    echo json_encode($categoryRating);


text:
Q: Have different entries in startmenu dependent on what user has chosen to install I'm making use of optional installation of components in NSIS installer as shown in Controlling Available Install Options on the NSIS wiki.
This works fine, dependent on what options the user has chosen, the related parts are installed.
But now there is a problem with the start menu entries which come in a separate section:
Section -startmenu
SetShellVarContext all
CreateDirectory "$SMPROGRAMS\MyInstall"
CreateShortCut "$SMPROGRAMS\MyInstallOpenAPC\Editor1.lnk" "$INSTDIR\Editor1.exe" "" "$INSTDIR\icon.ico" 0
CreateShortCut "$SMPROGRAMS\MyInstallOpenAPC\Editor2.lnk" "$INSTDIR\Editor2.exe" "" "$INSTDIR\icon.ico" 0
CreateShortCut "$SMPROGRAMS\MyInstallOpenAPC\Editor3.lnk" "$INSTDIR\Editor3.exe" "" "$INSTDIR\icon.ico" 0
CreateShortCut "$SMPROGRAMS\MyInstallOpenAPC\Editor4.lnk" "$INSTDIR\Editor4.exe" "" "$INSTDIR\icon.ico" 0
Sectionend

Dependent on the optionally installed packages I want to create only some of the start menu entries.
How can this be done? How can I create a relation between start menu entries and the installed sections?

A: You can check if the relevant component (section) is selected:
!include LogicLib.nsh
InstallDir "$ProgramFiles\MyApp"
Page Components
Page InstFiles

Section "Foo" SID_FOO
SetOutPath "$InstDir\Foo"
; ...
SectionEnd

Section "Bar" SID_BAR
SetOutPath "$InstDir\Bar"
; ...
SectionEnd

Section "Start menu shortcuts"
SetShellVarContext all
${If} ${SectionIsSelected} ${SID_FOO}
    CreateDirectory "$SMPROGRAMS\MyApp"
    CreateShortcut "$SMPROGRAMS\MyApp\Foo.lnk" "$InstDir\Foo\Foo.exe"
${EndIf}
${If} ${SectionIsSelected} ${SID_BAR}
    CreateDirectory "$SMPROGRAMS\MyApp"
    CreateShortcut "$SMPROGRAMS\MyApp\Bar.lnk" "$InstDir\Bar\Bar.exe"
${EndIf}
SectionEnd


text:
Q: how to get the second table values in one to many relationship I have two Models
TermOne
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TermOne extends Model
{
    public function term_one_files()
    {
        return $this->hasMany('App\TermOneFile');
    }
}

I want to get values of this Model
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TermOneFile extends Model
{
    public function term_ones()
    {
        return $this->belongsTo('App\TermOne');
    }

}

I want to get the table two values TermOneFile form TermOne with eager loading but I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'term_one_files.term_one_id' in 'where clause' (SQL: select * from term_one_files where term_one_files.term_one_id in (1))
here is my Controller
$curriculum = TermOne::with('term_one_files')->where('id', $request->curriculum_id)->get();

 dd($curriculum);

return view('backend.uploads.index', compact('grade', 'subject', 'term_id', 'curriculum'));

maybe Im doing something wrong
term_one_files structure
public function up()
    {
        Schema::create('term_one_files', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('curriculum_id');
            $table->string('filename')->nullable();
            $table->string('filepath')->nullable();
            $table->timestamps();

            $table->foreign('curriculum_id')->references('id')->on('term_ones')
            ->onUpdate('cascade')->onDelete('cascade');
        });
    }

A: Try specifying your foreign key in the relationship this way:
public function term_one_files()
{
    return $this->hasMany('App\TermOneFile', 'curriculum_id');
}

or you can change your column name in the migration file from: 'curriculum_id' to 'term_one_id'.


text:
Q: How to break a loop if "break" is inside fork-join? I need to break a repeat loop, whose break decision is made inside a fork-join block, but my simulator doesn't compile the code that has the following structure.
repeat (10) begin
    fork
        begin
            // do something
        end
        begin
            #(100ms);
            break; // compile error
        end
    join_any
    disable fork;
end

I also tried the disable command. I was able to compile, but it didn't break the loop.
repeat (10)
begin : repeat10_loop
    fork
        begin
            // do something
        end
        begin
            #(100ms);
            disable repeat10_loop; // try
        end
    join_any
    disable fork;
end : repeat10_loop

Is there a way to use break or disable inside fork-join?

A: The break and continue statements must be within the same process as the loop statement. The problem with your disable is you incorrectly labeled your loop. Try:
repeat10_loop: repeat (10)
   begin


text:
Q: Retrieve all messages in Slack(more than 1000) I want to retrieve all the messages that were sent in my teams slack domain,more than year.
i'm using  channels.history method to retrieve the history of each channel,
But this method returns maximum of 1000 records only.
count  100 Optional, default=100
Number of messages to return, between 1 and 1000.
And i dont have access for  https://my.slack.com/services/export to export all the data.
Also timesatmp is not way to get the desired data, beacuse my slack channel recived more than 1000 message per day
Are there any possibilities?

A: Yes, you can get all messages with channels.history for your situation. Here is how:

*

*Call the method once to get the newest 1000 messages (1st chunk)

*Call the method again with latest property set to the timestamp of
the oldest message you received in the last chunk and the
inclusive property set to false. This will get you the next
chunk of 1000 messages

*Repeat until you received all messages

Remember that the rate limit is 1 call per second, so make sure you don't call the API more often.


text:
Q: Joining to OverlayItems In a class derived from the MapActivity class, I want to join two OverlayItems with a line. So far, I have tried to override the MapView's onDraw method but it is not possible because this method is declared final.
How can I do?
Thanks in advance for the time you will spend trying to help me.

A: Override draw() in your Overlay and draw what you wish.


text:
Q: Renderscript runtime error "failed to read script metadata" on Android 4.1.x phones I have three Renderscript functions (in three separate RS files) that used to work great on Adroid 4.1.x phones. However, after I upgraded to ADK 18, they started having runtime errors, crashing on the same phones. The errors are like this:
V/RenderScript( 3644): rsContextCreate dev=0x5a2f0fc0
V/RenderScript( 3644): 0x40051010 Launching thread(s), CPUs 0
V/ScriptC ( 3644): Create script for resource = levels
E/bcc     ( 3644): CPU is krait2
E/bcc     ( 3644): Cache dependency levels sha1 mismatch:
E/bcc     ( 3644):   given:  4144ab455aa71df31932ff5baf15583cf1775d72
E/bcc     ( 3644):   cached: d2ab2c2b568810d8ca0c39d730cb2494cae89106
V/ScriptC ( 3644): Create script for resource = sepia
E/bcc     ( 3644): Cache dependency sepia sha1 mismatch:
E/bcc     ( 3644):   given:  6b15396c900dd23c700b8c13e7d5019fb72fcb0e
E/bcc     ( 3644):   cached: 8d011a42147f8d3895db549e0b3fe4a43ed49fe2
V/ScriptC ( 3644): Create script for resource = flip
E/bcinfo  ( 3644): Could not parse bitcode file
E/bcinfo  ( 3644): Invalid SWITCH record
E/RenderScript( 3644): bcinfo: failed to read script metadata
W/dalvikvm( 3644): threadid=1: thread exiting with uncaught exception (group=0x410f4498)
E/AndroidRuntime( 3644): FATAL EXCEPTION: main

It is worth noting that on 4.2.x and newer devices, the Renderscript functions still work.
In the "project.properties" file, I tried sdk.buildtools = 17.0.0, 18.0.1, 18.1.0, 18.1.1, and 19.0.0. None of them worked on 4.1.x phones, though the error message changed slightly with 19.0.0. I googled the error message "failed to read script metadata". Apparently it was added by Stephen Hines. I don't really understand Stephen's changes, so I'd like to ask the following questions:

*

*Why were the changes made?

*What is the most likely reason that my Renderscript functions stopped working on 4.1.x devices?

*How to fix the crashes?

The flip.rs that's causing the crash is listed below. Suggestions and comments are welcome. Thanks!
#pragma version(1)
#pragma rs java_package_name(com.xxxx.yyyy.zzzz)
#include "rs_time.rsh"

rs_script flipScript;
rs_allocation gIn;
rs_allocation gOut;
int width;
int height;
int direction = 0;

void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {
    if(direction == 0) { // flip horizontally
        const uchar4 *element = rsGetElementAt(gIn, width - x, y);
        float4 color = rsUnpackColor8888(*element);
        float4 output = {color.r, color.g, color.b};
        *v_out = rsPackColorTo8888(output);
    }
    else if(direction == 1) { // flip vertically
        const uchar4 *element = rsGetElementAt(gIn, x, height - y);
        float4 color = rsUnpackColor8888(*element);
        float4 output = {color.r, color.g, color.b};
        *v_out = rsPackColorTo8888(output);
    }
    else if(direction == 2) { // rotate left
        const uchar4 *element = rsGetElementAt(gIn, width - y, x);
        float4 color = rsUnpackColor8888(*element);
        float4 output = {color.r, color.g, color.b};
        *v_out = rsPackColorTo8888(output);
    }
    else if(direction == 3) { // rotate right
        const uchar4 *element = rsGetElementAt(gIn, y, height - x);
        float4 color = rsUnpackColor8888(*element);
        float4 output = {color.r, color.g, color.b};
        *v_out = rsPackColorTo8888(output);
    }
}

void flip(int testIdx) {
    int64_t  t0, t1;
    int64_t  t;
    t0 = rsUptimeNanos();
    rsForEach(flipScript, gIn, gOut);
    t1 = rsUptimeNanos();
    t = t1 - t0;
    rsDebug("  flip: timer on RS side: ", t);
    timeNanoSec[testIdx] = (float)t;
}

A: What target API are you compiling for? Can you send me an apk or at least the 3 failing .bc files?
This looks like a bitcode encoding issue for only v16 (JellyBean) devices. It has nothing to do with the changelist you mentioned, but actually has to do with coalescing of ranged values in a switch statement. It is a bug in the compiler frontend, llvm-rs-cc. Libbcc (the on-device compiler) is rightfully rejecting the bad bitcode that a v16 device can't read (namely, the coalesced case ranges). I will file a bug to fix this internally and hopefully get it released in a future SDK update. In the meantime, I suggest you make use of the RenderScript support library, which would bypass this particular bug (since it won't generate v16 bitcode).


text:
Q: Why does  come left of copyright symbol? Why does the special symbol "Â" come left of the copyright symbol?
I tried meta and it didn't work. I used Meta tag and still.

A: Make sure you use the same character encoding throughout your project
Nowadays, that's usually utf-8 because it's reasonably compact and supports global characters as well as emoji.
This happens specifically because the © symbol is two bytes in utf-8: 0xC2 0xA9. If these two bytes are saved to a file/ database etc, and then read using the wrong character encoding, it comes out as something else. Specifically 0xC2 in Windows-1252 an extension of ASCII is the character you're seeing - Â. Single byte encodings are very basic by today's standards as they only have a very small amount of characters.
As it seems like you're saving your text to a .html file and a browser is displaying it with the wrong encoding, add a doctype at the top of your file. The HTML5 doctype tells the browser to use utf-8 by default (if it didn't already), and the meta tag covers old browsers too:
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
    </head>
    <body>
    ©
    </body>
</html>


text:
Q: Need help to understand mechanical drawing for footprint I am a new user of Altium Designer. I need to make a footprint of this varistor, and I cannot understand its drawing. Same thing happens for the rest of the components. Can someone here tell me how I am supposed to decide the pad diameter, height, width? Take this doc as a reference, and I hope I will cater other drawings as well then!
Here is the datasheet link (Littelfuse LA Varistor Series).

A: The datasheet describes a family of devices, which have similar shapes (disk with radial leads) but different dimensions.  The case sizes are identified by the nominal diameter (even though a 7mm part can actually be as large as 9mm).

To avoid making an individual drawing for each size, the authors of the datasheet made one parametrized drawing with letter designators, and listed the mechanical dimensions in the table below.
So for instance, the diameter of the pin is marked as Øb on the drawing.  From the table we find that for 7mm size, will have pin diameter between 0.585mm and 0.685mm.

(p.10 in the datasheet)

A: This is what you have to draw:

Dimensions are at page 10 of that datasheet. For information regarding pads/holes What pad hole (drill) size is appropriate for a given through-hole lead diameter?


text:
Q: How to float
* element only without affecting another element I have two divs. One should be for my menu and the second is just the title. When I try to make the
 items float next to each other, it goes down from its position and affects my title div; it gets into the title div (it places itself into my title head).
HTML:

Home

Query

Reports

Attendnace & Absence

CSS:
 .empbox
 {
  height:30px;
  background:-moz-linear-gradient(left, #FFFFFF 0%,#6C8483 50%,#FFFFFF 100%);
  background:-webkit-linear-gradient(left, #FFFFFF 0%,#6C8483 50%,#FFFFFF 100%);
  background:linear-gradient(left, #FFFFFF 0%,#6C8483 50%,#FFFFFF 100%);
  width:100%;
  display:block;
  color:White;
  margin-top:190px;
  padding-top:10px;
  }
 .menu
 {
  background:white; color:Black;
 }
 .menu ul
 {
  list-style:none;
  padding-right:20px;
 }
 .menu li
  {
  float:left;
  }

I want my li to go above the title. I want to know why
 is not the only element affected.  I specified
 element not the entire div.

A: Can't comment, so let's do it this way... I don't know what you want actually. Can you describe it a little better? Anyhow, you don't need to float the list items. If you float the ul and give an display: inline to the
, than that should be enough. In any case, that's one problem solved. Now waiting for your response.
Here you go: http://jsfiddle.net/33VyN/

A: You can wrap the title with a
 that clears the float. Also  tags are deprecated.

Attendnace & Absence


text:
Q: SyntaxError: identifier starts immediately after numeric literal error in javascript? I am working on an application where I am fetching the weather information from OpenWeatherMaps API and then plotting it on graphs using FlotJS.
The data is coming from:
http://api.openweathermap.org/data/2.5/forecast?lat=39.77476949&lon=-100.1953125
Where the lat, lon are dynamically generated. You can go to the link to get an idea of what kind of JSON response is sent back.
I am trying to construct the arrays first in order to pass them into the data object while plotting the graph like so:
var temp = [];
var humidity = [];
var rain = [];

$.each(response.list, function(i, item){
    if(moment(item.dt, 'X').isSame(moment(), 'day')){
        temp.push([moment(item.dt, 'X').valueOf(), parseFloat(item.main.temp)]);
        humidity.push([moment(item.dt, 'X').valueOf(), parseFloat(item.main.humidity)]);
        rain.push([moment(item.dt, 'X').valueOf(), parseFloat(item.rain.3h)]);
    }
});

temp and humidity were working fine. I cannot add precipitation. The precipitation values are in the rain object in 3h and when I try to push it into the array, I get a console error saying:

SyntaxError: identifier starts immediately after numeric literal

How to go around this problem?

A: 3h isn't a valid symbol, it's a numeric literal followed by an "h"; parser go boom.
You need item.rain['3h'] instead.


text:
Q: Strange random numbers at the end of .js I have a strange problem, and I don't know where to start to search. My file /nat.js in chrome developer tools shows /nat.js:35, /nat.js:5, /nat.js:16 or /nat.js:6 and all that paths are inaccessible. Only when I directly type http:xxxxx/test/nat.js is reachable, but on-page is not. Does someone know why js files adding that random numbers? What causing those redirections to not accessible pages?
Thanks.


text:
Q: How can I repair the default GTK libraries after installing GTK 3.4 from source? I am running Ubuntu 12.04 and compiled and installed GTK 3.4 to go through some GTK developer tutorials.
Installing this version of GTK has caused problems with Unity.
All system dialogs and top bar now have a different (older) look, and when I try to launch Nautilus I get the following message:
Gtk-Message: Failed to load module "canberra-gtk-module"
Initializing nautilus-open-terminal extension
Initializing nautilus-dropbox 1.4.0
Initializing nautilus-gdu extension
nautilus: symbol lookup error: nautilus: undefined symbol: ubuntu_menu_proxy_get

I have run make uninstall on the newer version of GTK and reinstalled just about every package I can think of, but I am still having the same problem.
How can I repair the default Ubuntu GTK libraries?
EDIT
Also, I noticed that my desktop icons are gone (launcher works), and I can't interact with the desktop. I can't drag any shortcuts to it, etc.

A: Long shot guess:
Within dconf-editor (install it with sudo apt-get install dconf-editor), navigate to:
org/gnome/settings-daemon/plugins/xsettings/
Is it active?...Its a harmless(?) thing to try.
There is also dconf to do it with a cli command, (run dconf help) but i like to check first how it is actually set.
Long story (could be helpful?):Same boat, not sure same storm:
Tried even with gtk-change theme, gnome-tweak, Ubuntu Tweak... to no avail. It affected all GNOME, including shell, Unity and even Cairo-Dock sessions.... No font settings size or hinting would show any difference...(I think it was after fiddling with gnome-shell and/or accessibility zoom settings...not really sure)
xdiagnose informed me that Raleigh was the "old-look" (GTK...2?) theme i could not get rid of, but gave me the clue. Searched for it in the filesystem / and digging thru the folders i found a text that explained it was the last resort theme in case nothing was defined. (/usr/share/themes/Raleigh/gtk-2.0/gtkrc).
So (kind of a hunch) i went to dconf-editor to org/gnome/settings-daemon/plugins/ and checking thru the keys there (i turned them all on as a desperate measure....i don't really recommend doing it so blindly...it worked for me thou...) i "stumbled" upon the -last- one: "xsettings" and found it was NOT activated. Activating THAT did the trick.


text:
Q: Spring Integration Gateway Inner Bean Definition I am in the process of upgrading:

*

*Spring 3.1.0.RELEASE => 4.0.6.RELEASE

*Spring Integration 2.1.0.RELEASE => 4.0.3.RELEASE

And am noticing some incompatibilities with the XML configuration of gateways as inner beans.
Before the upgrade, something like this was fine:
<bean id="eventPublisher" class="com.blorp.EventPublisher">
    <constructor-arg>
           <int:gateway default-request-channel="eventPublishingChannel"
                         default-reply-timeout="10000"
                         service-interface="com.blorp.messaging.Sender">
                <int:method name="send" />
            </int:gateway>
    </constructor-arg>
</bean>

<int:channel id="eventPublishingChannel" />

After performing the aforementioned upgrade, when an event is actually sent at runtime an exception is thrown because the request channel has not been set:
Caused by: java.lang.IllegalStateException: send is not supported, because no request channel has been configured
    at org.springframework.util.Assert.state(Assert.java:385) ~[spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.integration.gateway.MessagingGatewaySupport.send(MessagingGatewaySupport.java:197) ~[spring-integration-core-4.0.3.RELEASE.jar:na]
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:344) ~[spring-integration-core-4.0.3.RELEASE.jar:na]
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:304) ~[spring-integration-core-4.0.3.RELEASE.jar:na]
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:295) ~[spring-integration-core-4.0.3.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy84.send(Unknown Source) ~[na:na]
    at com.blorp.DefaultEventPublisher.publish(DefaultEventPublisher.java:29) ~[blorp-0.54.0-SNAPSHOT.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_45]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_45]
...

When I step through with the debugger, the MessageGatewaySupport.requestChannel property is indeed null even though the configuration specifies it.
The workaround is to not configure the gateway as an inner bean. The snippet below runs fine:
<int:gateway id="sender" default-request-channel="eventPublishingChannel"
                         default-reply-timeout="10000"
                         service-interface="com.blorp.messaging.Sender">
    <int:method name="send" />
</int:gateway>

<bean id="eventPublisher" class="com.blorp.EventPublisher">
    <constructor-arg ref="sender" />
</bean>

I am curious why the former doesn't work after the upgrade. Is it some issue creating the proxy? Is it a bug? I haven't been able to find an issue for this.

A: That's true, because here you try to configure <gateway> as nested element.
Since Spring Integration 3.0 it is possoble only in the <chain> definition.
The root of cause is here (GatewayParser):
boolean isNested = parserContext.isNested();
...
gatewayAttributes.put("defaultRequestChannel", element.getAttribute(isNested ? "request-channel" : "default-request-channel"));

For any other cases you really have to configure <gateway> as root component and use its id for injection to other beans.
It's just a simple cost of migration: other cases may not be so simple: https://github.com/spring-projects/spring-integration/wiki
From other side I find you nested solution isn't so useful for integration as it is presented by Gateway pattern definition.
I'm really sure that some day you decide to use the same gateway interface from another service.
Don't try to treat framework in this case: it's just an API with wich we should follow, as we have to provide an object of concrete type as parameter to the existing methods of some Java core class.


text:
Q: How do I set the InvocationCount at runtime in TestNG - @Test? I want to run my Test methods multiple times based on a business logic. Is there a way to alter InvocationCount to achieve the same ? any other suggestions are also welcome.

A: You would need to basically leverage an IAnnotationTransformer for doing this.
Here's a sample that shows this in action.
The marker annotation which we are going to be using to indicate that a particular test method needs to be run more than once.
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;

/**
 * A Marker annotation which is used to express the intent that a particular test method
 * can be executed more than one times. The number of times that a test method should be
 * iterated is governed by the JVM argument : -Diteration.count. The default value
 * is 3
 */
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD})
public @interface CanRunMultipleTimes {
}

The test class looks like this.
import org.testng.annotations.Test;

import java.util.concurrent.atomic.AtomicInteger;

public class TestClassSample {
    private volatile AtomicInteger counter = new AtomicInteger(1);

    @CanRunMultipleTimes
    @Test
    public void testMethod() {
        System.err.println("Running iteration [" + counter.getAndIncrement() + "]");
    }
}

Here's how the annotation transformer looks like.
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class SimpleAnnotationTransformer implements IAnnotationTransformer {
    @Override
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
        if (testMethod == null || testMethod.getAnnotation(CanRunMultipleTimes.class) == null) {
            return;
        }

        int counter = Integer.parseInt(System.getProperty("iteration.count", "3"));
        annotation.setInvocationCount(counter);
    }
}

Here's how the suite xml file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46998341_Suite" verbose="2">
    <listeners>
        <listener class-name="com.rationaleemotions.stackoverflow.qn46998341.SimpleAnnotationTransformer"/>
    </listeners>
    <test name="46998341_Test">
        <classes>
            <class name="com.rationaleemotions.stackoverflow.qn46998341.TestClassSample"/>
        </classes>
    </test>
</suite>

Here's how the output would look like :
... TestNG 6.12 by Cédric Beust (cedric@beust.com)
...
Running iteration [1]
Running iteration [2]
Running iteration [3]
PASSED: testMethod
PASSED: testMethod
PASSED: testMethod

===============================================
    46998341_Test
    Tests run: 3, Failures: 0, Skips: 0
===============================================

===============================================
46998341_Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================

A: Can you do it in a class level. Thanks for the help, method level works perfect, just wondering if we can do for Class level also
I tried below but it didn't work. used TYPE
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD, TYPE})
public @interface CanRunMultipleTimes {
}


text:
Q: I am getting an error using geom_density_2d in R I'm new to R and new to programming. I'm currently trying to use geom_density_2d in ggplot to graph a simple heat map using the faithful dataset. Here's the code I'm trying to run:
library(tidyverse)

m <- faithful %>%  ggplot(aes(x = eruptions, y = waiting)) +
geom_point() +
xlim(0.5, 6) +
ylim(40, 110)
m + geom_density_2d()

m + geom_density_2d(aes(fill = stat(level)), geom = "polygon")

The first graph works just fine, but when I try to run the second I get the following error message:
'Error in stat(level) : could not find function "stat"'
Any ideas on how this can be fixed?

A: I was able to reproduce the same error using the example for stat https://ggplot2.tidyverse.org/reference/stat.html
library(ggplot2)
ggplot(mpg, aes(displ)) +
  geom_histogram(aes(y = stat(count)))

However, as some of my packages were out of date I was able to resolve it by 1) restarting R and 2) running:
install.packages("tidyverse", dependencies = TRUE)


text:
Q: Equation of pair of lines created by the intersection of 2 double cones? The equations of $2$ double cones having their vertex at the origin $(0,0,0)$ are given by:
$(ax+by+cz)^2=(x^2+y^2+z^2)\cos^2(\theta_1)   \hspace{25pt} (1)$
($\theta_1=$semi-apical angle, and $a,b,c$ are the direction cosine of the axis of the cone)
$(a'x+b'y+c'z)^2=(x^2+y^2+z^2) \cos^2(\theta_2) \hspace{25pt} (2)$
($\theta_2=$ semi-apical angle, and $a',b',c'$ are the direction cosine of the axis of the cone)
Suppose, it's given that the 2 cones intersect. So, it is obvious that their intersection will yield a pair of straight lines (Also at a specific case only a line, when just touching each other).
What will be the equation of the lines (or line)?

A: Define $r = [x, y, z]^T$ and
$Q_1 = \cos^2(\theta_1)I- v_1 v_1^T $
$Q_2 = \cos^2(\theta_2) I- v_2 v_2^T $
where $v_1 = [a, b, c]^T , v_2 = [a', b', c']^T $
Then the equation of the cones are
$r^T Q_1 r = 0 $
and
$r^T Q_2 r = 0 $
If $r$ satisfies both equations (i.e. $r$ lies on both cones) then
it will satisfy
$r^T Q_\alpha r = 0 $
where
$Q_\alpha = Q_1 + \alpha Q_2 $
The determinant of $Q_\alpha$ is a cubic polynomial in $\alpha$ that has at least one real root.  Choosing this value for $\alpha$, we can diagonalize $Q_\alpha$ into
$Q_\alpha = R D R^T $
where $D$ has one of its diagonal entries equal to zero.  Therefore, $D$ takes the form
$D = \begin{bmatrix} D_{11} && 0 && 0 \\ 0 && D_{22} && 0 \\ 0 && 0 && 0 \end{bmatrix} $
Now we have the following situation
$ r^T R D R^T r = 0 $
Define vector $u = R^T r$, then $ u^T D u = 0 $ so that
$D_{11} u_1^2 + D_{22} u_2^2 = 0 $
If $D_{11}$ and $D_{22}$ have the same sign, then the above equation implies that
$u_1 = u_2 = 0$ while $u_3 = t$, i.e. $u = t [0, 0, 1]^T$
Hence candidate solutions are $r = t R_3 $ where $R_3$ is the third column of matrix $R$.  Now using the equation of the first cone, we get
$ t^2 R_3^T Q_1 R_3 = 0 $
If $R_3^T Q_1 R_3 \ne 0 $ then $t = 0 $ and the origin is the only solution, otherwise $t$ can be any real number, and $r = t R_3$ is the single line of intersection between the two cones.
Next, we assume that $D_{11}$ and $D_{22}$ have different signs, then from
$D_{11} u_1^2 + D_{22} u_2^2 = 0 $
we have
$ u =  \begin{bmatrix} t \\ \pm t \sqrt{ \dfrac{D_{11}}{D_{22}} } \\ s \end{bmatrix}$
where $t$ and $s$ are real.
Vector $u$ is more conveniently written as
$ u = t x_1 + s x_2 $
where
$x_1 = [1 , \pm  \sqrt{ \dfrac{D_{11}}{D_{22}} } , 0 ]^T$
$x_2 = [0, 0, 1]^T$
Now $r = R u = R ( t x_1 + s x_2) = t (R x_1) + s (R x_2 ) = t y_1 + s y_2$
Using $r^T Q_1 r = 0 $ we get
$t^2 y_1^T Q_1 y_1 + 2 t s y_1^T Q_1 y_2 + s^2 y_2^T Q_1 y_2 = 0 $
Dividing through by $s^2$ and defining $ \beta = \dfrac{t}{s} $, then
$ \beta^2 (y_1^T Q_1 y_1) + 2 \beta (y_1^T Q_1 y_2) + (y_2^T Q_1 y_2) = 0 $
which is a quadratic equation in $\beta$, and can have no solutions, implying no lines of intersection, one solution giving a single line of intersection, or two solutions implying two lines of intersection.
Suppose, for example, that we have two solutions $\beta_1 , \beta_2 $ then
for the $i$-th line we have
$ t = \beta_i s $
and
$r = t y_1 + s y_2 = s ( \beta_i y_1 + y_2 ) $
for $i = 1, 2$
And this gives the equation of the lines of intersection as a scalar multiple of the vector $ (\beta_i y_1 + y_2 ), i = 1, 2$

A: Another way to solve this problem is to consider the lines that constitute the curved surface of the first cone, and apply the condition that the angle it makes with the axis of the second cone be $\theta_2$.
A line on the first cone is generated as follows.  Let $d$ be defined as
$d = a_1 + \tan( \theta_1) u_1 $
where $a_1= [a, b, c]$ is the unit vector along the axis of the first cone, and $u_1$ is any unit vector that is orthogonal to $a_1$.
Then the set of all scaled rotations of $d$ about the axis $a_1$ constitutes the surface of the first cone.  Rotations of $d$ are about the axis $a_1$.  Thus, a general line on the surface of the first cone is given by
$ r = t R d $
where $R$ is the rotation matrix having axis $a_1$ and angle of rotation $\phi$, and $t \in \mathbb{R} $
Using the Rodrigues' rotation matrix formula we can express $R$ as
$R = {a_1 a_1}^T + (I - {a_1 a_1}^T ) \cos(\phi) + S_{a_1} \sin(\phi) $
where
$ S_{a_1} = \begin{bmatrix} 0 && - a_{1z} && a_{1y} \\
a_{1z} && 0 && -a_{1x} \\
-a_{1y} && a_{1x} && 0 \end{bmatrix} $
Now we want vector $r$ to lie on the second cone, hence the angle it makes with $a_2=[a',b',c']^T$ has to be equal to $\theta_2$
Therefore, the condition for intersection can be expressed as
$ \cos(\theta_2) = \dfrac{ t R d \cdot a_2 } { \| t R d \| } = \dfrac{ R d \cdot a_2 }{ \| d \| } $
Now vector $d$ is a constant vector , so this becomes
$ \| d \| \cos(\theta_2) = a_2^T R d $
expanding the right hand side using the expression for $R$ given above, this becomes the simple trigonometric equation
$ A \cos(\phi) + B \sin(\phi) = C $
where
$A = a_2^T (I - {a_1 a_1}^T ) d $
$B = a_2^T S_a d $
$C =  \| d \| \cos(\theta_2) -  a_2^T {a_1 a_1}^T d$
And this equation is trivial to solve.  For completeness, I am going to include it solution.
Find the angle $\psi = \text{Atan2}( A, B ) $ , i.e. the angle $\psi $ satisfies $\cos \psi = \dfrac{A}{\sqrt{A^2 + B^2}} $ and $\sin \psi = \dfrac{B}{\sqrt{A^2 + B^2 }} $, and this transforms the trigonometric equation to
$ \cos \psi \cos \phi + \sin \psi \sin \phi = \dfrac{C}{\sqrt{A^2 + B^2}} $
which simplifies to
$ \cos(\phi - \psi ) = \dfrac{ C }{\sqrt{A^2 + B^2}} $
Hence,
$ \phi = \psi \pm \cos^{-1} \left( \dfrac{C}{\sqrt{A^2 + B^2 }} \right) $
Depending on the values of $A,B,C$ we can have no solutions, a single solution, or two solutions.
Once the values of $\phi $ are found, we find $R$, then we find $r = t R d$ which the parametric form of the line with parameter $t$ and direction $Rd$.
As an explicit example, suppose
$a_1 = [\frac{1}{3}, \frac{2}{3}, \frac{2}{3}]^T $
and
$a_2 = [\frac{1}{9}, - \frac{-4}{9}, \frac{8}{9} ]$
And $theta_1 = \dfrac{\pi}{3} $ and $\theta_2 = \dfrac{\pi}{4} $
We have to solve the trigonometric equation
$A \cos \phi + B \sin \phi = C$
where
$A = a_2^T (I - {a_1 a_1}^T ) d $
$B = a_2^T S_a d $
$C =  \| d \| \cos(\theta_2) -  a_2^T {a_1 a_1}^T d$
and
$ d = a_1 + \tan(\theta_1) u_1 $
and $u_1$ is any unit vector perpendicular to $a_1$
So let's choose $u_1 = [2, 0, -1]/\sqrt{5} $, then
$d = (-1.21586, 0.66666, 1.4412633 ) $
And applying the formula given, we get two solutions for $\phi$,
$ \phi_1 = 0.4016017696 , \phi_2 = 2.09648977 $
And this results in two solutions
$X_1 = t (-0.44537, 0.081013 , 0.891673 ) $
and
$X_2 = t ( 0.778705 , -0.22501 , 0.585654 )$
The above vectors have been normalized.

A: This is a third method that is probably the simplest.
We have the vector
$v_1 = [a, b, c]^T $ which is a unit vector, and $v_2 = [a',b',c'] $ which is also a unit vector.  Define $\phi$ to be the angle between them.  Thus
$\phi = \cos^{-1}({ v_1 \cdot v_2 } )$
Generate a third vector from $v_1$ and $v_2$ using their cross product and normalize it.  That is,
$ v_3 = \dfrac{ v_1 \times v_2 }{\| v_1 \times v_2 \| } $
Now the vector of intersection of the two cones can be written as a linear combination of $v_1, v_2 , v_3 $, i.e.
$ x = c_1 v_1 + c_2 v_2 + c_3 v_3 $
Since $x$ lies on the first cone then
$ x \cdot v_1 = \| x \| \cos \theta_1 = c_1 + c_2 \cos \phi \hspace{25pt}(1) $
(note that $v_1 \cdot v_3 $ = 0 )
Similarly,
$ x \cdot v_2 = \| x\| \cos \theta_2 = c_1 \cos \phi + c_2 \hspace{25pt}(2)$
Hence, by dividing these two equations,
$ \dfrac{ \cos \theta_2 }{\cos \theta_1 } = \dfrac{ c_1 \cos \phi + c_2 }{ c_1 + c_2 \cos \phi } \hspace{25pt}(3)$
Solving for $c_2 $ in terms of $c_1 $ yields
$ c_2 = \alpha \hspace{3pt} c_1$, where $\alpha  =  \dfrac{ \cos \theta_2 - \cos \phi \cos \theta_1 }{ \cos \theta_1 - \cos \theta_2 \cos \phi } \hspace{25pt}(4)$
We need to find $c_3 $ in terms of $c_1$.  From the equation $(1)$
$(x \cdot x) \cos^2 \theta_1 = c_1^2 + 2 c_1 c_2 \cos \phi + c_2^2 \cos^2 \phi $
and we have $x \cdot x = c_1^2 + c_2^2 + 2 c_1 c_2 \cos \phi + c_3^2 $
Therefore,
$( c_1^2 + c_2^2 + 2 c_1 c_2 \cos \phi + c_3^2 ) \cos^2 \theta_1 = ( c_1^2 + c_2^2 \cos^2 \phi + 2 c_1 c_2 \cos \phi ) $
Dividing through by $c_1^2$ yields,
$\begin{equation}\begin{split}
\left(1 + \alpha^2 + 2 \alpha \cos \phi + \left(\dfrac{c_3}{c_1} \right)^2 \right) \cos^2 \theta_1  &= 1 + \alpha^2 \cos^2 \phi \\ &+ 2 \alpha \cos \phi \end{split}\end{equation}$
From which,
$ \cos^2 \theta_1 \left( \dfrac{c_3}{c_1} \right)^2 = \sin^2 \theta_1 + \alpha^2 (\cos^2 \phi - \cos^2 \theta_1 ) + 2 \alpha \cos \phi \sin^2 \theta_1 $
Hence,
$\dfrac{c_3}{c_1} = \pm \beta $
where
$\beta = \sqrt{ \tan^2 \theta_1 (1 + 2 \alpha \cos \phi ) + \alpha^2 \left(\dfrac{\cos^2 \phi}{\cos^2 \theta_1}-1 \right) } $
Hence the solutions are
$ X = c_1 v_1 + c_2 v_2 + c_3 v_3 $
where $c_1$ is arbitrary, $c_2 = \alpha c_1,  c_3 = \pm \beta c_1 $
In other words, $X = t [v_1, v_2, v_3] [ 1, \alpha, \pm \beta ]^T $
As an explicit example, suppose
$ v_1 = (\frac{1}{3} , \frac{2}{3}, \frac{2}{3} ) $
$ \theta_1 = \dfrac{\pi}{3} $
and
$ v_2 = (\frac{1}{9} , - \frac{4}{9}, \frac{8}{9} ) $
$ \theta_2 = \dfrac{\pi}{4} $
Then,
$ \phi = 1.230959 $
and
$ \alpha = 2.0448155 $
$ \beta = 2.18327804 $
Resulting in
$X_1 = t ( 2.618949, -0.75674, 1.969677 ) $
as one solution, and
$X_2 = t ( -1.49788, 0.272463, 2.998884) $
as the other solution.
After normalization these become
$X_1 = t ( 0.778705 , -0.22501 , 0.585654 )$
and
$X_2 = t (-0.44537, 0.081013 , 0.891673 ) $
which are exactly what we got with the other method involving the rotation matrix.


text:
Q: Is it possible to list post attachments in a sub URL endpoint with a dedicated template? Wordpress provides templates for displaying media attached to a post or page (attachment.php and more). They're also displayed with nice permalinks, such as:
site.com/projects/a-project/an-attachment/

Where projects is the slug for my custom post type project. a-project is the post name, and an-attachment is the name of an attached image.
The functionality I'm asking for is a sub URL endpoint for listing all post attachments with a dedicated template file. It would be great with a permalink for a post's attachments, wouldn't it?
Such as:
site.com/projects/a-project/attachments/
or
site.com/projects/a-project/images/

Is it possible? If not with pretty permalinks, is it with some kind of query variable? Apart from showing a single attachment, I haven't ever seen another form of sub URL endpoint to a Wordpress post before.
Thanks in advance!
EDIT
Some interesting resources:
http://johnbeales.com/20090824/endpoints-a-little-secret-for-url-manipulation-in-wordpress/
http://wordpress.org/support/topic/custom-rewrite-approach-with-add_rewrite_endpoint
http://www.rlmseo.com/blog/passing-get-query-string-parameters-in-wordpress-url/
http://codex.wordpress.org/User:DavidHouse/WP_Rewrite_API
URL Design for Sub-Posts?
http://codex.wordpress.org/Template_Hierarchy

A: I think I found it myself. Now I've successfully managed to add a /photos endpoint to a permalink URL, such as:
http://mywordpressite.com/projects/a-project/photos

And then a custom template, photos.php will load and show – with access to the global $post variable.
Helpful links:

*

*http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint

*http://codex.wordpress.org/Template_Hierarchy
In my functions.php I added functions for the single_template and query_vars filters and added a photos endpoint with the handy add_rewrite_endpoint() function.
// Permalink rewrites/add endpoints
add_filter( 'single_template', 'project_attachments_template' );
add_filter( 'query_vars', 'add_query_vars');

// You may need to go to wp-admin > Settings > Permalinks and
// save the changes in order to flush rewrite rules to activate.
add_rewrite_endpoint('photos', EP_PERMALINK);

Further down in the file:
/**
*   Add the 'photos' query variable so Wordpress
*   won't mangle it.
*/
function add_query_vars($vars){
    $vars[] = "photos";
    return $vars;
}

/**
*   From http://codex.wordpress.org/Template_Hierarchy
*
*   Adds a custom template to the query queue.
*/
function project_attachments_template($templates = ""){
    global $wp_query;

    // If the 'photos' endpoint isn't appended to the URL,
    // don't do anything and return
    if(!isset( $wp_query->query['photos'] ))
        return $templates;

    // .. otherwise, go ahead and add the 'photos.php' template
    // instead of 'single-{$type}.php'.
    if(!is_array($templates) && !empty($templates)) {
        $templates = locate_template(array("photos.php", $templates),false);
    }
    elseif(empty($templates)) {
        $templates = locate_template("photos.php",false);
    }
    else {
        $new_template = locate_template(array("photos.php"));
        if(!empty($new_template)) array_unshift($templates,$new_template);
    }

    return $templates;
}

Be sure to visit the Permalink page in wp-admin for the changes to take effect.


text:
Q: angular.js change url without calling controller I have to fix such solution:
my url is http://localhost:8080/#/dashboard in my dashboard there are some features to load, for example when my url will be http://localhost:8080/#/dashboard/20 I must load cities which country id equals 20 and when my url will be http://localhost:8080/#/dashboard/20/1 I have to load districts which city id equals 1. so what is my problem:
    when I click some links and url changes to #/dashboard/20 I am loading cities, after that I click another one link and url changes to #/dashboard/20/1 but here my controller is refreshing and all data is loading again, I want to change url but not refreshing controller, when my cities are already loaded I must have opportunity to load only districts after that and not both of them again at once.
I tried window.history.pushState but it does not work, may be is there any way to disable and enable my $routeProvider?
any ideas?

A: The only way I see this working is referring to the same controller or using a factory/service to maintain your variables.
The controllers will always change when the state changes if they are glued to them.
Edit: Btw, have you taken a look at ui.router? https://github.com/angular-ui/ui-router
Here's the link. I find this much more helpful than the old $route


text:
Q: Add variable to an existing json object request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;

var time =  Math.floor((Date.now() - Date.parse($scope.cases[i].date_case_modified))/(60000*60*24));

$scope.cases.duration.push(time);
}
});

Inside the controller I am trying to tack on the cases.duration onto the cases object but it wont add it onto the object that is returned. Any ideas?

A: I think you just need to introduce a forEach as shown here:
request = myService.getCases();
request.then(
    function(payload) {
         $scope.cases = payload.data;

         angular.forEach($scope.cases, function (el) {
            var time =  Math.floor((Date.now() - Date.parse(el.date_case_modified))/(60000*60*24));

            el.duration = time;
        });
    }
});

Hope this helps


text:
Q: Multiple threads for StaTaskScheduler in ViewModel ListBox contains list of files with their icons. I am trying to have 10 icons extracted at the same time but icons appear at same rate whether I have 1 of 10 as number of threads for StaTaskScheduler (TPL extensios).
public class FileData : INotifyPropertyChanged
{
...
private ImageSource icon = MainWindow.DefaultFileIcon;
public ImageSource Icon
{
    get
    {
        Task.Factory.StartNew(() =>
        {
            Icon = cIcon.GetIcon(FullPath); //uses SHGetFileInfo so STA is needed
        }, CancellationToken.None, TaskCreationOptions.None, FactorySTA.MyStaIcon);
        return icon;
    }
    set
    {
        if (icon != value)
        {
            icon = value;
            OnPropertyChanged("Icon");
        }
    }
}

public static class FactorySTA
{
        public static readonly StaTaskScheduler MyStaIcon = new StaTaskScheduler(10);
}

<DataTemplate DataType="{x:Type local:FileData}"  >
  <StackPanel...>
    <Image Source="{Binding Icon}" />

If this worked, I would also expect icons to appear in non-sequential order since it takes more time to get icon from an .exe file.


text:
Q: A way to compute and store the short url for a model Let's say you have simple model called Project and you need to store it's short url for later usage, when is the best way to compute it?
The best solution I have for now is a after_create hook, but that leads to code like

short_url || Rails.application.routes.url_helpers.project_path(project, host: HOSTNAME)

It does not feel right to access the url from the model.
In short, where do you put the code to compute the short_url?
Thank you,

A: Is there a reason why you dont want to save the exact short_url instead?  So when you need the url for the project object, you can just check if the short_url is present or not.  I believe you can just add a decorator to determine the url of project.
#using Draper
class ProjectDecorator < Draper::Decorator
  def effective_url
    source.short_url.present? ? source.short_url : project_path(source)
    # or source.short_url || project_path(source) if short_url will not be an empty string
    # or source.short_url || source
  end
end

A: I would add this code in the controller.
class ProjectsController < ApplicationController
  def create
    @project = Project.new(params[:project])

    respond_to do |format|
      if @project.save
        @project.update_attribute(:short_url, project_url(@project))
        (..)
  end
end

It feels like this code belongs to the controller as it deals with http/url. Storing in the db sounds ok, but asking for the url is the controller's responsibility.
The line:
@project.update_attribute(:short_url, project_url(@project))

needs to be added below the call to .save (or .create), as only then the project_url helper can be called (the project object got its id already).


text:
Q: Observability matrix: What is its rank? I'm writing a controller for an inverted pendulum in which the state vector isn't completely measurable.  The state vector is $\mathbf{x}\in\mathbb{R}^4$ and the output vector is $\mathbf{y}\in\mathbb{R}^2$.
The worked examples of evaluating observability that I've found all use  $\mathbf{y}\in\mathbb{R}^1$, so I'm reaching out here to ask whether I'm correctly calculating rank of the observability matrix $O$.
The output matrix $C$ is
$$
C = \begin{bmatrix}
1&0&0&0 \\
0&0&1&0
\end{bmatrix}
$$
The observability matrix $O$ is
$$
O = \begin{bmatrix}
 C \\
 CA \\
 CA^2 \\
 CA^3
 \end{bmatrix}
$$
A rounded version of the system matrix $A$ is
$$
A = \begin{bmatrix}
0&10&0&0\\
1&0&0&0\\
0&-20&0&0\\
0&0&1&0\end{bmatrix}
$$
The resulting observability matrix $O$ is then
$$
O = \begin{bmatrix}
\begin{bmatrix}1&0&0&0\\0&0&1&0\end{bmatrix}\\
\begin{bmatrix}0&10&0&0\\0&-20&0&0\end{bmatrix}\\
\begin{bmatrix}10&0&0&0\\-20&0&0&0\end{bmatrix}\\
\begin{bmatrix}0&100&0&0\\0&-200&0&0\end{bmatrix}\\
\end{bmatrix}
$$
Clarifications
1. On taking the rank of nested matrices
Wikipedia defines the rank of a matrix A is the dimension of the vector space generated (or spanned) by its columns.  Could I not say that $O$ is full rank 1 of 1 because it contains a single column of nonzero elements?
No, in this context we view this not as a 4x1 of 2x4 but as a melded 8x4 matrix.  Rank is then established by checking linear independence of the four columns.
2. On how the output matrix $C$ is represented
The way I represented the output matrix $C$ here as $q$x$n$ where $\mathbf{x}\in\mathbb{R}^n$ and $\mathbf{y}\in\mathbb{R}^q$
is in accordance with the Wikipedia article on State-Space.
However, the two controls textbooks I'm looking at:

*

*Feedback Control of Dynamic Systems (6th Edition) (FPE)

*Control Systems Engineering (7th Edition) (Nise)

strictly consider cases in which the shape of $\mathbf{x}$ and $\mathbf{y}$ is identical.  The shape of the $C$ matrix is always $1$x$n$.  Zero terms in $C$ are used to represent un-measurable terms in the output vector $\mathbf{y}$.  For example, let $\mathbf{x} = \begin{bmatrix}\dot\theta\\\theta\\\dot\phi\\\phi\end{bmatrix}$.  If only the terms $\dot\theta$ and $\dot\phi$ appear in the output vector $\mathbf{y}$, then the C matrix is given as $C = \begin{bmatrix}1&0&1&0\end{bmatrix}$
This approach feels misleading to me, as a term in the output vector $\mathbf{y}$ that's always zero is conceptually different from a term that doesn't appear at all.  Nonetheless, it's valid for the sake of calculating rank.
$$
O = \begin{bmatrix}
1&0&1&0\\
0&-10&0&0\\
-10&0&0&0\\
0&-100&0&0
\end{bmatrix}
$$
Conclusion
Both approaches show one three columns with linear independence and one without.  Therefore the rank is 3.

A: You've evaluated it correctly although it is easier to see the rank through the columns in this case. The last column of zeros places an upper bound on the rank at 3; from that alone you can conclude the system is not observable. Specifically, the first three columns are linearly independent so then you can conclude the rank is 3 and therefore you can only observe the evolution of the system in a 3 dimensional subspace of the entire state-space.  Note that last column of zeros indicate that you cannot observe the evolution of the 4th state.


text:
Q: How do I display in HTML the cover of an epub book using epub.js? I'm using EPUB.js and Vue to render an Epub. I want to display the cover images of several epub books so users can click one to then see the whole book.
There's no documentation on how to do this, but there are several methods that indicate that this should be possible.
First off, there's Book.coverUrl() method.
Note that I'm setting an img src property equal to bookCoverSrc in the Vue template. Setting this.bookCoverSrc will automatically update the src of the img tag and cause an image to display (if the src is valid / resolves).
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
  this.book.coverUrl().then((url) => {
    this.bookCoverSrc = url;
  });
})

The above doesn't work. url is undefined.
Weirdly, there appears to be a cover property directly on book. So, I try:
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
  this.coverSrc = this.book.cover;
});

this.book.cover resolves to OEBPS/@public@vhost@g@gutenberg@html@files@49010@49010-h@images@cover.jpg, so at least locally when I set it to a src results in a request to http://localhost:8080/OEBPS/@public@vhost@g@gutenberg@html@files@49010@49010-h@images@cover.jpg, which 200s but returns no content. Probably a quirk of webpack-dev-server to 200 on that, but if I page through sources in Chrome dev tools I also don't see any indicate that such a URL should resolve.
So, docs not helping. I googled and found this github question from 2015. Their code is like
$("#cover").attr("src", Book.store.urlCache[Book.cover]);

Interesting, nothing in the docks about Book.store.urlCache. As expected, urlCache is undefined, though book.store exists. I don't see anything on there that can help me display a cover image though.
Using epub.js, how can I display a cover image of an Epub file? Note that simply rendering the first "page" of the Epub file (which is usually the cover image) doesn't solve my problem, as I'd like to list a couple epub files' cover images.
Note also that I believe the epub files I'm using do have cover images. The files are Aesop's Fables and Irish Wonders.
EDIT: It's possible I need to use Book.load on the url provided by book.cover first. I did so and tried to console.log it, but it's a massive blog of weirdly encoded text that looks something like:
����

So I think it's an image straight up, and I need to find a way to get that onto the Document somehow?
EDIT2: that big blobby blob is type: string, and I can't atob() or btoa() it.
EDIT3: Just fetching the url provided by this.book.cover returns my index.html, default behavior for webpack-dev-server when it doesn't know what else to do.
EDIT4: Below is the code for book.coverUrl from epub.js
    key: "coverUrl",
    value: function coverUrl() {
        var _this9 = this;

        var retrieved = this.loaded.cover.then(function (url) {
            if (_this9.archived) {
                // return this.archive.createUrl(this.cover);
                return _this9.resources.get(_this9.cover);
            } else {
                return _this9.cover;
            }
        });

        return retrieved;
    }

If I use this.archive.createUrl(this.cover) instead of this.resources.get, I actually get a functional URL, that looks like blob:http://localhost:8080/9a3447b7-5cc8-4cfd-8608-d963910cb5f5. I'll try getting that out into src and see what happens.

A: The reason this was happening to me was because the functioning line of code in the coverUrl function was commented out in the source library epub.js, and a non-functioning line of code was written instead.
So, I had to copy down the entire library, uncomment the good code and delete the bad. Now the function works as it should.
To do so, clone down the entire epub.js project. Copy over the dependencies in that project's package.json to your own. Then, take the src, lib, and libs folders and copy them somewhere into  your project. Find a way to disable eslint for the location you put these folders into because the project uses TAB characters for spacing which caused my terminal to hang due to ESLINT exploding.
npm install so you have your and epub.js dependencies in your node_modules.
Open book.js. Uncomment line 661 which looks like
      return this.archive.createUrl(this.cover);

and comment out line 662 which looks like
      // return this.resources.get(this.cover);

Now you can display an image by setting an img tag's src attribute to the URL returned by book.coverUrl().
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
  this.book.coverUrl().then((url) => {
    this.bookCoverSrc = url;
  });
})


text:
Q: Verification: DFA/NFA that accepts all strings over $\{0,1\}$ with exactly one block of $00$ I am trying to design a DFA or NFA that accepts all strings over $\Sigma = \{0,1\}$ in which the block $00$ appears only once.
Here is what I've tried.

Can you verify that this accepts all string over $\{0,1\}$ that has exactly one block of $00$?

A: Yes, you constructed your NFA correctly. Note that to convert your NFA to a DFA, you can simply remove the loop transition $\delta(q_3,1)=q_3$, include the loop transition $\delta(q_4, 1) = q_4$, and draw an extra circle around $q_4$ in order to include it in your set $F$ of final/accept states.