text:
Q: Prob. 1, Sec. 3.7, in Bartle & Sherbert's INTRO. TO REAL ANALYSIS: Removal of the zero terms of a convergent series does not affect the sum? Here is Prob. 1, Sec. 3.7, in the book Introduction to Real Analysis by Robert G. Bartle and Donald R. Sherbert, 4th edition:

Let $\sum a_n$ be a given series and let $\sum b_n$ be the series in which the terms are the same and in the same order as in $\sum a_n$ except that the terms for which $a_n = 0$ have been omitted. Show that $\sum a_n$ converges to $A$ if and only if $\sum b_n$ converges to $A$.

My Attempt:

In order to have a series at all for $\sum b_n$, we must of course assume that there are non-zero terms in $\sum a_n$; rather, we must also assume that there are infinitely many non-zero terms of the series $\sum a_n$, for otherwise both $\sum_{n=1}^\infty a_n$ and $\sum_{n=1}^\infty b_n$ be finite sums having the same non-zero terms and will thus be equal.

Am I right?

For the sake of definiteness, let us assume that $a_n = 0$ whenever $n$ is a prime number and that $a_n$ is non-zero otherwise. Let $\left( s_n \right)_{n \in \mathbb{N}}$ and $\left( t_n \right)_{n \in \mathbb{N}}$ be the sequences of the partial sums of $\sum a_n$ and $\sum b_n$, respectively.  Then we note that
  $$
\begin{align}
t_1 &= s_1 = s_2 = s_3, \\
t_2 &= s_4 = s_5, \\
t_3 &= s_6 = s_7, \\
t_4 &= s_8, \\
t_5 &= s_9, \\
t_6 &= s_{10} = s_{11}, \\
t_7 &= s_{12} = s_{13}, \\
t_8 &= s_{14}, \\
t_9 &= s_{15}, \\
t_{10} &= s_{16} = s_{17},
\end{align}
$$
  and so on and so forth. In this way, we observe that $\left( t_n \right)_{n \in \mathbb{N}}$ is a subsequence of $\left( s_n \right)_{n \in \mathbb{N}}$ and therefore the former sequence has the same limit as the latter.

Is this kind of "proof" satisfactory enough, I wonder? I would like to make it more general and rigorous though.

Reading off the above array from the right to left, we observe that the terms of the sequence $\left( s_n \right)_{n \in \mathbb{N}}$ also appear in the sequence $\left( t_n \right)_{n \in \mathbb{N}}$ and the predecessor-successor relationship between terms is preserved in passing from the latter sequence to the former. Thus (intuitively at least) the former sequence cannot have any limit different from the limit of the latter sequence.

How to make this part of my argument more precise and rigorous, employing only what has preceded this particular exercise problem in the book?
In general, how to give a proof of each one of the two parts in the full level of generality, rigor, and detail?

A: Let $\sum a_n$  and $\sum b_n$ be two series satisfying the hypothesis
Let $s_n = a_1 + a_2 + a_3 + \cdots +a_n $,
and let
$t_n = b_1+ b_2 + b_3 + \cdots + b_n $ be the sequences of the partial sums of $\sum a_n$ and $\sum b_n$, respectively.
Suppose there are $m$ terms $a_i$ equal to 0 in the partial sum of $a_n$
Thus, $n-m$ non-zero terms are there in the sum $s_n$ , which is exactly the first $n-m$ terms of $\sum b_n$.
Thus,
$$s_n = t_{n-m}. $$
Therefore , if $s_n$ converges, then $t_n$ converges. And, conversely, if $t_n$ converges then $s_n$ converges.
Let $lim s_n = lim  t_n = \alpha$, say.
Hence $\sum a_n$ converges to $\alpha$ $\iff$ $\sum b_n$ converges to $\alpha$.


text:
Q: When deploying to github pages, fetch is working from my pc but not from my smarphone I am trying to learn by doing this game
https://domindez.github.io/mistery/
The problem is that fetch is not working from my phone when I am working in localhost:3000, and it's also not working after I deployed to GitHub pages.
But if I go try from my pc then it works perfectly, in local and on GitHub pages.
This is one of my fetch:
  window.onload = function () {

  fetch("http://localhost:3000/api/onload", {
    method: "GET",
  })
    .then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => {
      console.log(response);
      setCurrentStatus(response);
    });
}

A: Whatever server you want http://localhost:3000/api/onload to react is running on your PC.
localhost is the private loopback address hostname. It means "This computer".
It works when you access the page from your PC because it is running on your PC.
localhost for your phone is your phone, where you aren't running the server.

You need to run the server somewhere accessible from every device you want to access it (be that your LAN or the public Internet) and change the hostname to an IP address on that network.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to diagnose issues in web page and png file via edm Png file
I want to ask few questions:
1. What is EDM.
2. How to diagnose issues in a web page and .png file via EDM.

A: EDM on IT words, can be an acronym for:

*

*Event Driven Marketing

*Electronic Direct Marketing

*Email Direct Marketing

*Electronic Direct Mail

*Enterprise Data Management

*Electronic Document Management

*Enterprise Data Modeling

*Entity Data Model

*Enterprise Decision Management

*...

i don't know if i've let some related out.
I don't know in which context you are, and it seems to rare to diagnose issues on a png file using "EDM".
It seems that you're asking some homework question on SO without googling it on the correct ambit.
Anyway, i think you're talking about EDMX:
EDMX is Visual Studio's "container" for all things about your Entity Data Model.
It contains all the information that is in the CSDL, SSDL, MSL, plus information about the visual layout of the tables in your Visual Studio designer surface.
The EDMX file is converted into CSDL, SSDL, MSL (typically embedded as resources in your assembly) during the build process. You definitely don't have to distribute or copy the EDMX files anywhere for the app to run.
if you are more interested in a code-based approach, you should check out the code-first CTP for Entity Framework which gets by without any .edmx, .csdl/ssdl/msl files at all.
You may need to do a research and ask it properly (i think your question will be highly down-voted)


text:
Q: Is this a safe way to store my passwords? I've been reading around a few different guides/tutorials on this topic and found the following:

*

*Storing Passwords Securely using Salt in PHP

*Secure Hash and Salt for PHP Passwords (Top Answer)
I know that what I've read there is a very secure way to store a users password. I've made an attempt to combined the 2 slightly while instead of using mt_rand like in the first example, I've generated my own dynamic salt.
Here is my code:
<?php

    $static_salt = ""; // Removed value for obvious reasons

    $dynamic_salt_choice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $dynamic_salt_length = 40;

    $dynamic_salt = "";

    $dynamic_salt_max = strlen($dynamic_salt_choice)-1;

    for ($i = 0; $i < $dynamic_salt_length; $i++) {

        $dynamic_salt .= substr($dynamic_salt_choice, rand(0, $dynamic_salt_max), 1);

    }

    $password_length = length($password);
    $split_at = $password_length / 2;
    $password_array = str_split($password, $split_at);

    $password = $password_array[0] . $static_salt . $password_array[1];

    $password_hash = hash_hmac('sha512', $password, $dynamic_salt);

?>

According to me this is fetching a static salt, generating a dynamic salt, we're then splitting the given password in 2 parts in an array and adding the static salt in between the two password sections.
We are then hashing the password with sha12 along with the dynamic salt.
My question to you is, is this more secure or just as secure as the 2 methods I've linked to? Or am I making it more vulnerable by mixing things up this way?
I also take it storing $password_hash in a cookie along side a username cookie for automatic login is a big no-no? If so, how do websites remember you through cookies in a secure manner?

A:
I'm trying to increase the level of security with my sites

well, to let you know, no password hashing ussue can increase your site security even a bit.
You have to focus on the other, much more important things such as SQL and file injections, XSS and CSRF vulnerabilities. If you keep your site secure, it will keep your passwords as well safe just as a side effect.
Next thing you have to focus on, is password strength. No hash can secure a a silly password like joe or 123.
As for the hashing itself - you can use whatever you wish, some basic things like using some sane salt like registration time or email and some number of iterations of whatever hashing function is enough. Don't put too much meaning in hashing. it is not the thing that requires SO much attention as inventing some extra-secure original algorithm.

My question to you is, is this more secure or just as secure as the 2 methods I've linked to? Or am I making it more vulnerable by mixing things up this way?

Dunno if you trust me (I bet you won't) but ALL these methods are secure enough and require no impreovement. And affect no security of the site but only passwords themselves in case they are stolen using another vulnerability in your site.

I also take it storing $password_hash in a cookie along side a username cookie for automatic login is a big no-no?

I don't think it's wise thing to reveal a hash itself. But again, it affects no site security but  passwords potential vulnerability only. If your hash and password are strong enough, a logic is making me to say that it is safe enough.

A: This seems like a reasonable salting scheme, although possibly overkill. It probably doesn't need to be 40 characters long - you're just trying to blow up the size of a rainbow table, not make an unguessable nonce - but making it long won't hurt.
As for autologin, you should store (in a cookie) a random token that corresponds to a database entry pointing to the user's account. When the user changes their password, erase all these entries for that user. When generating this token, rand() isn't good enough - you need a secure, unguessable random number. Unfortunately, PHP doesn't really have a built-in facility for secure random numbers - mt_rand() is about as close as it gets, but I personally would directly read random bytes from /dev/urandom on a Linux system and use that to generate my nonce.

A: Assuming that the $dynamic_salt is stored alongside the final $password_hash -- since the hash wouldn't be testable without it -- this scheme is quite weak. Using a salt does protect against rainbow tables, but a non-iterated HMAC leaves this scheme weak to brute-force attacks. (The length of the salt does you no good, as it's a known constant in the hash input. Putting it in the middle of the original password doesn't really help either.)
Overall, this scheme is far weaker than bcrypt(), as it only (effectively) iterates the hash twice. You're really no better off than if you simply were storing the password using a simpler scheme such as:
$salt = uniqid();
$password_hash = hash_hmac('sha512', $password, $salt);

But you're still better off using someone else's (tried and tested) password encryption routine, rather than cooking your own.

With regard to using the password hash in a cookie -- this is to be avoided, as it allows an attacker with read-only access to the database (e.g, via a SQL injection attack or a stolen backup) to impersonate any user in your application without knowing or changing their password. It also means that, if a user's computer has been set to automatically log in, the password hash is stored on it. I'd avoid this.
A better scheme might be to set a randomly generated nonce in a cookie when a user chooses to log in automatically, then store a hash of that nonce in the database. This way, the server can check the correctness of a login key without ever having to "remember" it.

A: Salts can be used,but it has got its own limitations. Another way is using bcrypt.More information can be found at http://www.openwall.com/phpass/
And i think This SO article is more than enough Secure hash and salt for PHP passwords


text:
Q: Add data inside documents in Mongo DB using PHP I want to insert data in Mongo database using PHP script, in year wise documents so that it may look like this (All years in one document);
cars{
        2017{
            car=Motorolla
            color = blue
        }
        2016{
            car=Toyota
            color = green
        }
        2015{
            car=Corolla
            color = black
        }
    }

I wanted to add the document but it prompts

Document can't have $ prefixed field names: $years[0]

Is it possible to make such schema in Mongo using PHP?
Code
<?php
    try {
        $car = 'Motorolla';
        $color = 'blue';

        //$car = 'Toyota';
        //$color = 'green';

        //$car = 'Corolla';
        //$color = 'black';

        $years = array(2017, 2016, 2015);
        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;
        $document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color];   // Making a query type

        try {
            $bulkWriteManager->insert($document);   // Inserting Document
            echo 1;
        } catch(MongoCursorException $e) {
            /* handle the exception */
            echo 0;
        }

        $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager);  // Going to DB and Collection

    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n";
        echo "It failed with the following exception:\n";
        echo "Exception:", $e->getMessage(), "\n";

    }

?>

I do not want to add whole car object at once. I want to add Year object every time. Any help will be appreciable.
OR
Any relative answer so that I may get the data from Mongo Database according to the year?
Edit1
For first time creation. - Credits goes to @Veeram
<?php
    try {
        $car = 'Malibu';
        $color = 'red';
        $years = array(2017);

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;
        //{"car":"chevy", "color":"black", year: 2017}
        $insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
        try {
            $bulkWriteManager -> insert($insert); // Inserting Document
            echo 1;
        } catch (MongoCursorException $e) {
            echo 0;
        }
        $manager->executeBulkWrite('dbName.mycol', $bulkWriteManager);  // Going to DB and Collection
    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n";
        echo "It failed with the following exception:\n";
        echo "Exception:", $e->getMessage(), "\n";
        echo "In file:", $e->getFile(), "\n";
        echo "On line:", $e->getLine(), "\n";
    }
?>

For the updation- Credits goes to @Veeram
<?php
    try {
        $car = 'ChangedCar';
        $color = 'changedColor';
        $years = array(2017);

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;

        $query = ['cars.year' => $years[0]];

        //{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
        $update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
        try {
            $bulkWriteManager->update($query, $update);   // Inserting Document
        } catch(MongoCursorException $e) {

        }
        $manager->executeBulkWrite('dbName.mycol', $bulkWriteManager);  // Going to DB and Collection
    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n";
        echo "It failed with the following exception:\n";
        echo "Exception:", $e->getMessage(), "\n";
    }
?>

The problem in this code is that it successfully insert the data for the first time but when i update the data it does not update it.
Example:
There is a document named as cars . Insert the data with object of year in one document. Let's say the Object is 2017, it  contains color and car Model. As showing below; (Multiple objects with years. Year is unique in whole document.)
cars{
        2017{
            car=Motorolla
            color = blue
        }
        2016{
            car=Toyota
            color = green
        }
        2015{
            car=Corolla
            color = black
        }
    }

If I want to update just make an object of 2017 like 2017{car=Updated-Motorolla color =Updated-blue} and insert in the document. It should update only the year 2017 object in side the document.
 cars{
            2017{
                car=Updated-Motorolla
                color =Updated-blue
            }
            2016{
                car=Toyota
                color = green
            }
            2015{
                car=Corolla
                color = black
            }
        }

A: You can try something like this. Its not possible to perform all the Mongo db operations just based off key as a value.
The first solution is written to stay close to OP's design.
Assuming you can add a key to the year.
{
  "cars": [{
      "year": "2017",
      "data": [{
          "car": "Motorolla",
          "color": "blue"
      }]
  }, {
      "year": "2016",
      "data": [{
          "car": "Toyota",
          "color": "green"
      }]
  }]
}

Makes it easy to reference the year by its value.
For example to add a new value into the data array for year 2017. You can try the below code.
Uses update positional $ operator.
query part to reference the array where 2017 record is stored.
update part using push to add the new car record to the existing data array for 2017 row.
<?php
    try {
        $car = 'Malibu';
        $color = 'blue';
        $years = [2017];

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $bulkWriteManager = new MongoDB\Driver\BulkWrite;

        //{"cars.year":2017}
        $query = ['cars.year' => $years[0]];

        //{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
        $update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];

        try {
            $bulkWriteManager->update($query, $update);  // Update Document
            echo 1;
        } catch(MongoCursorException $e) {
            /* handle the exception */
            echo 0;
        }

        $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager);  // Going to DB and Collection

    } catch (MongoDB\Driver\Exception\Exception $e) {
        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n";
        echo "It failed with the following exception:\n";
        echo "Exception:", $e->getMessage(), "\n";
    }

?>

For accessing data by year you can run below query.
Use query positional $operator to find the array index using the query part and reference that value in projection part.
db.collection.find({"cars.year":2017}, {"cars.$.data":1});

Alternative Solution :
This will take care of everything as just inserts
You are better off saving each car entry in its own document.
{ "year" : 2017, "car" : "Motorolla", "color" : "blue" }
{ "year" : 2016, "car" : "Toyota", "color" : "green" }
{ "year" : 2015, "car" : "Corolla", "color" : "black" }

For each entry you can use:
db.collection.insert({"year":2017,  "car":"Motorolla", "color":"blue"});

PHP Code:
 //{"car":"chevy", "color":"black", year: 2017}
 $insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];

 try {
    $bulkWriteManager - > insert($insert); // Inserting Document
    echo 1;
 } catch (MongoCursorException $e) {
    /* handle the exception */
    echo 0;
 }

For access data by year you can use
db.collection.find({"year":2017});

Updated PHP code:
<?php
try {
  $cars = ['Motorolla','Toyota', 'Corolla'] ;
  $colors = ['blue', 'green', 'black'];

  $years = [2017, 2016, 2015];
  $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
  $bulkWriteManager = new MongoDB\Driver\BulkWrite;

  $query1 =["year" => $years[0]];
  $query2 =["year" => $years[1]];
  $query3 =["year" => $years[2]];

  $update1 = ['$set' => ['car' => $cars[0], 'color' => $colors[0]]];
  $update2 = ['$set' => ['car' => $cars[1], 'color' => $colors[1]]];
  $update3 = ['$set' => ['car' => $cars[2], 'color' => $colors[2]]];

  try {
    $bulkWriteManager->update($query1, $update1, ["upsert" => true]);
    $bulkWriteManager->update($query2, $update2, ["upsert" => true]);
    $bulkWriteManager->update($query3, $update3, ["upsert" => true]);
     echo 1;
  } catch(MongoCursorException $e) {
  /* handle the exception */
  echo 0;
  }

  $manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection

  } catch (MongoDB\Driver\Exception\Exception $e) {
    $filename = basename(__FILE__);
    echo "The $filename script has experienced an error.\n";
    echo "It failed with the following exception:\n";
    echo "Exception:", $e->getMessage(), "\n";
  }
?>

You can perform complex queries using aggregation pipeline and you can add index to make your response quicker.
Observations:
First Solution : Harder to update/insert data, but keeps everything together so easier to read data.
Second Solution :
Cleaner and simpler to do CRUD operations on documents and use aggregation pipeline to preform complex queries.

A: Try to change
$document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color];

to something like:
$document = ['_id' => new \MongoDB\BSON\ObjectID, $years[0] => ['car' => $car, 'color' => $color]];

it gives such result in mongo:
{ "_id" : ObjectId("58a936ecfc11985f525a4582"), "2017" : { "car" : "Motorolla", "color" : "blue" }

If data about all cars must be in one document, you need to combine data fitst:
$cars = [
    '2017' => [
        'car' => 'Motorolla',
        'color' => 'blue'
    ],
    '2016' => [
        'car' => 'Toyota',
        'color' => 'green'
    ],
    '2015' => [
        'car' => 'Corolla',
        'color' => 'black'
    ]
];

and than
$document = ['_id' => new \MongoDB\BSON\ObjectID, 'cars' => $cars];

It gives mongo document like:
{ "_id" : ObjectId("58aabc0cfc11980f57611832"), "cars" : { "2017" : { "car" : "Motorolla", "color" : "blue" }, "2016" : { "car" : "Toyota", "color" : "green" }, "2015" : { "car" : "Corolla", "color" : "black" } } }


text:
Q: Scraping Daraz.pk I am new to scraping and i would like to scrape products and prices from daraz.pk . I learned from a tutorial and was able to scrape data from amazon but not able to do it in daraz.
Please can anyone tell me how get the laptop product name from this link: https://www.daraz.pk/gaming-laptops/?spm=a2a0e.home.cate_1_4.1.35e349375wfPov
i tried using response.css("c16H9d::text").extract() but not able to retrieve any data.
Regards

A: I have written this code for grooming category of Daraz.pkl. However, if you want to scrape other products, just add link of that page in Url and add required xpath below.
import bs4 as bs
import re
from selenium import webdriver
name=[]
price=[]
url = 'https://www.daraz.pk/dog-grooming-supplies/'

driver = webdriver.Chrome('chromedriver')
driver.get(url)
for i in range(1,40):
  target_name=driver.find_element_by_xpath('//*[@id="root"]/div/div[3]/div[1]/div/div[1]/div[2]/div['+str(i)+']/div/div/div[2]/div[2]/a')
  target_prize=driver.find_element_by_xpath('//*[@id="root"]/div/div[3]/div[1]/div/div[1]/div[2]/div['+str(i)+']/div/div/div[2]/div[3]/span')
name.append(target_name.text)
price.append(target_prize.text)

driver.quit()
print(name)
print(price)

Adjust the intend, if you find any problem and do let me know, if you find any problem


text:
Q: Is the service account mandatory for google app marketplace listing We are trying to list our app in google app marketplace, and it is domain installable app. Is the creation of service account mandatory in this case?

A: https://firebase.google.com/`

emphasized textgoogle.com/
://

*

*publish/

`


text:
Q: Half of my monitor has suddenly turned green since yesterday When I'm on Discord, half of my monitor suddenly turns green. I've tried restarting it, but it didn't work.
I have tried all the tricks but none of them work.


text:
Q: changing the width of the text input when hover i am a beginner at CSS. i am trying to change the width of the input to 120px when i hover over the search text. how do i do it? i have try few code, but it doesn't seem to work.
html

    <input class="search-text" type="text" placeholder="type something">
    search

CSS
a:hover + .search-text{`
width:125px;
}

A: Css
There isn't a nice CSS selector that allows us to target a element when an other element is behing hovered.
There is a way, described in this question, but that expects the element to exist after the hover element seen in the DOM. Your current HTML is reversed, so that wont work.
The easiest way, in my opinion, is to use flex-direction to reverse the DOM element so we can use the 'hack' described in the linked post.
Example:

a:hover ~ .search-text {
  width:200px;
}

.search-box {
  display: flex;
  justify-content: flex-end;
  flex-direction: row-reverse;
}

.search-button {
  margin-left: 10px;
}

  search
  <input class="search-text" type="text" placeholder="type something">

NB: Since the <input> is getting larger, the mouse isn't hovering on the element anymore, therefor it will shrink again, letting the mouse back over the element, this causes the weird jumping effect.

jQuery
Of course we can create a jQuery based solution using the mouseover and mouseleave events. This way we

*

*Don't need to change the DOM order

*Prevent the <input> jumping by checking on mouseleave on the <input> instead off the
Example:

let i = $('.search-text'),
    a = $('.search-button');
i.width(150);

a.on('mouseover', function() {
    i.width(300);
});

i.on('mouseleave', function() {
    i.width(150);
});

  <input class="search-text" type="text" placeholder="type something">
  search

A: Try this:
CSS

.search-text:hover{
width: 120px;
}

    <input class="search-text" type="text" placeholder="type something">
    search

NB : you are trying to decrease the width.

A: To do this without Javascript you will have to wrap your input element inside of a(anchor) tag something like this--
try out the code below

a:hover .search-text{
  width: 120px;
}

      <input class="search-text" type="text" placeholder="type something">search

A: From 0stone0 answer :)

.search-box:hover > .search-text {
  width:125px;
}

    <input class="search-text" type="text" placeholder="type something">
    search

A:

.searchbox > input[type='text']{
  border : 1px solid rebeccapurple;
  outline: none;
  transition : 0.7s;
}

.searchbox > input[type='text']:hover{
  padding-right: 300px;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

      <input type="text" placeholder="search">


text:
Q: r - plotting gantt chart where multiple periods exist within one category I borrowed example data from another post and modified to suit my situation.
(Add shading to a gantt chart to delineate weekends)
My issue with plotting a Gantt chart is that my data includes multiple periods within the category.
In the below sample, I added two more periods for "Write introduction" and one more for "Write results".
Also, I want to colour specific periods that meet the criteria. Here, if any portion of a period falls in either May or August, I flagged it.
It seems having up to two periods in one category works fine.
But when there are three periods, they become merged into a single period?!
My real dataset is much more complicated with one category sometimes having more than 10 periods, with very defined criteria for flagging.
I'm not sure how I could address this issue.

require(reshape2)
require(ggplot2)

# Create a list of tasks name strings.
tasks <- c("Write introduction", "Parse citation data",
           "Construct data timeline",
           "Write methods", "Model formulation",
           "Model selection", "Write results", "Write discussion",
           "Write abstract and editing",

           "Write introduction", "Write introduction", "Write results")

# Compile dataframe of task names, and respective start and end dates.
dfr <- data.frame(
  name = factor(tasks, levels = tasks[1:9]),
  start.date = as.Date(c("2018-04-09", "2018-04-09", "2018-04-16",
                         "2018-04-30", "2018-04-16", "2018-05-21",
                         "2018-06-04", "2018-07-02", "2018-07-30",

                         "2018-05-15", "2018-06-03", "2018-07-25"
                         )),
  end.date = as.Date(c("2018-04-30", "2018-04-20", "2018-05-18",
                       "2018-06-01", "2018-05-18", "2018-06-01",
                       "2018-06-29", "2018-07-27", "2018-08-31",

                       "2018-05-29", "2018-06-20", "2018-08-15")),
  flag = c(0, 0, 1,
           1, 1, 1,
           0, 0, 1,
           1, 0, 1)
)

# Merge start and end dates into durations.
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

# gannt chart

ggplot(mdfr) +

  geom_line(aes(value, name, colour = as.factor(flag)), size = 4) +
  labs(title = "Project gantt chart",
       x = NULL,
       y = NULL) +
  theme_minimal()

A: I solved it by skipping melt and using geom_linerange instead of geom_line
ggplot(dfr) +
  geom_linerange(aes(y = name,
                     xmin = start.date,
                     xmax = end.date,
                     colour = as.factor(flag)),

                 size = I(5)) +
  theme_minimal()

Still, it would be good to know why it didn't work with geom_line.
If anyone could help me with that, I'd appreciate it very much!

A: The geom_line approach should work if you retain an identifier for each pair of start / end dates, and specify that as the grouping variable so that ggplot knows which coordinates belong to the same line:
dfr$row.id <- seq(1, nrow(dfr)) # use row id to identify each original row uniquely
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

ggplot(mdfr,
       aes(x = value, y = name, colour = factor(flag), group = row.id)) + # add group aesthetic
  geom_line(size = 4) +
  labs(title = "Project gantt chart",
       x = NULL,
       y = NULL) +
  theme_minimal()


text:
Q: Display simple product SKU on config product pages after attribute selection I am looking to have the configurable SKU change to the corresponding simple product SKU when the configurable product attributes have been selected. Any help or suggestions would be appreciated.

A: Out of the box, when choosing options, the images and the price will change, but not SKU.
More information about which elements on the page change when options are selected can be found here: Magento\ConfigurableProduct\Block\Product\View\Type\Configurable::getJsonConfig().
In order to display product SKU of the selected product, you can create a Plugin (Interceptor) for Magento\ConfigurableProduct\Block\Product\View\Type\Configurable::getJsonConfig() where you need to add missing SKU for each simple product.
Switching SKU added in getJsonConfig() when selecting an option can be implemented in vendor/magento/module-swatches/view/base/web/js/swatch-renderer.js and vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js depending on the type of attribute.

I made free VCT Change SKU Dynamically module that solve this problem.


text:
Q: SQL Query, how to get data from table but only when it was inserted in another table Well, I didn't know how to explain this one on the title, so I'll be clearer here.
I have a couple of tables:
TiposDeCatalogo:
PK IdTipoCatalogo (int)
IdVendedor (int)
Nombre (string)
Descripcion (string)
Estado (string)
FechaAlta (date)

Catalogo:

PK IdCatalogo (int)
IdTipoCatalogo (int)
IdVendedor (int)
Nombre (string)
Descripcion (string)
Estado (string)
FechaAlta (date)

There is a foreign key on Catalogo.IdTipoCatalogo = TiposDeCatalogos.IdTipoCatalogo
I need a query that can show all rows on TiposDeCatalogo that have already been registered on Catalogo
For instance...
TiposDeCatalogos has the following rows
IdTipoCatalogo IdVendedor Nombre Estado FechaAlta

1   1   Catalogos de Ventas     Activo  20/08/2012
2   1   Catalogos de CRM        Activo  20/08/2012
3   1   Catalogos de Inventario     Activo  20/08/2012
4   1   Catalogos de Facturacion        Activo  04/09/2012
5   1   Catalogos de Cobranza       Activo  04/09/2012
6   1   Catalogos de Admin      Activo  04/09/2012
7   1   Catalogos de Admin      Activo  04/09/2012
8   1   Catalogos de Finanzas       Activo  04/09/2012
9   1   Catalogos de Clientes       Activo  04/09/2012
12  1   Catalogos de Administ General       Activo  04/09/2012

Then Catalogo has the following rows
IdCatalogo IdTipoCatalogo IdVendedor Nombre Estado FechaAlta

1   1   17  Formas de Pago  formas de pago para las ventas  Activo  01/09/2012
2   5   1   Tipos de Moneda     Activo  05/09/2012
3   2   1    Tipos de Agendamiento      Activo  05/09/2012
4   3   1   Tipos de Precios        Activo  06/09/2012
5   5   1    TIpos de Moneda        Activo  06/09/2012
6   3   1   Tipo de Presentacion        Activo  06/09/2012

You might notice that in Catalogo, only the following IdTipoCatalogo have been registered (1, 2, 3, 5)
So what I want, is a query that shows me those TiposDeCatalogos (only once each, so the query should only return 4 rows in this example)....
I hope you can help me, thanks

A: You can use EXISTS to accomplish this:
SELECT
    tc.IdTipoCatalogo,
    tc.IdVendedor,
    tc.Nombre,
    tc.Estado,
    tc.FechaAlta
FROM TiposDeCatalogos tc
WHERE EXISTS (
    SELECT 1
    FROM Catalogo c
    WHERE c.IdTipoCatalogo = tc.IdTipoCatalogo
)

Alternately, you could use a JOIN and DISTINCT:
SELECT DISTINCT
    tc.IdTipoCatalogo,
    tc.IdVendedor,
    tc.Nombre,
    tc.Estado,
    tc.FechaAlta
FROM
    TiposDeCatalogos tc
    JOIN Catalogo c ON c.IdTipoCatalogo = tc.IdTipoCatalogo

However, this will likely be less efficient, because the DISTINCT will require the additional operation to exclude the duplicates produced by the JOIN.


text:
Q: Gradle module package not found error I've 3 modules in my project:
Lib - apply plugin: 'com.android.library'
Proj A - apply plugin: 'com.android.application'
Proj B - apply plugin: 'com.android.application'
Both project inport the lib in their build.gradle file:
compile project(path: ':lib-module')
The settings.gradle imports it to:
include ':projectA-module', ':projectB-module', ':lib-module'
The gradle builds correctly, and I can import my lib classes inside my projects and navigate through the code. The only problem appears in compile time where I get this kind of errors showing that the lib classes and packages cannot be found:

Error:Gradle: Execution failed for task ':projectA-module:compileDebugJavaWithJavac'.
  Compilation failed; see the compiler error output for details.
  .../Class.java
  Error:(27, 42) Gradle: error: package com.mylib.somepackage does not exist

What's happening?


text:
Q: Can't get thumbnail from AVAsset In my Xamarin.Forms project, I use dependency injection to call a method inside my .iOS project in order to retrieve a thumbnail of a video that the user just recorded.
Called from my Xamarin.Forms project:
byte[] thumbnailBytes = DependencyService.Get<IMediaMetaData>().ReturnVidThumbnailBytes(vid.Path);

The following code is then called from the .IOS project:
public class MediaMetaData : IMediaMetaData
{
    public byte[] ReturnVidThumbnailBytes(string videoFilePath)
    {
        // videoFilePath example =
        // /var/mobile/Containers/Data/Application/3E84C0D0-F590-4AAF-89E7-7D3BFC023E6B/Documents/temp/trim_160491789522565DC08BE-862C-4EE0-A135-BCD9236C6874.mov

        //Take local url and create an AVAsset
        AVAsset asset = AVAsset.FromUrl(new NSUrl(videoFilePath));

        AVAssetImageGenerator assetImageGenerator = AVAssetImageGenerator.FromAsset(asset);

        // Total duration of asset
        CMTime actualTime = asset.Duration;

        // 1/60 = 60th of a second
        CMTime cmTime = new CMTime(1, 10);

        NSError error;
        var imageRef = assetImageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error);

        if (imageRef == null)
            return null;

        var image = UIImage.FromImage(imageRef);
        return image.AsJPEG().ToArray();
    }
}

The problem:
CopyCGImageAtTime always returns null. I check the NSError and I get the following information:
Class Handle = Unable to cast object of type 'Mono.Debugger.Soft.PointerValue' to type 'Mono.Debugger.Soft.PrimitiveValue
code = -11850
Localized failure reason = The server is not correctly configured (But wait, this is a local file I'm accessing here...?)
I've not been able to find any helpful information regarding the class handle error, and the localized failure reason brings up threads from people who are trying to access videos from web services as opposed to local storage. Anyone have experience with the problem I'm having?


text:
Q: Criteria - where clause on joined table I have two tables in a MySQL database: COURSE and COURSE_SESSION.
COURSE has two fields : code(primary key) and title.
CourseSession has a field called course_code which is a foreign key linked to an element of Course.
I want to do somthing like this but using the Criteria API in Java :
SELECT * FROM COURSE_SESSION join COURSE
WHERE course_code = code AND title like "%substring%";
Both tables are mapped correctly with hibernate.
I tried this :
Criteria criter = s.createCriteria(CourseSession.class);
        criter.add(Restrictions.like("courseCode.title", "%substring%"));
But I end up with an error :
HTTP 500 - could not resolve property: courseCode.title of: org.xxx.core.entity.CourseSession

message could not resolve property: courseCode.title of: org.xxx.core.entity.CourseSession

exception

org.hibernate.QueryException: could not resolve property: courseCode.title of: fr.utbm.lo54.core.entity.CourseSession
    org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:81)
    org.hibernate.persister.entity.AbstractPropertyMapping.toColumns(AbstractPropertyMapping.java:96)
    org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:62)
    org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1443)
    org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:483)
    org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumnsUsingProjection(CriteriaQueryTranslator.java:443)
    org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:68)
    org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:380)
    org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:114)
    org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:83)
    org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:92)
    org.hibernate.impl.SessionImpl.list(SessionImpl.java:1687)
    org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
    fr.utbm.lo54.core.servlet.SearchData.doGet(SearchData.java:52)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

The strange thing is that if I do a Restriction on courseCode.code   with Restrictions.like("courseCode.code", "%substring%"), it works fine.
EDIT
Course.hbm.xml :
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.xxx.core.entity">
    <class name="Course" table="COURSE">
        <id name="code" column="CODE">
            <generator class ="identity"/>
        </id>
    <property name="title" column="TITLE" not-null="true"/>
    </class>
</hibernate-mapping>

CourseSession.hbm.xml :
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.xxx.core.entity">
    <class name="CourseSession" table="COURSE_SESSION">
        <id name="id" column="ID">
            <generator class="identity" />
        </id>

        <property name="startDate" column="START_DATE" not-null="true" />
        <property name="endDate" column="END_DATE" not-null="true" />
        <many-to-one name="courseCode" column="COURSE_CODE" />
        <many-to-one name="locationId" column="LOCATION_ID" />
    </class>
</hibernate-mapping>

A: create an alias for the field first to achieve this.
try the below code, it should help
criter.createAlias("courseCode","courseCode");//course code is the association variable in your pojo class.


text:
Q: Triangular matrices and commutators From Humphreys' Introduction to Lie Algebras and Representation Theory:

We conclude this subsection by mentioning several other subalgebras of $gl(n,F)$ which play an important subsidiary role for us. Let $t(n,F)$ be the set of upper triangular matrices $(a_{ij})$, $a_{ij}=0$ if $i>j$. Let $n(n,F)$ be the strictly upper triangular matrices ($a_{ij}=0$ if $i\geq j$). Finally, let $o(n,F)$ be the set of all diagonal matrices. It is trivial to check that each of these is closed under the bracket. Notice also that $t(n,F)=o(n,F)+n(n,F)$ (vector space direct sum), with $[o(n,F),n(n,F)]=n(n,F)$, hence $[t(n,F),t(n,F)]=n(n,F)$. (If $H,K$ are subalgebras of $L$, $[H K]$ denotes the subspace of $L$ spanned by commutators $[xy]$, $x\in H, y\in K$.)

I am confused about why $[t(n,F),t(n,F)]=n(n,F)$. If we have two upper triangular matrices $X,Y$, then $XY$ is also upper triangular, and so $XY-YX$ is upper triangular, so it should stay in $t(n,F)$. But I don't see why $XY-YX$ should be strictly upper triangular.

A: Two things make it easy to see that the commutator of upper triangular matrices is a strictly(1) upper triangular matrix:

*

*diagonal matrices commute,

*the product of an upper triangular matrix and a strictly upper triangular matrix is strictly upper triangular.

The multiplication of diagonal matrices amounts to multiplication of corresponding diagonal elements, and since/if multiplication in $F$ is commutative, that entails the commutativity of multiplication in $o(n,F)$.
To see that the product of a strictly upper triangular matrix with an upper triangular matrix is strictly upper triangular (I assume it already known that the product is upper triangular), consider the generic diagonal element of the product,
$$c_{ii} = \sum_{k=1}^n a_{ik} b_{ki} = \sum_{k=1}^i a_{ik}b_{ki} = \sum_{k=i}^i a_{ik}b_{ki} = a_{ii}b_{ii};$$
the first reduction of the range $k$ traverses is because $B$ is upper triangular, hence $b_{ki} = 0$ for $k > i$, the second because $A$ is upper triangular, hence $a_{ik} = 0$ for $k < i$, and that leaves only $a_{ii}b_{ii}$. One of the factors is $0$ since one of $A$ and $B$ is strictly upper triangular by assumption.
Thus, when we have two upper triangular matrices $X$ and $Y$, write them as $X = D_X + S_X,\; Y = D_Y + S_Y$ with diagonal $D_\ast$ and strictly upper triangular $S_\ast$, to find
$$\begin{align}
[X,Y] &= [D_X+S_X,Y] = [D_X,Y] + [S_X,Y]\\
&= [D_X, D_Y + S_Y] + [S_X,D_Y + S_Y]\\
&= [D_X,D_Y] + [D_X,S_Y] + [S_X,D_Y] + [S_X,S_Y]\\
&= [D_X,S_Y] + [S_X,D_Y] + [S_X,S_Y]
\end{align}$$
and all products that remain involve at least one strictly upper triangular matrix, hence are strictly upper triangular.

(1) If the ring of scalars is commutative.


text:
Q: Angular - Strapi Upload file during entry creation through formdata I followed the documentation from Strapi to upload file during entry creation, but the data from Angular is not sending properly to the back. I tested the back with Postman and it works perfectly, so I guess the formData object is not creating properly.
Here is my submit action:
async onSubmit() {
    if (this.form.valid) {
      const formData = new FormData();
      formData.append('files.resume', this.form.get('resume').value);
      formData.append('data', JSON.stringify(this.form.value));

      const res = await this.apiService.addResume(formData);
    }
}

And the back is giving me:
error error: invalid input syntax for integer: "[object Object]"

If I console the formData entries, it looks like I want (exactly like when I insert data in Postman), so I don't know where the problem is.


text:
Q: populate comboBox with both Name and Value, I'm have a combobox listing some single byte cmds that can be sent to some custom hardware I've developed.  With the C# code below, users can currently select commands from the cbCANcmd by name only.  I also found ways to display the values only, but prefer to display both name and number.

*

*How can I display both hex value & cmd in the cb dropdown? e.g. 0d - CommsSoftReset

*And still able to type in un-enumerated values, like 05, for unlisted commands?

*Can I hide more dangerous items easily(i.e. 09-WipeAllFlash), but still numerically enter them as per #2 above?

Note: The enum is from a straight C language .h file, and the header is changing more times daily than the c# app.  For this reason, I'm hoping to avoid adding [Description()] for each value, or dramatically change the formatting, since it will have to be copied and redone many times as we continue development)
P.S. I normally write only in simple C, for the 8bit micro receiving these commands..As this is my first test app in c#, please be gentle :)
enum COMMS_MESSAGE_ID_t : byte
{
    CommsRAMRead = 0x00,
    CommsRAMWrite = 0x01,
    CommsCommitRAMbufferToFlash = 0x02,

    CommsWipeAllFlash = 0x0c,
    CommsSoftReset = 0x0d,

    CommsGetVersion = 0xff
}

private void SendTab_Enter(object sender, EventArgs e)
{
    //need to populate the pulldowns with the available commands
    cbCANcmd.DataSource = Enum.GetValues(typeof(COMMS_MESSAGE_ID_t));
}

private void SendDownlinkCmd_Click(object sender, EventArgs e)
{
    // send the command selected in the send tab's combobox
    byte CANcmd = (byte)(COMMS_MESSAGE_ID_t)cbCANcmd.SelectedValue;//first byte
}

A: If this is a WinForms app, here is a possible solution for #1. If this works, we can move on from there.
public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (var val in Enum.GetNames(typeof(COMMS_MESSAGE_ID_t)))
        {
            cbCANcmd.Items.Add(new CommsMessage(val));
        }
    }

}

public class CommsMessage
{
    public string Name { get; set; }
    public COMMS_MESSAGE_ID_t Message { get; set; }

    public CommsMessage(string msgName)
    {
        Name = msgName;
        Message = (COMMS_MESSAGE_ID_t)Enum.Parse(typeof (COMMS_MESSAGE_ID_t), msgName);
    }

    public override string ToString()
    {
        return string.Format("{0:x} - {1}", Message, Name);
    }
}

Then, any time you get the value of the ComboBox.SelectedItem, you can do something like:
COMMS_MESSAGE_ID_t msg = (cbCANcmd.SelectedItem as CommsMessage).Message;

I've left out lots of exception handling that you should probably do, but I hope this is helpful.


text:
Q: ¿Cómo se hace un array de objetos para luego emplear el Arrays.equals?
*

*¿Cómo lleno un array de objetos?

*¿Cómo uso el Arrays.equals?
En el main hago dos arrays y los trato de llenar pero la respuesta es: (en el final)

(claramente ya puse los get y set de cada uno, solo que seria demasiado largo el código y por eso los borre)

    package Edible_ingredients;
    import java.util.*;
    enum Categorias{vegetales, proteinas, carbohidratos};
    public class Edible_ingredients {

    private String cod;
    private String nombre;
    private int calorias;
    private Categorias Categoria;

    public Edible_ingredients() {

    }

    public Edible_ingredients(String cod,String nombre, int calorias,Categorias Categoria) {
        this.cod=cod;
        this.nombre=nombre;
        this.calorias=calorias;
        this.Categoria=Categoria;

    }

    public static void main(String[] args) {

        Edible_ingredients[] arr1= new Edible_ingredients[1];
        Edible_ingredients[] arr2= new Edible_ingredients[1];

        arr1[0]= new Edible_ingredients("1234", "pan", 10, Categorias.carbohidratos);
        arr2[0]= new Edible_ingredients("1234", "pan", 10, Categorias.carbohidratos);
        boolean answer2=Arrays.equals(arr1, arr2);
        System.out.println("arr1 y arr2: "+answer2);

     }
}

respuesta: arr1 y arr2: false
y debería de ser true ya que puse exactamente los mismos valores de cada variable...

Y tampoco sé si así se debe de llenar un array o no?

A:

¿Cómo uso el Arrays.equals?

Déjame decirte que el código está correctamente bien. Lo único que le faltó fue sobrescribir el método equals.
Como la clase Edible_ingredients en ningún momento sobrescribe el método equals, usa el equals que heredó de la clase Object (cualquier clase creada en Java es una subclase de Object). El problema es que el método equals de la clase Object es implementado de esta forma:
public boolean equals(Object obj) {
        return (this == obj);
}

Así que el resultado en este caso será false porque estarías comparando las referencias de dos objetos y por ende, dará false. Ya que una referencia no es más que el identificador del objeto y su característica es que debe ser único.
Solución: Simplemente sobrescribe el método equals en la clase Edible_ingredients:
@Override
public boolean equals(Object o)
{
    Edible_ingredients ei = (Edible_ingredients)o;
    return ei.cod.equals(cod) && ei.nombre.equals(nombre) && ei.calorias == calorias && ei.Categoria == Categoria;
}

De este modo, el método equals de la clase Arrays no invocará el equals de la clase Object, sino, el que hayas sobrescrito.

¿Cómo lleno un array de objetos?

Déjame decirte que ya has llenado el array de objetos.

A: Puedes usar este template en el objeto para implementar equals() a partir de los atributos del objeto:
public class Edible_ingredients {
    private String cod;
    private String nombre;
    private int calorias;
    private Categorias Categoria;

    @Override
    public boolean equals(Object o) {
        // self check
        if (this == o)
            return true;
        // null check
        if (o == null)
            return false;
        // type check and cast
        if (getClass() != o.getClass())
            return false;
        Edible_ingredients item = (Edible_ingredients) o;
        // atributos
        return Objects.equals(cod, item.cod)
                && Objects.equals(nombre, item.nombre)
                && calorias=item.calorias
                && Objects.equals(Categoria, item.Categoria);
    }
}

La implementación predeterminada del método equals se define en la clase Java.lang.Object que simplemente verifica si dos referencias de Objeto (digamos x e y) se refieren al mismo Objeto. es decir, comprueba si x == y (por ello te da false ya que son dos objetos creados aparte).
Para este caso, deberias implementar esto mismo en la clase Categoria.
Cabe destacar que equals() debe implementar las reglas indicadas en la documentacion: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-


text:
Q: How to get the difference between previous and current node inner text value Would you please help me on this.  I would like to insert a node to every node. This node is contain the difference between "OriIndex" of this node and the "OriIndex" of previous node (just one before this).  I have a compile error when writing my XSLT.
My Input is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>1</TestFlow>
    <TestParameter>1</TestParameter>
    <OriIndex>0</OriIndex>
  </Test>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>1</TestFlow>
    <TestParameter>2</TestParameter>
    <OriIndex>1</OriIndex>
  </Test>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>3</TestFlow>
    <TestParameter>1</TestParameter>
    <OriIndex>2</OriIndex>
  </Test>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>2</TestFlow>
    <TestParameter>2</TestParameter>
    <OriIndex>3</OriIndex>
  </Test>

My XML output is (This one is wrong because the Diff of second item should be 1 = Current OriIndex (1) - previous OriIndex (0).  Actually I have no idea how to do this) :
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>1</TestFlow>
    <TestParameter>1</TestParameter>
    <OriIndex>0</OriIndex>
    <SortedIndex>0</SortedIndex>
    <Diff>1</Diff>
  </Test>
  <Test>
    <TestPhase>1</TestPhase>
    <TestFlow>1</TestFlow>
    <TestParameter>2</TestParameter>
    <OriIndex>1</OriIndex>
    <SortedIndex>1</SortedIndex>
    <Diff>0</Diff>
  </Test>
.
.
.
.

My XSLT is :
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" encoding = "UTF-8" indent="yes" omit-xml-declaration="no" standalone="yes" />

  <xsl:template match="Root">
   <xsl:copy>
    <xsl:apply-templates select="Test">
      <xsl:sort select="TestPhase" data-type="number" order="ascending"/>
      <xsl:sort select="TestFlow" data-type="number" order="ascending"/>
      <xsl:sort select="TestParameter" data-type="number" order="ascending"/>
    </xsl:apply-templates>
   </xsl:copy>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

   <xsl:template match="Test">
     <xsl:copy>
       <xsl:apply-templates select="@* | *"/>
       <SortedIndex><xsl:value-of select="position() - 1"/></SortedIndex>
       <Diff><xsl:value-of select="OriIndex - OriIndex[position() - 1]" /></Diff>
     </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

Please help.
Thank you very much.  Your effort is very much appreciated.
Cheers !

A:
This node [should] contain the difference between "OriIndex" of this node and the "OriIndex" of previous node (just one before this).

An XPath expression for the <OriIndex> child of the preceding sibling of the context node (equivalent to the preceding sibling element, because only elements and the document root can have element children) would be
preceding-sibling::*[1]/OriIndex

For your particular data and context, you might write instead this more explicit expression:
preceding-sibling::Test[1]/OriIndex

Overall, then, you might put that together into this template:
    <xsl:template match="Test">
      <xsl:copy>
        <xsl:apply-templates select="@* | *"/>
        <SortedIndex><xsl:value-of select="position() - 1"/></SortedIndex>
        <Diff><xsl:value-of
            select="OriIndex - preceding-sibling::Test[1]/OriIndex" /></Diff>
      </xsl:copy>
    </xsl:template>


text:
Q: Zoho Creator -- Get calendar date from calendar report and paste into another form I have a calendar report. when i click on a date, i want a different form to open, not the form that the calendar report is based on. Then i want the date value from the first form to be passed to the second form. So far, I have this code, on load of the Calendar Form:
MyDate = input.Departure_Date_Time;
//return same window to calendar report
openUrl("https://app.zohocreator.com/ccimailzoho/interhof-travel-
calendar#Calendar","same window");
//open trip form in popup
openurl("#Form:Trip_Form","popup window");
//Trip_Form.Departure_Date_Time = MyDate;

But it doesn't work; MyDate variable does not hold the value between the two forms. Any ideas?

A: For future viewers, if you want to set a value of a form on open from a different form, you can set the value directly in the openurl statement:openurl("#Form:Trip_Form?Departure_Date_Time=" + input.Departure_Time + "&Arrival_Date_Time=" + input.Departure_Time,"same window");


text:
Q: very weird behavior on mysql query I have two queries.
The first one is..
INSERT INTO balik
    ( balik_date,
      balik_time,
      balik_cardID,
      balik_status,
      balik_type )
   select
         current_date(),
         '00:00:00',
         L_CardID,
         'BELUM BALIK',
         L_Type
      FROM
         logdetail t1
            LEFT JOIN balik t2
               ON t1.L_CardID = t2.balik_cardID
      WHERE
             t1.L_Type = 'IN'
         and t1.L_Date = current_date()
         AND t2.balik_cardID IS NULL"

and another one is..
UPDATE balik blk
   INNER JOIN logdetail ld
      ON blk.balik_cardID = ld.L_CardID
     and blk.balik_date = current_date()
   SET
      blk.balik_status = 'SUDAH BALIK',
      blk.balik_type = 'OUT',
      blk.balik_time = ld.L_Time
   WHERE
          ld.L_Type = 'OUT'
      and ld.L_Date = current_date()

My problem is that when I execute the first and second query nothing happens unless I delete all records in my table beforehand. In that case both queries are executed and work like a charm.
Why is this happening?

A: From what I remember, you can't do an insert into a table that is a result of a query that may be an impact of what you are inserting...  So, it MIGHT help if the select was "wrapped" inside another layer so the inner query is completely processed FIRST and thus not impacted by the inserts.
INSERT INTO balik
    ( balik_date,
      balik_time,
      balik_cardID,
      balik_status,
      balik_type )
   select
         PreQuery.newDate,
         PreQuery.newTime,
         PreQuery.newCardID,
         PreQuery.newStatus,
         PreQuery.newType
      from
         ( select
                 current_date() newDate,
                 '00:00:00'     newTime,
                 L_CardID       newCardID,
                 'BELUM BALIK'  newStatus,
                 L_Type         newType
              FROM
                 logdetail t1
                    LEFT JOIN balik t2
                       ON t1.L_CardID = t2.balik_cardID
              WHERE
                     t1.L_Type = 'IN'
                 and t1.L_Date = current_date()
                 AND t2.balik_cardID IS NULL" ) PreQuery

I would alter the syntax on the update to more closely match that of the SQL Syntax per documentation... list the tables comma separated, then apply join conditions in the WHERE clause
UPDATE balik blk, logdetail ld
   SET
      blk.balik_status = 'SUDAH BALIK',
      blk.balik_type = 'OUT',
      blk.balik_time = ld.L_Time
   WHERE
         blk.balik_cardID = ld.L_CardID
     and blk.balik_date = current_date()
     and ld.L_Type = 'OUT'
     and ld.L_Date = current_date()

Yeah, essentially the same thing, but might be interpretation issues.


text:
Q: Eagle Schematic and Board layout design for simple opamp module questions Hopefully I'm not doing anything illegal, I posted a very similar question a few days ago, but this one is different.
Here is what I've been working on the past couple days, trying out different software finally settling on Eagle. Its a simple mic+opamp module that I want to get printed.
Schematic:

Board:

I'm not looking to do SMD, just want to create a board where I can solder on DIP/through-hole components. (I have done copper pour ground on both layers BTW)
So the questions I have are:
1.Should I be using curved traces?
2.Are the green rings the copper rings where I can solder?
3.Is there anything missing from the board layout? (I'm sure there is...)
4.This is where I'm concerned: are the part sizes going to be OK? Are the distances the between the holes for parts standardized or do they differ?
5.Have I chosen the right part for the interface pins? I just want 3 holes that I solder wires to.
Thank you!
EDIT (7/28):

@Steven, I re-did the PCB design on one layer upon your recommendation. It turned out to not be all that hard, and it was good practice. What do you think?
Although I think I did something awkward here: I put two resistors underneath the opamp IC, beause I figured I could use SIP sockets to elevate the IC and fit the resistors under it. Is this OK?

A: *

*You're using a strange mix of curved, straight and 45° traces. The point is purely aesthetic for a design like this, but I would try to stick to 45° traces.

*Yes, they're the solder pads.

*Not if your PCB netlist matches the schematic's.

*You'll have to choose actual parts first and check the drawings in the datasheet, or, if you have parts already, measure them. This goes especially for the capacitors, resistors are more forgiving about this (though you'll want to use as much as possible the same pitch for them).

*If you don't want to place a header or connector there I would place them a bit more apart. You can use a 1-pin header as component.

Also try to be consistent with the symbols in your schematic. You mix American resistor symbols with a European potmeter symbol. (Personally, I don't like the American symbol at all; a schematic with lots of resistors IMO looks messy and frenetic, while the same with European symbols radiates rest & relaxation :-)).
edit
A comment on the double-sided board. This is a design that easily can be done on a single layer. It's worth practicing the layout part of your design. You'll learn how just swapping two components may simplify your routing significantly. For instance the red trace from R6 to the IC can be swapped to the other side by simply placing R6 between R4 and C4. Things like that. It will help you later on when you have more complex designs with hundreds of nets. And it can be fun, too. I like this kind of puzzles a lot. It's like playing planarity.
The problem with this double-sided design is that there are pads which are not accessible for soldering, because they're under a component on the component side, like with C3 or M1. If you don't have plated-through holes you can't be sure the wire is properly soldered to the pad. Worse, if the component's package sits on the pad you can almost be certain that there won't be a solder connection between pin and pad.

A: I see Steven has already answered the questions you asked, so I'm going to answer the ones you didn't ask.
This looks familiar.  Didn't I give you a circuit for this before, but now you've changed a bunch of parts around without understanding why they were the way they were?  I'm pretty sure I specified a true rail-rail opamp, which is why biasing it at 1/2 the supply made sense.  The LM358 needs something like 1.5V headroom on the high side, so is only usable from 0 to 3.5V with a 5V supply.  That means it should be biased at 1.75 volts, not 2.5V.  You can fix that by changing R5 and R6.  Better yet though would be to use the right opamp.
The parallel combination of R5 and R6 are going to load the output of C5 a significant amount, especially if R7 is set to its maximum setting of 10 kΩ.  There is no need for such a low impedance.  You can easily make R5 and R6 100 kΩ each, for a total of 50 kΩ load on the microphone output.  If you insist on sticking with the LM358, then make R5 180 kΩ and R6 100 kΩ.
You are asking for a gain of 100 from the first stage and 11 from the second.  You want to keep the maximum gain per stage down.  If you really want the gain of 1100 as you have now, give each stage close to the square root of that.  R3 of 330 kΩ will give the first stage a gain of 34.  That should be enough if the second stage has a gain of 34 too.
For no apparent reason, you decided to reduce the feedback impedances around the second amp by a factor of 10, but didn't adjust the capacitor accordingly.  R4 and C2 form a high pass filter with a rolloff of 16 Hz.  That's reasonable.  However, R1 and C1 will now roll off at 160 Hz, which is well into the audible range.  There is no reason the two stages can't be the same.  Make R1 10 kΩ and R2 330 kΩ, just like in the first stage.

A:
I re-did the PCB design on one layer upon your recommendation. It turned out to not be all that hard, and it was good practice. What do you think?

You removed the silkscreen! Labels are great.  See this article from Sparkfun about PCB design for manufacturability for a more thorough description.  Simply put, more silk is better.

Although I think I did something awkward here: I put two resistors underneath the opamp IC, beause I figured I could use SIP sockets to elevate the IC and fit the resistors under it. Is this OK?

Um, perhaps?  Planning to mount a high-speed opamp in a SIP socket may or may not be good depending on your application, but I'd be hesitant to do this from a mechanical standpoint unless you really need the space, which you don't.  Use up that blank space at the top right of the board, and just run the traces outside of the space.
If you were doing double-sided design, then you might consider putting SMD parts on the backside, but I understand that PTH and single-sided design is comfortable and cheap for many people.


text:
Q: Select data from table throws an error in SQL Server I've get an error when executing a simple query in SQL Server 2012:
SELECT *
FROM Table

Error:

An error occurred while executing batch. Error message is: Unable to find an entry point named 'SetClrFeatureSwitchMap' in DLL 'SqlServerSpatial110.dll'.

It happens with the only table in database which contains coordinates in DbGeography format. I can operate with this table via my local SQL Server 2014, but this database is on a remote server, and application does not work.
I have the same version of the database on another server, and there it works.
Everything I found was about Entity Framework, but this error appears inside SQL Server 2012. Also I tried to connect to database with Entity Framework by applying this option: Entity Framework cannot update database, but it didn't help.
Is there any way to solve the problem?
This is not a duplicate question because this error does not appear by using EntityFramework. And also I've tried every answer from the related question.


text:
Q: Add a top bar to a three-column flexbox layout (Implementing the Flex-wrap) I have to build a 3-column Flex Layout here on the codepen

But I need to add a black color top bar like this:

I have added a code, which is commented in the codepen.
I have to write a CSS for this so that the black color top bar appears. Don't know how to do this. May be some wrap property will be used or some reverse property. Please guide me.

body {
  margin: 0;
}

header,
footer,
.content {
  display: flex;
}

.content {
  justify-content: space-between;
  height: 75vh;
  max-width: 1500px;
  margin: auto;
}

.main {
  display: flex;
  justify-content: space-between;
  width: 70.5%;
}

.primary {
  width: 27%;
  background-color: yellow;
}

.article {
  background-color: blue;
  width: 71%;
  order: 2;
}

.secondary {
  background-color: pink;
  width: 25%;
  order: 1;
}

.footer {
  display: flex;
}

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>The Fundamental Layout</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="style.css">

This is a Header Location

        The secondary Sidebar

      The Primary Sidebar

    The Footer Area

A: revised codepen

body {
  margin: 0;
}

header,
footer,
.content {
  display: flex;
}

.content {
  justify-content: space-between;
  height: 75vh;
  max-width: 1500px;
  margin: auto;
}

.main {
  flex: 0 0 70.5%;
  display: flex;
  flex-wrap: wrap;
}

.top {
  flex: 0 0 100%;
  background-color: black;
  color: white;
}

.secondary {
  background-color: pink;
  flex: 0 0 25%;
  order: 1;
}

.article {
  background-color: blue;
  flex: 1;
  order: 2;
}

.primary {
  flex: 0 0 27%;
  background-color: yellow;
}

This is a Header Location

The Top area

    The secondary Sidebar

  The Primary Sidebar

The Footer Area

Here's how the top bar is positioned:

*

*.top is made 100% wide inside its container, .main, which is 70.5% wide in a larger container.

*Because .main has flex-wrap: wrap, that forces the other two flex items, .secondary and .article to the next row.

*The siblings are then sized to fit together on the second row.


text:
Q: Ui-Router $stateParams with nested routes I'm trying to route to a url with the selected object's id value within a nested state but it's not working.
ROUTER:
 .state('sessions.editor', {
    url: '/editor/:id',
    templateUrl: 'views/editor.html',
    controller: 'EditorCtrl'
  })

CONTROLLER (EditorCtrl):
  $scope.theSession.$id = $stateParams.id;
  //$scope.session object is successfully returned with the $id property.

PREVIOUS CONTROLLER:

//when button is clicked
$state.go('sessions.editor');

However, when I try to set it to $stateParams, the id property becomes undefined. I tested this with another property on $scope.session and that property becomes undefined also when I try to set it $stateParams.
I'm thinking the trouble has something to do with the state being nested. Is this correct?

A: I believe you need to add the params key to the state for UI-Router, example:
    .state('sessions.editor', {
        url: '/editor/:id',
        controller: 'EditorCtrl',
        templateUrl: 'views/editor.html',
        params: {
            id: {
                value : '',//Default
                squash: false
            }
        }
    })

Then use your existing implementation in the EditorCtrl for $stateParams.


text:
Q: How Can I retrieve my Image From MySQL in visual C++/CLI I want to retrieve my image from MySQL database the type of it LONG BLOB using visual C++ I try this in my key event
String^ con = L"datasource=localhost;port=3306;username=root;password=root";
    MySqlConnection^ conn = gcnew MySqlConnection(con);
    MySqlCommand^ cmd = gcnew MySqlCommand("select * from test.testphoto where test.testphoto.name=@name",conn);
    MySqlDataReader^ re;
    try {
        conn->Open();
        cmd->Parameters->AddWithValue("@name", "shakira");
        re = cmd->ExecuteReader();
        while (re->Read()) {
            BinaryFormatter^ bf = gcnew BinaryFormatter(); // to convert object to byte array
            MemoryStream^ ms = gcnew MemoryStream();
            bf->Serialize(ms, re->GetValue(1));
            pictureBox1->Image = gcnew Bitmap(ms);
            MessageBox::Show("Excute");
        }
    }
    catch (Exception ^e) {
        MessageBox::Show(e->Message, "Error");
    }
    conn->Close();

The problem here that I get error

parameter is not valid

  Update
  i try this now and same Error parameter is not valid please any help

String^ con = L"datasource=localhost;port=3306;username=root;password=kapookingkong";
    MySqlConnection^ conn = gcnew MySqlConnection(con);
    MySqlCommand^ cmd = gcnew MySqlCommand("select * from test.testphoto where test.testphoto.name='shakira'",conn);
    MySqlDataReader^ re;
    try {
        conn->Open();
        re = cmd->ExecuteReader();
        re->Read();
        BinaryFormatter^ fe = gcnew BinaryFormatter();
        MemoryStream^ ms = gcnew MemoryStream();
        fe->Serialize(ms, re["photo"]);
        array<Byte>^ arr = ms->ToArray();
        MemoryStream^ ms2 = gcnew MemoryStream(arr);
        pictureBox1->Image = Image::FromStream(ms2);
    }
    catch (Exception ^e) {
        MessageBox::Show(e->Message, "Error");
    }
    conn->Close();

third try this time index outside bounds of the array Any Help please
this solved I choose the wrong column
String^ con = L"datasource=localhost;port=3306;username=root;password=root";
    MySqlConnection^ conn = gcnew MySqlConnection(con);
    MySqlCommand^ cmd = gcnew MySqlCommand("select photo from test.testphoto where test.testphoto.name='amr'",conn);
    MySqlDataReader^ re;
    try {
        conn->Open();
        re = cmd->ExecuteReader();
        array<Byte>^ arr;
        while (re->Read())
        {
            long long l = re->GetBytes(1, 0, nullptr, 0, 0);
            arr = gcnew array<Byte>(l);
            re->GetBytes(1, 0, arr, 0, l);
        }
        pictureBox1->Image = Image::FromStream(gcnew MemoryStream(arr));
        pictureBox1->Refresh();
    }
    catch (Exception ^e) {
        MessageBox::Show(e->Message, "Error");
    }
    conn->Close();

I get this code from C# code, I try to modify it so I can use it in C++ I didn't find any answer to retrieve image from MySQL in visual C++
Note: I'm using visual C++ 2015

A: BinaryFormatter^ bf = gcnew BinaryFormatter(); // to convert object to byte array
The object contains a byte array. Converting an object containing a byte array to a byte array results in something other than the original byte array. You can verify that yourself by making a simple example of creating a byte array, serializing it, and then inspecting the contents of the memorystream (which will now be larger)
I think you need to use GetBytes() on the reader. You can read more at https://msdn.microsoft.com/en-us/library/87z0hy49%28v=vs.110%29.aspx and MySqlDataReader GetBytes buffer issue...

A: To fix the issue you need to add the following line at the top of your file:
using namespace System::IO;


text:
Q: USB Ejects itself when attempting to format or write to it Similar to this question when I attempt to copy files to or format a USB stick it removes itself from my desktop. When I attempt to do this on my laptop, the issue does not occur. I can read from it fine.
I have tried running diskpart and got attributes but it shows all options as No, including read-only. I tried uninstalling my AV.

A: I would recommend using "DISKPART" to clean and format the USB while it is connected to the laptop.
1.DISKPART > list disk
2.DISKPART > select (enter required usb disk number)
3.DISKPART > clean
4.DISKPART > create partition primary
5.DISKPART > active
6.DISKPART > select partition 1
7.DISKPART > format fs=fat32


text:
Q: Android ListPreference with add-button Is there an example or maybe an already implemented ListPreference for Android, which has a TextView and a Button to add a new value to the list?
Something like this:
|------------------------| |Add|

*

*item

*item

*item

A: This is quite simple to do.

*

*Create a subclass of a ListPreference

*Override the onPrepareDialogBuilder(Builder builder);
2.1 Create a new adapter in which you use your custom layout (standard adapter)
2.2 call builder.setAdapter()

*Done!
see http://blog.isys-labs.com/creating-a-custom-listpreference/


text:
Q: using variable in regex with mysql.connector i need to search a specific word in database, my query is like this:
mysql> SELECT * FROM test1 WHERE question REGEXP '\\bis\\b';

it works good...
but in my python script i use this and nothing happens!
import mysql.connector
cnx = mysql.connector.connect(user='root',
                            password='----',
                            host='127.0.0.1',
                            database='test',
                            auth_plugin='mysql_native_password')

cursor = cnx.cursor(buffered=True)

t = input()

query = "SELECT * FROM test1 WHERE question REGEXP '\\b%s\\b';" % t

cursor.execute(query)
cnx.commit()

for q,one,two,three,four in cursor:
    print(q+'\n',one+'\n',two+'\n',three+'\n',four)

cnx.close()

how can i use a variable in this case!?
Thanks

A: This is because in Python, a doube-quoted string literal uses the backslash also as escape character, just like MySQL.
Either escape both backslashes in each pair:
c.execute("SELECT * FROM test WHERE question REGEXP '\\\\b%s\\\\b';", (t,))

...or use the r prefix to have a raw string where backslashes are not interpreted as escape characters (for Python):
c.execute(r"SELECT * FROM test WHERE question REGEXP '\\b%s\\b';", (t,))

A: You should be using REGEXP in your query instead of LIKE (the way you used in the console). You can try something like this:
c=conn.cursor()
c.execute("SELECT * FROM test WHERE question REGEXP '\\b%s\\b';", (t,))

Assuming t is your input


text:
Q: How to programmatically remove app from Default Apps List for android?
I have made a app for viewing pdf documents in android.When I try to
  open any pdf from outside my app my app is displayed as an option to
  view that pdf inside Complet action using Dialog. I am using the mupdf
  library as a module in my app.  How can I solve this problem?

This is what my AndroidManifest.xml file looks like:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inevitable.org.shatayushi">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:name=".GlobalClass"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ShatayushiActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PayUActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

        <activity
            android:name="com.artifex.mupdfdemo.MuPDFActivity"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="application/vnd.ms-xpsdocument"/>
                <data android:mimeType="application/xps"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="application/pdf"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="application/x-cbz"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="application/epub+zip"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="file"/>
                <data android:mimeType="*/*"/>
                <data android:pathPattern=".*\\.xps"/>
                <data android:host="*"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="file"/>
                <data android:mimeType="*/*"/>
                <data android:pathPattern=".*\\.pdf"/>
                <data android:host="*"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="file"/>
                <data android:mimeType="*/*"/>
                <data android:pathPattern=".*\\.cbz"/>
                <data android:host="*"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="file"/>
                <data android:mimeType="*/*"/>
                <data android:pathPattern=".*\\.epub"/>
                <data android:host="*"/>
            </intent-filter>
        </activity>
        <activity android:name="com.artifex.mupdfdemo.OutlineActivity"
            android:theme="@android:style/Theme.Holo.Light.DarkActionBar"
            android:label="@string/outline_title"
            >
        </activity>
        <activity
            android:name="com.artifex.mupdfdemo.PrintDialogActivity"
            android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"
            android:label="@string/print">
        </activity>
    </application>

</manifest>

Any help or suggestion is appreciated.Thank you.

A: That's means that there is an Intent Filter to get the action.
See here https://developer.android.com/guide/components/intents-filters.html#Receiving
I don't know mupdf library but I guess there is in the manifest something like the following code (just an example):
<activity android:name="ShareActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

A: As I could not see the code snippet of the intent filter, my suggestion would be to refer
 How can I have my app appear in the intent chooser only for certain urls?
This link might also be helpful in your case I don't want my app to appear on the chooser dialog when opening URL's
Hope this helps.


text:
Q: Where is the Write Protect Screw on Notebook? NL61
Pictured is a CTL brand NL61 Chromebook. I'm trying to enable developer mode but it's locked.
How can I fix it?

A: Contact CTL Support at https://support.ctl.net/hc/en-us as the user manual does not explain where it is, and their web site does not show how.


text:
Q: Batch-compressing/archiving files within subcategories (files have to be in the root) I've been searching for a while now to archive a LOT of photographs in different directories into seperate zip-archives. With no luck so far. How come? I have some specific requests;
The directory-structure:
YEAR => Category (12 directories, the same for each year) => Each Category has it's own events => Each event has it's own pictures. For example:
2013\
--------Category1\
--------Category2\
--------Category3\
-----------------------Subcategory1\
--------Category4\
--------Category5\
--------Category6\
-----------------------Subcategory1\
-----------------------Subcategory2\
------------------------------------------Photograph1.jpg
------------------------------------------Photograph2.jpg
--------Category7\
and so on...
Year: 7 directories
Subcategories in each year-folder: 12
Sub-subcategory in each Subcategory folder: 100-200
Photographs inside all folders: 70GB, not sure how many files exactly.
My question
I would like to create individual zip-archives for each subcategory. Here's the catch:
The zip archives must fulfil to 2 requests:
1) The photographs have to be placed in the root of the zip-archive. When you open up a zip-archive, the first thing you have to see are photographs. No (sub)directories.
2) If possible, the zip-archives have to be limited to a filesize of 150mb each. So even if a subcategory contains 200mb of photographs, the script/parameters have to set limits to the filesize. Not just 'splitting up' a 200mb zip-archive, but really make 2 seperate zip-archives. One being 150mb in size, the other 50mb.
Would this be possible to do? There are a lot of ways to archive files by scripts and I did try a few, but none of them seem to work the way I want it to work ;-)
So... the zip-archives have to be put in the same sub-category besides the photographs, can't be any bigger then 150mb each and have to understand what files have to be zipped (the content of sub-categories within a sub-category within the year-category).
Thanks! :)

A: Here you go.  Save this with a .vbs extension.  I haven't tested it thoroughly, but I think it should work.  For each directory that contains files, it will zip those files to an archive within the same containing directory.
Oh, and welcome to SO!  Since you are new, you might want to check this link.
' archive_limit.vbs
' usage: cscript archive_limit.vbs (directory, optional)
' If directory is not supplied, traverse subdirectories of current

on error resume next
if WSH.arguments.count = 0 then
    dir = left(WSH.ScriptFullName,(Len(WSH.ScriptFullName))-(len(WSH.ScriptName)))
else
    dir = WSH.arguments(0)
    if not Right(dir, 1) = "\" then
        dir = dir & "\"
    end if
end if

set fso = createobject("scripting.filesystemobject")
set shl = createobject("shell.application")

EnumFolders(fso.GetFolder(dir))

WSH.Quit 0

Sub EnumFolders(fFolder)
    Set objFolder = fso.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    zipnum = 1
    For Each objFile in colFiles
        zipfile = fFolder.Path & "\archive" & zipnum & ".zip"

        If fso.FileExists(zipfile) Then
            projected = fso.GetFile(zipfile).Size + objFile.Size
            if projected >= 157286400 Then
                zipnum = zipnum + 1
                zipfile = fFolder.Path & "\archive" & zipnum & ".zip"
            End If
        End If

        if not fso.FileExists(zipfile) Then
            set zip = fso.createtextfile(zipfile)
            zip.write "PK" & chr(5) & chr(6) & string(18, chr(0))
            zip.close
        End If

        If Not LCase(fso.GetExtensionName(objFile.name)) = "zip" Then
            ' uncomment the following line to log progress to the console
            ' WSH.Echo "Zipping " & fFolder.Path & "\" & objFile.name & " to " & zipfile
            zipitems = shl.namespace(zipfile).items.count
            shl.namespace(zipfile).copyhere(fFolder.Path & "\" & objFile.name)
            do until shl.namespace(zipfile).items.count > zipitems
                WSH.Sleep 100
            loop
        End If

    Next

    For Each Subfolder in fFolder.SubFolders
        EnumFolders(Subfolder)
    Next
End Sub


text:
Q: R: Visualizing the "path" taken by an optimization algorithm I am using R and trying to recreate the visualizations from this stackoveflow post, where the "path" taken by an optimization algorithm for some function is visualized:
visualizing the optimization path till convergence in R
I created some fake data:
#load libraries
library(dplyr)

# create some data for this example
a1 = rnorm(1000,100,10)
b1 = rnorm(1000,100,5)
c1 = sample.int(1000, 1000, replace = TRUE)
train_data = data.frame(a1,b1,c1)

Then, I defined the function:
  fitness <- function(x) {
    #bin data according to random criteria
    train_data <- train_data %>%
        mutate(cat = ifelse(a1 <= x[1] & b1 <= x[3], "a",
                            ifelse(a1 <= x[2] & b1 <= x[4], "b", "c")))

    train_data$cat = as.factor(train_data$cat)

    #new splits
    a_table = train_data %>%
        filter(cat == "a") %>%
        select(a1, b1, c1, cat)

    b_table = train_data %>%
        filter(cat == "b") %>%
        select(a1, b1, c1, cat)

    c_table = train_data %>%
        filter(cat == "c") %>%
        select(a1, b1, c1, cat)

    #calculate  quantile ("quant") for each bin

    table_a = data.frame(a_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[5],1,0 )))

                         table_b = data.frame(b_table%>% group_by(cat) %>%
                                                  mutate(quant = ifelse(c1 > x[6],1,0 )))

                                              table_c = data.frame(c_table%>% group_by(cat) %>%
                                                                       mutate(quant = ifelse(c1 > x[7],1,0 )))

                            }

                                                                   #group all tables

                                                                   final_table = rbind(table_a, table_b, table_c)
                                                                   # calculate the total mean : this is what needs to be optimized
                                                                   mean = mean(final_table$quant)
}

I then used an optimization algorithm on this function:
library(optimization)
Output <- optim_nm(fitness, k = 7, trace = TRUE)

Problem : Now, I am trying to follow the instructions from the previous stackoverflow post (visualizing the optimization path till convergence in R) to visualize the results of this algorithm:
First, define the grid:
library(gganimate)

#define grid

 l.grid <- 200
  grid.b <- as.matrix(expand.grid(b0=seq(-3,0.5,length.out=l.grid), b1=seq(-6,6,length.out=l.grid)))
  grid.f <-apply(grid.b,1,logll)
  grid.b <- as.data.frame(grid.b)

Next, visualize the results (e.g. between any 2 variables) - But I am not sure how to adapt the code from the previous stackoverflow post to my example:
#animate/visualize - not working

op <- sapply(
  seq_len( optim_nm(fitness, k = 7, trace = TRUE)$counts['function']),
  function(i) {
    set.seed(1234)
    optim([1], [2] , control = list(maxit = i))$par
  }
)
op_df <- data.frame(b0 = op[1,], b1 = op[2,])
op_df$step <- 1:nrow(op_df)

p <- ggplot(grid.b, aes(b0, b1)) +
  geom_raster(aes(fill = f)) +
  geom_contour(aes(z = f), col = 'grey40') +
  geom_path(data = op_df, col = 'white') +
  geom_point(data = op_df, col = 'white') +
  scale_fill_viridis_c() +
  coord_cartesian(expand = FALSE)

library(gganimate)
a <- p + transition_reveal(step)

Can someone please show me how to do this?
Thanks


text:
Q: Como abrir um navegador com Python, Selenium e o geckodriver? Eu escrevi uma automatização para seguir pessoas no instagram, porém, quando coloco Run no código, ele me retorna no log com nenhum erro, e mesmo assim não abre o navegador para que eu teste o código. Acho que tem algo errado no inicio do meu código que não está permitindo abrir o navegador mas não sei o que pode ser. Esse é o código que estou utilizando para abrir o Firefox:
from selenium.webdriver.common.keys import Keys
import time

class InstagramBot:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Firefox(executable_path=r'C:\geckodriver\geckodriver.exe')```

A: Provavelmente o que esta faltando e inserir no código a url do site.
E logo após iserir a opção ex.: web.get(url)
segue um exemplo de código:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located

with webdriver.Firefox() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get("https://google.com/ncr")
    driver.find_element(By.NAME, "q").send_keys("cheese" + Keys.RETURN)
    first_result = wait.until(presence_of_element_located((By.CSS_SELECTOR, "h3>div")))
    print(first_result.get_attribute("textContent"))

fonte: https://www.selenium.dev/documentation/en/
Espero ter ajudado.


text:
Q: Range of values of 'a' so that the function has local maxima/minima at given values of x Find the set of all the possible values of $a$ for which the function:
$$f(x)=5+(a-2)x+(a-1)x^2-x^3$$
Has a local minimum value at some x<1 and local maximum value at some x>1.

I started by taking the derivative first, since the derivative becomes 0 at any local maxima/minima.
$$f'(x)=(a-2)+2(a-1)x-3x^2=0$$
I tried to get the roots using quadratic formula which just gives an expression in $a$ which doesn't seem to conclude at any desired result. Also, I don't understand how I can separately apply this condition for $x>1$ and $x<1$ respectively.
Rolle's Mean Value Theorem also struck me since I could use it to conclude that $f'(x)$ has a root but I would need an interval for that,
to get the condition $f(p)=f(q)$ so that $f'(x)$ has a root between $p$ and $q$. Clearly, $-1$ and $+1$ would be one of these in each case but what about the other end of the interval? I'm not able to find any other x which gives the same value as $f(-1)$ or $f(+1)$
Please help me out with a way to approach this, or if there's any other better way.


text:
Q: Exporting stock chart (ohlc) to Excel by C# code I want to export the stock chart ohlc to Excel
I'm using EPPlus, now I came to know that EPPlus does not support stock charts to draw, hence I'm looking for another third party dll, I've found aspose, but it's paid kind of feature to use.
Can anyone suggest any other for exporting stock chart creating stock chart in Excel by C# code?
Or is it possible to create stock chart ohlc in Excel by C# by EPPlus?
When using the aspose, I need to use it in bw the code, wen I save the aspose workbook, it pops exception that file is being used by another process, is there any way to forcefully close the process accessing it, or making it to be over written by it?
Adding to above, I've got EPPlus and also the aspose at a same tym.

A: Yes, you can create Stock chart using Aspose.Cells. The following stock charts are supported in Aspose.Cells:

*

*High-low-close stock chart

*Open-high-low-close stock chart

*Volume-high-low-close stock chart

*Volume-open-high-low-close stock chart

For your issue regarding the file is being used by another process, such issue occurs, when you for example try to save your workbook as c:\output.xlsx and at the same time, you have opened it in Microsoft Excel.
In this case, Aspose.Cells will not be able to save to c:\output.xlsx because c:\output.xlsx is being used by another process i.e Microsoft Excel. You should first close c:\output.xlsx in Microsoft Excel, then Aspose.Cells will be able to save it to c:\output.xlsx.
Note: I am working as Developer Evangelist at Aspose