text:
Q: ImportError: no module named mako.template This line of code in my foobar.py file:
from mako.template import *

results in an

ImportError: No module named mako.template

How can I fix this? Both help('modules') and repr(mako) in my Python console assures me that the mako module is installed and available.
I'm on a Mac by the way, running Python 2.6 for this particular project.
As requested, this is the output from running pip freeze

*

*Mako==0.8.1

*MarkupSafe==0.18

*PyYAML==3.10

*wsgiref==0.1.2

As requested, this is my sys.path
['', '/Users/username/env/myProject/lib/python26.zip', '/Users/username/env/myProject/lib/python2.6', '/Users/username/env/myProject/lib/python2.6/plat-darwin', '/Users/username/env/myProject/lib/python2.6/plat-mac', '/Users/username/env/myProject/lib/python2.6/plat-mac/lib-scriptpackages', '/Users/username/env/myProject/Extras/lib/python', '/Users/username/env/myProject/lib/python2.6/lib-tk', '/Users/username/env/myProject/lib/python2.6/lib-old', '/Users/username/env/myProject/lib/python2.6/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Users/username/env/myProject/lib/python2.6/site-packages']

A: Do you have template.py inside your .env/lib/python2.6/site-packages/mako directory?
Are you using virtualenv, or have installed mako in /Library/Python/2.6/site-packages?
Please paste an output of pip freeze

Update:
Have you checked if there is no CR/LF or wrong character on this import line?
What is the encoding of your foobar.py file?
file -I foobar.py

it should contain utf-8 or ascii


text:
Q: Virtual domains and subdomains using mod_rewrite I would like to create a service where a user either can get a subdomain or a regular domain on my service.
The idea is that all subdomains except www. should go to /subdomains.php?user=[sub]&url=[requestet url]
And all domains except my own 2 domains should go to /domain.php?url=$1
My 2 domains are:
domain1.com and domain2.se
I've tried the following code:
<IfModule mod_rewrite.c>
Options +FollowSymLinks

RewriteEngine On

# Rewrite sub domains.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^www\.domain1\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain1\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\.domain2\.se$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain2\.se$ [NC]
RewriteRule ^(.*)$ /subdomain.php?user=%2&url=$1 [QSA,L]

#Rewrite
RewriteCond %{HTTP_HOST} !^www\.domain1\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\.domain2\.se$ [NC]
RewriteRule (.*) http://www.domain1.com/domain.php?url=$1 [R=301,L]
</IfModule>

But it does not seen to work.

A: Sub domains: how do you expect an URL to be both a subdomain of domain1.com and domain2.se at the same time?
Try e.g. this simplification:
RewriteCond %{HTTP_HOST} !^www\.(domain1\.com|domain2\.se)$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.(domain1\.com|domain2\.se)$ [NC]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Differences between cin and scanf the input
a, b and c in [−263 ,263 ]
t <= 10
#include <bits/stdc++.h>

using namespace std;

int main()
{
    //freopen("in.txt", "r", stdin);

    int t, tcase = 1;
    //scanf("%d", &t);
    cin >> t;
    while(t--)
    {
        long long a, b, c;
        //scanf("%lld %lld %lld", &a, &b, &c);
        cin >> a >> b >> c;
        long long res = a + b;
        bool flag;
        if(a < 0 && b < 0 && res >= 0)flag = false;
        else if(a > 0 && b > 0 && res < 0)flag = true;
        else if(a + b > c)flag = true;
        else flag = false;

        if(flag == true)
        {
            printf("Case #%d: true\n", tcase++);
        }
        else
        {
            printf("Case #%d: false\n", tcase++);
        }
    }
    return 0;
}

sometimes I use scanf, program runs correctly, but when replacing it with cin, I get wrong answer. Plese tell me what is the problem, thank you very much.

A: The values of a, b and c are uninitialized and therefore indeterminate. The two expressions will have the same value within the single execution of a program:
#include <iostream>

int main()
{
    long long a, b, c;
    long long res = a + b;

    std::cout << (res > c) << '\n';
    std::cout << (a + b > c) << '\n';
}

However, this value may change when executing this program multiple times.
Edit 1
You added a line initializing these variables from stdin, but this happens before the variables are declared. If this code compiles, your variables have been declared previously and are then being shadowed.
Edit 2
The code in the question was edited again. I give up.


text:
Q: How to determine the child of an inheritance in Power Designer I have an entity object in Power Designer and walk through its inheritances but I do not know how to get the child object. Could someone post an example code? It is also important to get the Object ID of the inheritance.
Edit: solution Idea based on pascals examples:
foreach (PdCDM.Inheritance curPDInheritance in curPDEntity.InheritedBy){
  foreach(PdCDM.InheritanceLink curPDInheritanceLink in curPDInheritance.InheritanceLinks){
    Console.WriteLine(curPDEntity.Name + " parent of " + ((PdCDM.Entity)curPDInheritanceLink.ChildEntity).Name+ " through " + curPDInheritance.Name + " (" + curPDInheritance.ObjectID + ")");
  }
}

A: Here are two examples in VBScript. It will give you an idea of the collections you're looking for. The first one directly gives the entities inheriting from the an entity.
option explicit
dim mdl : set mdl = ActiveModel
dim ent,chl
for each ent in mdl.Entities
   for each chl in ent.InheritedByEntities
      output ent.Name + " parent of " + chl.Name
   next
next

The second example enumerates the inheritances, to retrieve their child entities:
option explicit
dim mdl : set mdl = ActiveModel
dim ent,inh,chl
for each ent in mdl.Entities
   for each inh in ent.InheritedBy
      for each chl in inh.ChildEntities
         output ent.Name + " parent of " + chl.Name + " through " + inh.Name + " (" + inh.ObjectID + ")"
      next
   next
next

EDIT: if your version of PowerDesigner does not have .ChildEntities, you can try through the InheritanceLink which links the child entity, with the inheritance:
option explicit
dim mdl : set mdl = ActiveModel
dim ent,inh,ilk
for each ent in mdl.Entities
   for each inh in ent.InheritedBy
      for each ilk in inh.InheritanceLinks
         output ent.Name + " parent of " + ilk.Object2.Name + " through " + inh.Name + " (" + inh.ObjectID + ")"
      next
   next
next


text:
Q: Gurobi in docker container problem generating unique host ID for this machine I am trying to install Gurobi on my docker container, but when I run grbgetkey I get this message.
info  : grbgetkey version 8.1.1, build v8.1.1rc0
error : Problem generating unique host ID for this machine.
I haven't generated a license file yet.

A: It's complicated to license commercial software inside a Docker container, so we created this error intentionally. Please contact Gurobi support directly for license options inside Docker.


text:
Q: Substract two dates delimited by comma in bash I have a CSV file like below
id,name,age,startdate,enddate,parentid,group
1,Anish,30,20200909140254,20200909140320,15,A
2,Ajo,25,20200909074813,20200909074918,25,B
.
.
.

Date is in the format YYYYMMDDHHMMSS. How do I substract field 5 from field 4 and display the output like below using bash (or AWK)?
Ajo,20200909074813,20200909074918,00000000000105
Regards,
Anish

A: Might work something like
awk ' BEGIN {FS = ","}; {print $2 "," $4 "," $5}' FILENAME.csv


text:
Q: Sorting a string without sort()/sorted() functions I need to sort a four-number string into the highest and lowest value numbers that can be made using the digits in string. I cannot use sort() or sorted() functions. It was hinted that I should use the min(), max(), and len() functions. Can anyone help me figure out how to go about sorting the string? My current code is below using the sorted() function.
num = input("Enter a four-digit integer: ")

#setting intial value of iterations
i = 0

#differentiating between initial input value and transformed number
kaprekar = num

#while loop performing kaprekar's method
while (kaprekar != '6174'):
    i +=1
    #add leading zeros
    kaprekar = kaprekar.zfill(4)
    #Sorts to largest and smallest number made from input number
    num1 = ''.join(sorted(kaprekar,reverse=True))
    num2 = ''.join(sorted(kaprekar))
    difference = str(int(num1) - int(num2))
    print(kaprekar, "> ", end='')
    #reassigns number for loop
    kaprekar = difference

print(kaprekar)
print(num, "reaches 6174 via Kaprekar's routine in", i, "iterations")

A: To find minimum/maximum number from the string (without sorted()):
s = "6174"

out = ""
while s:
    out += min(s) # or max() for maximum
    s = s.replace(out[-1], "", 1)

print(out)

Prints:
1467


text:
Q: $this->getProductCollection() returns only 15 items I am using the following code for getting products in the beforeToHtml() function of a block, but when I get the products in the template file using $this->getProductCollection() it returns only 15 items, while running the query in mysql directly returns 120 items.
Query:
SELECT `e`.*, `at_inventory_in_stock`.`is_in_stock` AS `inventory_in_stock`, `cat_index`.`position` AS `cat_index_position`, `price_index`.`price`, `price_index`.`tax_class_id`, `price_index`.`final_price`, IF(price_index.tier_price IS NOT NULL, LEAST(price_index.min_price, price_index.tier_price), price_index.min_price) AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price`, `cat_index1`.`position`, SUM(sfoi.qty_ordered) AS `ordered_qty` FROM `catalog_product_entity` AS `e` INNER JOIN `cataloginventory_stock_item` AS `at_inventory_in_stock` ON (at_inventory_in_stock.`product_id`=e.entity_id) AND ((at_inventory_in_stock.use_config_manage_stock = 0 AND at_inventory_in_stock.manage_stock=1 AND at_inventory_in_stock.is_in_stock=1) OR (at_inventory_in_stock.use_config_manage_stock = 0 AND at_inventory_in_stock.manage_stock=0) OR (at_inventory_in_stock.use_config_manage_stock = 1 AND at_inventory_in_stock.is_in_stock=1)) INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id='1' AND cat_index.visibility IN(2, 4) AND cat_index.category_id='2' INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 INNER JOIN `catalog_category_product_index` AS `cat_index1` ON cat_index1.product_id=e.entity_id AND cat_index1.store_id=1 AND cat_index1.category_id IN (43,42,71,50,44,45,54,46,47,51,48,49,52,55) INNER JOIN `sales_flat_order_item` AS `sfoi` ON e.sku = sfoi.sku GROUP BY `e`.`entity_id` ORDER BY `ordered_qty` DESC

Code:
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'Phones');
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

$collection = $this->_addProductAttributesAndPrices($collection)
    ->addStoreFilter()
    ->setPageSize($this->getProductsCount())
    ->setCurPage($currentPage);

if(!is_numeric($price) && $price != "-1"){
    $price = explode(',', mysql_escape_string($price));
    //Mage::log(print_r($price,true), null, 'phonefinder.log');
    if(count($price) == 2){
        $start = $price[0];
        if($start != 0) {
            //Mage::log("Adding gteq expression for start amount of : " . $start, null, 'phonefinder.log');
            $collection->addAttributeToFilter('price', array('gteq' => $start));
        }
        $end = $price[1];
        if($end != '-1') {
            //Mage::log("Adding lteq expression for end amount of : " . $end, null, 'phonefinder.log');
            $collection->addAttributeToFilter('price', array('lteq' => $end));
        }
    }
}
if($sortBy == 1)
    $collection->addAttributeToSort('price', 'desc');
else if($sortBy == 0)
    $collection->addAttributeToSort('price', 'asc');

if($sortBy == 2){
    $collection->getSelect()
        ->joinLeft('sales_flat_order_item AS sfoi',
        'e.sku = sfoi.sku',
        'SUM(sfoi.qty_ordered) AS ordered_qty')->group('e.entity_id')->order('ordered_qty DESC');

}

$this->setProductCollection($collection);
echo $collection->getSelect();
//exit;
return parent::_beforeToHtml();

A: It's probably due to the $this->getProductsCount() having a value of 15. This causes the query to only return 15 records.
Do a var_dump on this method to see if it is indeed 15.


text:
Q: Can I use R.Net without installing R I am building an application within C# and I want to use some of the R libraries within this application. I am using R.Net to do this.
However, I will deploy this software to users that may not have R downloaded on there computers. Is there any way that I can use the R dll so that the users can run my application without having to install R onto there machines?
Many thanks

A: While this question is rather old, maybe this elaboration on Hackerman's answer will still help someone:
You do not have to have R installed properly on your computer and you also do not have to have any registry entries for R if you want to use R.NET. However, R.NET still needs to access the native DLLs found in ...\R\bin\i386 and the contents of ...\R\library.
Assuming your R files are located at C:\Program Files, setting the paths to ...\R\bin\i386 and ...\R\library works as follows:
REngine.SetEnvironmentVariables(@"C:\Program Files\R\bin\i386", @"C:\Program Files\R");

You can then set up an REngine using:
REngine engine = REngine.GetInstance();

This works using R.NET v1.7 and R v3.4.2 (32bit).


text:
Q: How to do fields names uppercase in JAXB in java object? I am trying to convert a Java Object to XML using JAXB and it works for me, but it converts the name of the class fields with a lowercase letter and I don't know how to change to capital letters.
For example, my class:
@XmlRootElement(name = "StockQuoteRequest")
@Component
public class StockQuoteRequest {

    @XmlElement(name = "Security")
    private Security securities;

// constructor
// getter/setter
// toString
}

Here is the Security class:
@Component
public class Security {

    private String name;
    private String lastName;
    private String address;

    // constructor
    // getter/setter
    // toString
}

For the StockQuoteRequest class, the Security field is capitalized, but for the Security class, its fields (name, lastName, address) are printed with a small one.
I tried to add an annotation in the Security class above each field
@XmlElement(name = "Name")
@XmlElement(name = "LastName")
@XmlElement(name = "Address")

But this does not work at all.
Can anyone tell me how to do this?
Thanks.

A: I get the following exception in Java 8 (jdk1.8.0_181) when trying your code, i.e. when I added standard getter/setter methods:
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "securities"
    this problem is related to the following location:
        at public Security StockQuoteRequest.getSecurities()
        at StockQuoteRequest
    this problem is related to the following location:
        at private Security StockQuoteRequest.securities
        at StockQuoteRequest

To fix, I had to do one of 3 things:

*

*Move the @XmlElement(name = "Security") annotation down to the getSecurities() method

*Add @XmlTransient to the getSecurities() method

*Add @XmlAccessorType(XmlAccessType.NONE) (or FIELD) to the StockQuoteRequest class
When I did any of those, I would get output like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StockQuoteRequest>
    <Security>
        <address>North Pole</address>
        <lastName>Doe</lastName>
        <name>John</name>
    </Security>
</StockQuoteRequest>

Notice how the 3 sub-elements are in the wrong order. To fix, add @XmlType(propOrder = { "name", "lastName", "address" }) to the Security class.
When I then added the 3 @XmlElement annotations, showed in the question, to the Security class, and applied similar fix to prevent exception, I get what I expected:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StockQuoteRequest>
    <Security>
        <Name>John</Name>
        <LastName>Doe</LastName>
        <Address>North Pole</Address>
    </Security>
</StockQuoteRequest>

Full Minimal, Reproducible Example to get the above output:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public class Test {
    public static void main(String[] args) throws Exception {
        StockQuoteRequest request = new StockQuoteRequest(
                new Security("John", "Doe", "North Pole"));

        JAXBContext jaxbContext = JAXBContext.newInstance(StockQuoteRequest.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(request, System.out);
    }
}

@XmlRootElement(name = "StockQuoteRequest")
@XmlAccessorType(XmlAccessType.NONE)
class StockQuoteRequest {

    @XmlElement(name = "Security")
    private Security securities;

    public StockQuoteRequest() {
    }

    public StockQuoteRequest(Security securities) {
        this.securities = securities;
    }

    public Security getSecurities() {
        return this.securities;
    }

    public void setSecurities(Security securities) {
        this.securities = securities;
    }

    @Override
    public String toString() {
        return "StockQuoteRequest" + this.securities;
    }

}

@XmlType(propOrder = { "name", "lastName", "address" })
@XmlAccessorType(XmlAccessType.NONE)
class Security {

    @XmlElement(name = "Name")
    private String name;
    @XmlElement(name = "LastName")
    private String lastName;
    @XmlElement(name = "Address")
    private String address;

    public Security() {
    }

    public Security(String name, String lastName, String address) {
        this.name = name;
        this.lastName = lastName;
        this.address = address;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Security[name=" + this.name + ", lastName=" + this.lastName + ", address=" + this.address + "]";
    }
}


text:
Q: How to remove duplicate rows in shell script? Could you kindly support the below query,
How to do in shell script (.sh) ?
cat inputFile.txt
row1 x_1    8
row2 x_1    8     1
row3 x_2    6
row4 x_2    6     1
row5 x_3    5
row6 x_4    7

Step 1:
We have to remove the below rows from above file
x_1    8
x_2    6

Step 2:
We have to keep the below rows from above file
row2 x_1    8  1
row4 x_2    6  1
row5 x_3    5
row6 x_4    7

Expected output:
cat outputFile.txt
x_1    8     1
x_2    6     1
x_3    5
x_4    7

A: When you say 'rows', this means lines to me, like duplicate lines in a file.  I can't tell if when you posted that those x_1 8 1 x_2.. above were originally one per line.  So let's assume they were.  A neat trick to remove the duplicates is simply:
cat outputFile.txt | sort | uniq

You need to sort the lines first because uniq removes repeated lines which are adjacent.
If you really meant to remove duplicates within a line itself, an easy hack would be to put the words in the line into separate lines using something like xargs -n 1 , then piping that to the sort | uniq, then put everything back on a single line with something like tr '\n' ' ':
cat outputFile.txt | xargs -n 1 | sort | uniq | tr '\n' ' '


text:
Q: Intuition for the derivative of the exponential function 1. THE PROBLEM
Take the definition of the derivative:
$$\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
Using this definition to calculate the derivative of $e^x$ is not the most trivial thing to do, as one ends up with:
$$\frac{d}{dx}e^x=e^x\lim_{h\to 0}\frac{e^h-1}{h}$$
We can finish this off by a change of variables $n=\frac1h$.
$$e^x\lim_{h\to 0}\frac{e^h-1}{h}=e^x\lim_{n\to\infty}n(e^{1/n}-1)=e^x\cdot\ln e=e^x$$
Note: the second to last equality holds because of a limit definition of the natural logarithm: $\ln x=\lim_{n\to\infty}n(x^{1/n}-1)$.
As we see, calculating the derivative of the exponential function is not easy with the usual limit definition of the derivative. It requires calculating a limit that is not obvious without knowing a special limit definition of $\ln x$.
One can wonder then, are there easier ways of proving that $\frac{d}{dx}e^x=e^x$? Indeed, there are easier ways to prove this. But all of the proofs I have ever seen either assume a taylor series or limit definition of the exponential function, or somehow use the derivative of $\ln x$ which itself has similar calculation problems. Finally, the proofs lack deep motivated intuition, and are raw algebraic manipulations for the most part. They prove things well, but they don't explain things well.
Question: is there a way to find the derivative of the exponential function intuitively?

2. POSSIBLE SOLUTIONS
I didn't ask this question without giving it a little thought.
Path A
I figured that one solution to this problem might be by intuituvely explaining how in the world $\ln x$ is equal to $\lim_{n\to\infty}n(x^{1/n}-1)$.
Euler observed, quite unrigorously, that if $\epsilon$ is an arbitrarily small number, then:
$$\ln(1+\epsilon)=\epsilon$$
Similarly, if we let $n$ be an arbitrarily large number, we can observe that:
$$x^{1/n}-1=\epsilon$$
Plugging this observation into the first one, we have:
$$\ln(x^{1/n})=x^{1/n}-1$$
$$\frac1n\ln x=x^{1/n}-1$$
$$\ln x=n(x^{1/n}-1)$$
Thus:
$$\ln x=\lim_{n\to\infty}n(x^{1/n}-1)$$
This would almost work as a solution, except for the fact that here we make observations that work for logarithms of all bases. The observation $\log_b(1+\epsilon)=\epsilon$ is valid for all bases $b$. The second observation we made doesn't even relate specifically to logarithms. Thus, the "intuition" in this case assumes that the limit can be equal to a logarithm of any base. This is obviously false; computations evidently show that this limit holds only for $b=e$. And it is not evident at all why it has to be $e$ and nothing else.
This solution will be complete if it can be shown why base $e$ and none other work.
Path B
Another solution to this problem would be noting that the exponential function grows proportionally to its size. The problem with this intuition is that it is not at all evident why would this function follow such a behavior.
The mystery is, how does one start with simple algebraic properties of exponents, which are trivially defined by multiplication, and arrive the conclusion that this function follows its unique growth behavior. It might help to note that exponentiation turns an arithmetic sequence into a geometric sequence.
Id est, if:
$$\alpha_n=a+\sum^n_1 d$$
$$\gamma_n=b\prod^n_1 r$$
Then:
$$e^{\alpha_n}=e^{a+\sum^n_1 d}=e^a\prod^n_1 e^d=b\prod^n_1 r=\gamma_n$$
If there is a way to start with basic algebraic facts about exponents and end up (intuitively) with the fact that exponential growth is proportional to its size, we could then justify the fact that $e^x$ is the solution of $y'=y$, $y(0)=1$. From there, we could automatically say that the derivative of the natural exponential is itself.
Caveat: While solving this ODE, there is still a problem because we need to compute the integral of $\frac1x$. It turns out that we can intuitively solve this task. We can begin by splitting the area under the curve into n rectangles of equal area $A$, situated between corresponding x coordinates: $\{x_0, x_1, ..., x_n\}$. We will then note that:
$$A=y_0(x_1-x_0)=y_1(x_2-x_1)$$
$$\frac{x_1-x_0}{x_0}=\frac{x_2-x_1}{x_1}$$
$$\frac{x_1}{x_0}-1=\frac{x_2}{x_1}-1$$
$$\frac{x_1}{x_0}=\frac{x_2}{x_1}$$
This will generalize to $\frac{x_n}{x_{n-1}}=\frac{x_{n+1}}{x_n}$. What this means is that, if rectangles are the same area, if we increase the x coordinates geometrically (because the ratio between next and current x coordinate is constant), we increase the area arithmetically. This is precisely what logarithms do, they turn geometric sequences into arithmetic sequences (opposite of the exponentials). Thus, the integral of $\frac1x$ will be some kind of logarithm.
The missing bit here, again, is...why is it base e, and not some another base?
Other paths
Those two paths are most likely not the only approaches.

3. MOTIVATION
At this point, I overstressed the word "intuition", and I just wanted to explain myself. I just really love to explore things that are proven symbolically, in a natural way. I might be considered weird for trying to do that so deeply for such a simple derivative, but oh well.
Thank you in advance for any good insights into this problem.

A: One fairly elementary way to approach this -- elementary enough that it's the way it was approached at the secondary school (= high school) I went to -- is to begin by defining the logarithm rather than the exponential. You say $\log x=\int_1^x1/t\ dt$ from which it immediately follows that the derivative of $\log x$ is $1/x$, you prove that $\log(ab)=\log a+\log b$ by a simple geometrical argument and $\log 1=0$ by inspection, and now you've got a nice log function and know its derivative. Then you define exp to be the inverse of log; you know it behaves like an exponential because you know log behaves like a logarithm; and now the derivative of exp is a trivial calculation using the already-known derivative of log.
(Personally I think I prefer to take YiFan's approach and begin by defining exp in terms of the ODE it satisfies. But the above works pretty well.)

A: If you can accept the derivative of $\ln x$ then this might provide "some" intuition.
$$
y=e^x \Rightarrow \\
\ln y = x \Rightarrow \\
\frac{y '}{y} = 1 \Rightarrow \\
y' = y = e^x
$$

A: This might not exactly be the type of answer you are looking for, but I think it's accurate so I'm writing it here anyway. Often in math, we can encounter objects with multiple (provably equivalent) definitions, some more natural than others, and some can be better in giving an intuitive insight into how the object in question works. Once we've chosen a definition, the others can then be proven as theorems.
If I guess correctly, your definition of the exponential function $\exp$ is given by first defining
$$\log(x)=\lim_{n\to\infty}n(x^{1/n}-1),$$
and then defining $\exp$ to be the inverse function of the logarithm. But this is not a very enlightening definition. A much more common definition would literally be that $\exp$ is the unique function $f:\mathbb R\to\mathbb R$ satisfying $f'(x)=f(x)$ for all $x$, and $f(0)=1$. Proving such a function exists and is unique takes some work, then showing that this is indeed equivalent to your definition takes some more. But once this is done, we can then accept, as a fact, that $\exp$ is the function that is meant to satisfy $\exp'=\exp$. We can define this in multiple ways, but this is the core property that is central to the exponential function---some might say, the defining property of the exponential function.
So your question is:

Are there easier ways of proving that $\dfrac{d}{dx}e^x=e^x$?

I would say yes: by assuming it is the case, by taking it to be true by definition. Showing that other definitions are equivalent to this definition is nontrivial and needs to be done of course, but as you observed might not necessarily be very intuitive or give much insight. To understand what the exponential function is deeply, this definition is the way to go.

To show that the definition $\frac{d}{dx}e^x=e^x$ is equivalent to the "arithmetic definition" $e^{a+b}=e^ae^b$ is an interesting problem. To go from the former to the latter, see the link provided by KM101 in the comments. On the other hand, let's try to start from the latter and try to go to the former. Now, differentiation deals with the "local growth rate" of a function with response to small changes in $x$, and we have an additive definition, so we consider
$$\exp(x+\Delta x)=\exp(x)\exp(\Delta x)$$
for a small $\Delta x>0$. Now in the definition of the derivative, we consider
$$\exp(x)\lim_{\Delta x\to 0}\left(\frac{\exp(\Delta x)-1}{\Delta x}\right).$$
To show that this is indeed $\exp(x)$, all we need to do is to show that the latter limit is $1$. Note that the limit is actually just $\exp'(0)$. Consider what we've done so far: we've reduced the proof of $\exp'=\exp$, which is information regarding the "growth rate" of $\exp$ globally, into the proof of just $\exp'(0)=1$, at a single point!
So how can we prove this, knowing just $\exp(a+b)=\exp(a)\exp(b)$? Well... unfortunately we can't. See, if we define $f'(0)=k$ for any arbitrary real number $k$, where $f$ satisfies $f(a+b)=f(a)f(b)$, we will get a perfectly well-defined function $f$ (you can try to show this). But when we make the choice that $f'(0)=1$ (or in other words $k=1$), then we end up with a function which is its own derivative. Indeed, this is the property that motivates the choice $f'(0)=1$.
In hindsight, if $f'(0)=k$ and $f(a+b)=f(a)f(b)$ for all $a,b$, we can describe $f$ in general: it is simply $f(x)=e^{kx}$.

A: The exponential function of base e is defined as the (monovariable real) function equal to the value of its first derivative for any value of x.
You are trying to prove the definition.

A: Another intuitive approch is to consider $g(x)=2^x$, $h(x)=3^x$ and since by convexity of the exponential function

*

*$\frac12<g'(0)<1$

*$\frac23<h'(0)<2$
we have that there exists $2<e<3$ such that for $f(x)=e^x$
$$ f'(0)=\lim_{x\to 0}\frac{e^x-1}{x}=1$$
and therefore $\forall x_0\in\mathbb R$
$$ f'(x_0)=\lim_{x\to x_0}\frac{e^x-e^{x_0}}{x-x_0}=e^{x_0}\cdot \lim_{(x-x_0)\to 0}\frac{e^{(x-x_0)}-1}{x-x_0}=e^{x_0}$$


text:
Q: Avoid click in two elements with angular I have the following HTML:

    {{image.Votes}}

And the following Javascript:
 application.controller('ImageController', function ImageController($scope, ImageService, ngDialog) {

    $scope.model = {
      images: [],
      loading: false,
      pages: { instagram: '' }
    }

    var load = function () {
      $scope.model.loading = true;
      ImageService.GetList($scope.model.pages.instagram)
        .success(function (data, status, headers, config) {
          $scope.model.images = $scope.model.images.concat(data.Images)
          $scope.model.pages.instagram = data.NextInstagramPage;
        })
        .error(function (data, status, headers, config) { })
        .finally(function () {
          $scope.model.loading = false
        });;
    }

    $scope.loader = function () {
      return $scope.model.loading ? 'loading' : 'load more';
    }

    $scope.open = function (image) {
      var scope = $scope.$new();
      scope.model = { image: image };
      ngDialog.open({
        className: "dialog",
        plain: false,
        scope: scope,
        template: 'image'
      });
    };

    $scope.vote = function (image) {
      ImageService.Vote(image)
         .success(function (data, status, headers, config) { })
         .error(function (data, status, headers, config) { });
    };

    load();

  });

The problem is when I click on vote both actions take place: open and vote.
This is because vote is inside the div image?
How should I avoid this?
UPDATE
I also tried the following which seems to work:
  application.directive('stopPropagation', function () {
    return {
      restrict: 'A',
      link: function (scope, element, attr) {
        element.bind(attr.stopPropagation, function (e) {
          e.stopPropagation();
        });
      }
    };
  });

Then use it as follows:

Does anyone sees any problem in using such a directive for this?

A: Change you code to following. You need to stop event propagation

        {{image.Votes}}

 application.controller('ImageController', function ImageController($scope, ImageService, ngDialog) {

        $scope.model = {
          images: [],
          loading: false,
          pages: { instagram: '' }
        }

        var load = function () {
          $scope.model.loading = true;
          ImageService.GetList($scope.model.pages.instagram)
            .success(function (data, status, headers, config) {
              $scope.model.images = $scope.model.images.concat(data.Images)
              $scope.model.pages.instagram = data.NextInstagramPage;
            })
            .error(function (data, status, headers, config) { })
            .finally(function () {
              $scope.model.loading = false
            });;
        }

        $scope.loader = function () {
          return $scope.model.loading ? 'loading' : 'load more';
        }

        $scope.open = function (image, $event) {
          var scope = $scope.$new();
          scope.model = { image: image };
          ngDialog.open({
            className: "dialog",
            plain: false,
            scope: scope,
            template: 'image'
          });

          $event.stopPropagation();
        };

        $scope.vote = function (image, $event) {
 $event.stopPropagation();
ImageService.Vote(image)
             .success(function (data, status, headers, config) { })
             .error(function (data, status, headers, config) { });
        };

        load();

      });

A: Because the event is bubbling. Both elements are capturing it. You could use event.stopPropagation to stop the event from propagation or event.preventDefault to prevent the default behavior of the event and implement by yourself.


text:
Q: Dijkstra SDSP Algorithm I'm trying to implement Dijkstra Algorithm for Single Destination Shortest Path using Adjacency List and PQ as Min Heap. The output must show path of all vertices to destination vertex, if path exists, and if yes, the sum of it (shortest), if no, NO PATH.
Link to entire code
Input Format:

*

*First line is number of vertices, n

*Second line onwards: (Vertices from 1 to n)

*

*First column is vertex.

*After, multiple pairs, <vertex, weight>

*test.txt

4
1 2 4 3 5 4 5
4 1 7 3 3
2 1 3 4 10

According to GDB, it showed Segmentation fault found at extractMin function.
Program received signal SIGSEGV, Segmentation fault.
0x00401746 in extractMin ()

Client.c
Extracting input from the text.txt file and create a directed graph
FILE *fptr = fopen("test.txt", "r");
    if (fptr == NULL) exit(1);

    int n;
    if (fscanf(fptr, "%d", &n) == 1 && n > 0)
    {
        Graph *graph = createGraph(n);
        int c;
        while ((c = fgetc(fptr)) != EOF && c != '\n');
        char *line = NULL;
        size_t len = 0;

        while (getline(&line, &len, fptr) > 0)
        {
            char *cur = line;
            int ccs = 0;
            int v1;

            if (sscanf(cur, "%d%n", &v1, &ccs) == 1)
            {
                cur += ccs;
                int v2;
                int w;
                while (sscanf(cur, "%d %d%n", &v2, &w, &ccs) == 2)
                {
                    addEdge(graph, v1, v2, w);
                    cur += ccs;
                }

                fputc('\n', stdout);
            }

        }
        free(line);
        for (int i = 0; i < n; i++)
            dijkstra(graph, i);
    }

Server.c
struct MinHeapNode* extractMin(MinHeap* minHeap)
{
    if (isEmpty(minHeap))
        return NULL;

    struct MinHeapNode* root = minHeap->array[0];
    struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1];
    minHeap->array[0] = lastNode;

    minHeap->pos[root->v] = minHeap->size-1;
    minHeap->pos[lastNode->v] = 0;

    --minHeap->size;
    minHeapify(minHeap, 0);

    return root;
}
void dijkstra(Graph* graph, int dest)
{
    int v = graph->vertices;
    int distance[v];
    int pathFollow[1000]={0};
    int ind = 0;

    MinHeap* minHeap = createMinHeap(v);

    for (int i = 0; i < v; ++i)
    {
        distance[v] = INT_MAX;
        minHeap->array[v] = newMinHeapNode(v, distance[v]);
        minHeap->pos[v] = v;
    }

    minHeap->array[dest] = newMinHeapNode(dest, distance[dest]);
    minHeap->pos[dest] = dest;
    distance[dest] = 0;
    decreaseKey(minHeap, dest, distance[dest]);

    minHeap->size = v;

    while (!isEmpty(minHeap))
    {
        struct MinHeapNode* minHeapNode = extractMin(minHeap);
        int u = minHeapNode->v;
        AdjListNode* path = graph->array[u].head;
        while (path != NULL)
        {
            int v = path->vertex;
            if (isInMinHeap(minHeap, v) && distance[u] != INT_MAX &&
              path->weight + distance[u] < distance[v])
            {
                distance[v] = distance[u] + path->weight;
                if(pathFollow[ind-1] != u)
                    pathFollow[ind++]=u;
                decreaseKey(minHeap, v, distance[v]);
            }
            path = path->next;
        }
    }
    printArr(distance, v, pathFollow, dest);
}

void printArr(int dist[], int n, int pathFollow[], int dest)
{
    printf("%d", dest+1);
    int j = 0;
    if(dist[n-1]!=0 && dist[n-1] < 100000000)
    {
        int k = j;
        printf(" %d", pathFollow[k]+1);
        while(pathFollow[j]!=0)
        {
        printf(" %d", pathFollow[j++]);
        }
        printf(" %d %d\n",n, dist[n-1]);
    }
    else
    {
        printf("NO PATH\n");
    }
}

A: I'm not going to debug this entire program but here are a few errors:

*

*You create
 Graph *graph = createGraph(n);

and are then accessing graph->array[src].head.
This is a problem since n is just the total number of vertices, in your case 4 but when that addEdge() is called with something like 4 1 7, that is a heap-buffer-overflow. You need to account for the 0-indexed arrays that you create.

*Another overflow problem, this time of the stack buffer, would be at:
int v = graph->vertices;
int distance[v];

But then this is referred to as
distance[v] = INT_MAX;

again not considering the 0-indexed array. Also, that code seems suspect and should be distance[i] = INT_MAX I believe.
Please review your own code for more such errors, especially for array index overflows, use Address Sanitizers to check code for memory errors, step through each line of the program, and see if what's expected is indeed happening. You mention the program faults around extractMin(). Check if it is accessing the memory it is supposed to access. SIGSEGV indicates illegal memory access. Is struct MinHeapNode* root pointing to something you allocated? Is struct MinHeapNode* lastNode pointing to something you allocated?


text:
Q: Node.js require I searched and read many articles but could not find a clear answer.
I have a module that exports one simple function that relies on filesystem ('fs') module to check if file exists.
In my 'main' module I also have a function that requires('fs').
Is there a way to use 'fs' from my main module instead of require('fs') in both files?
I thank you in advance

A: You shouldn't need to do this, because require is internally optimized and it costs very close to nothing to re-import the same module again.  (The cost is literally just checking a cache and returning the same module again.)
But having said that, your function can "require" the fs object (or any other object/function/etc. from the fs module that it needs) as a parameter when calling the function.  For example:
module.exports = function (fs) {
    // use the fs object
}

Then in your consuming code...
const fs = require('fs');
const myFunc = require('./your_module');

myFunc(fs);


text:
Q: Using xcopy to copy multiple files/directories, some of which have spaces I'm trying to use xcopy to copy over several files and directories onto an external hard drive. The following command works fine...
xcopy d:\location\folder /e

... except it's not copying over any files/directories withing d:/location/folder that have spaces. I understand that Windows requires file names with spaces need to be enclosed in quotes, but what do I do if I'm trying to do a huge recursive copy where there may be several files or folders with spaces in the name?

A: You should use quotes the following way:
xcopy "d:location\folder\anotherfolder\folder with spaces"

Note the unit letter and the colon go outside the quotes and no \ at the beginning either.

A: Use quotes:
xcopy "d:\location\folder" /e

A: This may not be the answer to your questions, but an alternative to xcopy is robocopy. See the following xcopy about subdirectories.
http://ss64.com/nt/xcopy.html
Additionally if there are spaces in the source or target directories. Then you should wrap them in quotes ("). For example:
xcopy "soure path with spaces" "targetPath"
Cheers

A: The example given makes me uneasy. Maybe needlessly, but my read on the Win cmd.exe window (using [] to enclose related bits :^) is:
[command] [d:\location\folder] [DESTINATION DRIVE:LOCATION:FOLDER] [/E]
Maybe lower-case /e, works as well, maybe in implied destination to present location works. When I type "help xcopy" is lists the command name, the source, and the destination and the /Upper Case Switches. Yes, destination is optional. But when results don't match your expectation, dropping back to the canonical form, with every jot and tittle in place, seems like a stronger start. One can focus on the thing that's not working.
The help example doesn't use it, but I also feel a bit safer if its clear that the literal path given is the stem and explicitly put in a wildcard:
C:>xcopy /E C:\Backup* C:\ToyVmBackup
C:\Backup\Backup_VM1_2015-08-27T221110.vbk
C:\Backup\Backup_VM2_2015-08-31T221227.vbk
C:\Backup\VeeamConfigBackup\SVC-L7-WABBOTT\SVC-L7-WABBOTT_2015-08-24_10-00-15.bco
3 File(s) copied
Ok, I prefixed the /E and got away with it. Its ambiguity I'm trying to control, as long as /E starts with a '/' it won't be taken for a path...


text:
Q: XHTML: how to highlight matching tag? I'd like highlighting of the matching HTML tag when the cursor is on the specific tag.
I'm looking for something like highlight matching parentheses in options menu.
I've checked the question How can I highlight unmatched HTML tags in Emacs? which is close to what I search but I want highlight of all the matching tags (where the cursor is), not only the errors.

A: web-mode provides this. You can enable with web-mode-toggle-current-element-highlight

A:
web-mode provides this. You can enable with web-mode-toggle-current-element-highlight

You can add (setq web-mode-enable-current-element-highlight t)
into your web-mode-hook to make this behavior persistent.


text:
Q: Webpack-RequireJS interop hacking: Module has not been loaded in context error, but sibling has I have a problem in a system where we liberally mix and match Webpack and RequireJS. We have a static code base creating a Web UI of sorts, but within this Web UI dynamic parts can be requested from other places.
The static Web UI part is built using Webpack. The dynamic parts, however, are naturally requested using RequireJS. Now this is nice and simple, but the problem comes that some of those dynamic parts want to refer back to the static part. This would normally cause duplication as RequireJS fetches and initializes the code anew, disregarding the fact that the code is already present in the Webpack-created bundle.
To solve this problem I came up with a (ingenious) freaky hack where at the beginning of our static code we import those static parts we know will be required through RequireJS and window.define("static/code/location", () => import "static/code/location") (paraphrasing, this actual code would not work of course).
So we essentially grab the Webpack module reference and define to RequireJS that this module provides a particular named module. This actually worked and I was overjoyed.
However a weird problem has appeared. One dynamically required piece of code has, inside it, RequireJS's const a = require("some/path/a"); syntax and for some reason this particular "some/path/a" errors with module has not been loaded yet for context: _. Use require([]). This will happen even if, right before the require line, I manually (through developer console) do define("path/to/a", () => {}). Furthermore, doing const b = require("some/path/b"); does work, returns the proper module and doesn't error, despite the path to the modules being the same and both of these modules originally being defined to RequireJS side by side in the freaky hack solution that I described above.
Any clues as to what is happening, why is one of the siblings defined while the other isn't and cannot be defined, would be most appreciated. Although this is definitely not a particularly "good" use case... Sorry about that.

A: I found a way to fix the situation. I still have no idea what actually caused the error, but the way around this was to define path/to/a as plain object instead of a parameterless function returning the plain object.
window.define("path/to/a", import("a")) (Once again paraphrasing.)


text:
Q: Why does the additive subgroup of $\mathbb{R}$ generated by $1$ and $\sqrt{2}$ contain arbitrary small elements? Let $G\subset \mathbb{R}$ be the additive subgroup of $(\mathbb{R},+)$ defined by $G=\mathbb{Z}+\sqrt{2}\mathbb{Z}$. I want to prove that for every $\epsilon>0$ there exists an element $g_\epsilon\in G$ with $\epsilon>g_\epsilon>0$. Can anybody imagine a nice proof?
(I coundn't think of an appropriate tag for this question. Please feel free to add or remove one)

A: If you know the more general result about subgroups of $(\mathbb{R},+)$ : a subgroup of $(\mathbb{R},+)$ is either dense or of the form $a\mathbb{Z}$ (see for example here). Then you see that if $\mathbb{Z}+\sqrt{2}\mathbb{Z}$ were of the form $a\mathbb{Z}$ then there will be $p,q\in \mathbb{Z}$ such that $1=aq$ and $\sqrt{2}=ap$.
Consequently, $\sqrt{2}=\frac{p}{q}$ which is absurd since $\sqrt{2}\not\in \mathbb{Q}$. So $\mathbb{Z}+\sqrt{2}\mathbb{Z}$ is dense.

A: Hint: $0<\sqrt 2 -1< 1$ and this group is also closed under multiplication.


text: Q: Add-ins not working for others users as they are not logged into Word application with the organization I am using centralized deployment to deploy my add-ins to users but it is not working if any user has not logged into desktop word application with the organization email, I want that external users can also use my add-ins that are not in the organization. Is there any way I can do that with Centralized deployment? I tried to do organization log-in in word application as a different user but organization login was not possible it seems, but as an admin as I am already logged into word application I am able to get the add-ins.


text:
Q: Disable App Transport Security while working with Socket.IO I am trying to connect to Socket.IO Server. I am using swift library
https://github.com/socketio/socket.io-client-swift
Here is my sample code
NSString *url = [NSString stringWithFormat:@"myIP:443];

    self.socket = [[SocketIOClient alloc] initWithSocketURL:url opts:nil];

    [socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"socket connected");
    }];

    [socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
        double cur = [[data objectAtIndex:0] floatValue];

        [socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
            [socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
        });

        [ack with:@[@"Got your currentAmount, ", @"dude"]];
    }];

    [socket connect];

This is what i have used in my plist
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>xx.xx.xxx.xxx</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
        </dict>
    </dict>

I am still getting
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

A: Then maybe it afterwards tries to connect to API with another address, that you have not provided in the info.plist file.
Just as a temporary thing, you could do this, to eliminated this Transport Security error:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


text:
Q: Textarea input - how to deal with paragraphs and headings? I currently use the following expression which I use to put paragraph tags around textarea input before storing it in a MySQL database.
$inputText = str_replace('

', '', '
' . preg_replace('#([\r\n]\s*?[\r\n]){2,}#', '
$0
', $inputText) . '
');

This works well and good, except when I wish to use header tags. These are then surrounded by unwanted paragraph tags:

Test Header

While this displays as expected, it is not great from a validation point of view.
Can anyone suggest an improved expression and/or method to catch headers tags and only apply the paragraph tags to actual paragraphs? Or, an expression which I can apply to my input prior to the expression I'm currently using to produce the same desired effect.
As a side note, I would like to be able to enter stand-alone hyperlink 'a' tags and still have them surrounded with paragraph tags as before.
I have considered that it may just be easier to manually edit the details after they are entered into the database to remove the unwanted paragraph tags.

A: I use this function from wordpress, wraps p's around paragraphs nicely as well as line breaks whilst preserving HTML:
function wpautop($pee, $br = 1) {
    $pee = $pee . "\n"; // just to make things a little easier, pad the end
    $pee = preg_replace('|
\s*
|', "\n\n", $pee);
    // Space things out a little
    $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
    $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
    $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
    $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
    $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
    $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "
$1
\n", $pee); // make paragraphs, including one at the end
    $pee = preg_replace('|
\s*?
|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
    $pee = preg_replace('!
([^<]+)\s*?(</(?:div|address|form)[^>]*>)!', "
$1
$2", $pee);
    $pee = preg_replace( '|
|', "$1
", $pee );
    $pee = preg_replace('!
\s*(</?' . $allblocks . '[^>]*>)\s*
!', "$1", $pee); // don't pee all over a tag
    $pee = preg_replace("|
(|i', "

", $pee);
    $pee = str_replace('

', '

', $pee);
    $pee = preg_replace('!
\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
    $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*
!', "$1", $pee);
    if ($br) {
        $pee = preg_replace('|(?<!
)\s*\n|', "
\n", $pee); // optionally make line breaks
    }
    $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*
!', "$1", $pee);
    $pee = preg_replace('!
(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
    $pee = preg_replace( "|\n
$|", '
', $pee );
    return $pee;
}

A: You can use the strip_tags function like this:
<?php
$text = '

Test Header

';
echo strip_tags($text);
echo "\n";

// Allow
 and

echo strip_tags($text, '

');
?>

It should work out.


text:
Q: Security for React front-end and Node back-end I'm relatively new to the modern JavaScript web development world. I've built a very simple Node/Express back-end and a separate React front-end. My vague plan is to have users that will have permission to access certain areas of the front-end, and then have the front-end make requests to the back-end. Can the front-end and back-end share the same authentication/authorization scheme? Can they both use something like Auth0? How can I make these two secure?
I'm a little stuck and would appreciate any advice or a nudge in the right direction. I'm mostly stuck because these are two separate applications but the same "user" would technically have permissions to certain React views as well as certain Express endpoints - how they moosh together?
Thanks.

A: Although seems not directly related to your topic, but I would actually suggest you try Meteor if you are not planning to immediately start working on large projects (not pressing too hard on scalability).
Meteor has a builtin support for Accounts and interacts with MongoDB nicely, and it also has its own DDP protocol that simplifies API call massively. It also interacts nicely with React.
If you think Meteor might not be a good choice for yourself, you could still learn from its design policies of authorization, etc. It has quite a bit package source code that are not too difficult to understand, and should be helpful for you to learn the basic idea. (Actually, Meteor's Accounts package already implements the basic idea mentioned by another answerer, you can learn from its design principles)

A: When users log in to your site, issue them with an access token that they keep client side. On front-end, check if user has token and correct permissions before rendering components. On back-end, send the token as request headers to the endpoints.

A: I have implemented a similar case, but with the spring boot kotlin at the backend instead. My solution is using JWT token to validate the authentication and authorization.

*

*User logins by input login form and send POST method to backend via a REST API.Backend validates credential and returns the JWT token including encrypted     user_role, expiration date, etc... if valid or 403 exception

*Front-end decodes the JWT (using jwt-decode lib or something else),
save it to validate the access permission to specific page in the
website based on user_role. Eg: role='ADMIN' can access to admin dashboard page, role='USER' can access user profile page, etc.
If you use express as the backend, I suggest to use the feathersjs. It has backend solutions for this and an optional front end version. Refer: https://docs.feathersjs.com/api/authentication/jwt.html

A: Secure Front end (React.js) and Back end (Node.js/Express Rest API) with Keycloak follow this


text:
Q: Declarative External Service Suddenly Getting Media Type Response Error Open API 2.0 schema used as Invocable Apex with Flow that has been working for six months. Two days ago we started getting an error on the 200 response.
Expected declared response media type application/json, but got text/plain; charset=UTF-8 for operation get

We have a Case opened since we didn't touch the schema and barring a change by the other party (Federal Govt), then must've been a change at Salesforce but I'm hoping someone has a suggestion for how we might edit our schema now to overcome this error.
The responses which look like this in Postman used to be recognized as JSON. This is valid JSON and will format correctly if I put into an editor. (The below is public info)
{"resultCount":1,"results":[{"created_epoch":"1135112244000","enumeration_type":"NPI-2","last_updated_epoch":"1223408717000","number":"1588640692","addresses":[{"country_code":"US","country_name":"United States","address_purpose":"MAILING","address_type":"DOM","address_1":"1364 CLIFTON RD NE","address_2":"ROOM HB48","city":"ATLANTA","state":"GA","postal_code":"303221064","telephone_number":"404-686-7041","fax_number":"404-712-5731"},{"country_code":"US","country_name":"United States","address_purpose":"LOCATION","address_type":"DOM","address_1":"1364 CLIFTON RD NE","city":"ATLANTA","state":"GA","postal_code":"303221064","telephone_number":"404-686-7041","fax_number":"404-712-5731"}],"practiceLocations":[],"basic":{"organization_name":"EMORY UNIVERSITY","organizational_subpart":"NO","enumeration_date":"2005-12-20","last_updated":"2008-10-07","status":"A","authorized_official_first_name":"Jimmy","authorized_official_last_name":"Hatcher","authorized_official_middle_name":"T","authorized_official_telephone_number":"4046862983","authorized_official_title_or_position":"CFO Emory Healthcare","authorized_official_name_prefix":"Mr."},"taxonomies":[{"code":"282N00000X","desc":"General Acute Care Hospital","state":"GA","license":"044-049","primary":true}],"identifiers":[{"code":"05","desc":"MEDICAID","issuer":null,"identifier":"00000712A","state":"GA"},{"code":"06","desc":"MEDICARE OSCAR/Certification","issuer":null,"identifier":"110010","state":"GA"}],"endpoints":[],"other_names":[]}]}

The relevant path statement is:
"paths": {
    "/": {
      "get": {
        "description": "Get NPPES NPI data",
        "consumes": ["application/x-www-form-urlencoded"],
        "produces": ["application/json"],

A: It does appear the issue was the response header was changed by the 3rd party from application/json to text/plain based on the Postman information.


text:
Q: Rails 5 - Namespaced folders I am trying (and not getting very far) to understand how to use namespaced folders in my Rails 5 app.
I have tables in my schema for users, identities and settings.
The associations are:
User
has_many :identities, dependent: :destroy
has_one :setting, dependent: :destroy

Setting
belongs_to :user

Identity
belongs_to :user

I have organised my controller folders so that I have app/controllers/users/identities_controller.rb and app/controllers/users/settings_controller.rb
Each of those controllers has this first line:
class Users::SettingsController < ApplicationController
class Users::IdentitiesController < ApplicationController

I have organised my views folders in a similar way.
I have app/views/users/settings/show.
I don't have views for identities, except for a partial called _authentications.html.erb. Currently that is stored in the app/views/users folder. I'm trying to move it to the app/views/users/settings folder and render it from the app/views/users/settings/show page.
In my routes file I have:
resources :users, shallow: true do
    scope module: :users do
      resources :assign_roles
      resources :identities
      resources :profiles
      resources :settings
    end

When I render the authentications partial from the app/views/users show page, I have no errors. Everything works. I am getting stuck because there is something that Im not understanding & I don't know what it is.
I'm trying to move the authentications partial to app/views/users/settings so that I can render it from app/views/users/settings/show.
When I try to do that, I get an error that says:
undefined method `identities' for nil:NilClass

That error references this block of my authentications partial:
<% if @user.identities.map(&:provider).include?('linkedin') %>

<% else %>
    <%= link_to 'Connect your Linkedin account', user_linkedin_omniauth_authorize_path %>
<% end %>

I don't understand whether I'm supposed to try to add settings in that if statement somehow? I tried if @setting.user.identities (only as a guess), but it didn't work.
Can anyone see what I'm doing wrong? I can't seem to find a plain english explanation of how to get started with nesting and namespacing.
Add settings controller
class Users::SettingsController < ApplicationController
    before_action :set_setting, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  after_action :verify_authorized

  def index
    @settings = Setting.all
    authorize @settings
  end

  def show
    # authorize @setting
  end

  def new
    @setting = Setting.new
    authorize @setting

  end

  def edit
  end

  def create
    @setting = Setting.new(setting_params)
    authorize @setting

    respond_to do |format|
      if @setting.save
        format.html { redirect_to @setting }
        format.json { render :show, status: :created, location: @setting }
      else
        format.html { render :new }
        format.json { render json: @setting.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
   respond_to do |format|
      if @setting.update(setting_params)
        format.html { redirect_to @setting }
        format.json { render :show, status: :ok, location: @setting }
      else
        format.html { render :edit }
        format.json { render json: @setting.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @setting.destroy
    respond_to do |format|
      format.html { redirect_to settings_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_setting
      @setting = Setting.find(params[:id])
      authorize @setting
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def setting_params
      params.require(:setting).permit( :newsletter )
    end

end

A: There's no @user variable being set in your show action, which is why you're getting that NoMethodError undefined method 'identities' for nil:NilClass
 error.  @user returns nil in your partial. You can either set this in the controller with @user = current_user (assuming you are using devise) or replace @user with current_user in your partial.
Having said all of that - is there any particular reason that you want to namespace all of your controllers like this? Just because you have set up a has_many or has_one relationship between your models doesn't necessarily mean that you have to namespace your controllers as well. If you have a good reason to do it then fine; if not then you could consider moving the controllers out of the users namespace.


text:
Q: Каким образом делать такое подчеркивание?
Как делать подчеркивание такого рода? Есть две идеи, это SVG и просто PNG картинка с абсолютным позиционированием относительно блока с заголовком. Может есть способы с помощью чистого CSS?

A: Самое простое решение - это svg

svg {
width:347;
height:188;
background:#3D4248;
}
 #txt {
font-size:70px;
 font-family:sans-serif;
 fill:white;
}
svg path {
fill:none;
stroke:white;
stroke-width:2;
}
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
        width="347" height="188" viewBox="0 0 347 188" >

<text id="txt" x="70" y="120" >Expire</text>
 <path d="m74.9 149.5 97.2 0 5.3 5.7 96.8 0-0.4 0" />
</svg>

A: Решение на CSS:

* {
  margin: 0;
  padding: 0;
}

.wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #3D4248;
  margin: 1rem;
  width: 250px;
  height: 200px;
  font-size: 4em;
  font-family: sans-serif;
  color: #fff;
}

.wrapper .line {
  position: absolute;
  bottom: 50px;
  right: 34px;
  width: 98px;
  height: 5px;
  background-color: #3D4248;
  z-index: 2;
}

.wrapper .line::before {
  content: "";
  display: block;
  position: absolute;
  bottom: -0.7px;
  left: -1.8px;
  width: 10px;
  height: 1px;
  background-color: #fff;
  transform: rotate(45deg);
}

.wrapper span {
  position: relative;
}

.wrapper span::before {
  content: "";
  display: block;
  position: absolute;
  bottom: -10px;
  width: 180px;
  height: 1px;
  border-bottom: 1px solid #fff;
}

.wrapper span::after {
  content: "";
  display: block;
  position: absolute;
  bottom: -17px;
  right: 1px;
  width: 91px;
  height: 1px;
  border-bottom: 1px solid #fff;
}

  Expire


text:
Q: When using requestAnimationFrame, how to make part of animation update faster I am using requestAnimationFrame to make a game (game like a snake), and the frame update speed of the game is initially updated each second one time
It needs to update the "requestAnimationFrame" of this snake from a second each time to 0.5 second each time. Because of many snakes' design and while a snake touches any item, it will get a speed-up situation for 10 seconds.
My question is how to maintain the main "requestAnimationFrame" (updated every second), and there is still another "requestAnimationFrame" (updated every 0.5 second)?
main requestAnimationFrame code
    let speed = 1;
    let lastRenderTime = 0;

    const doAnimation = function (currentTime) {

        window.requestAnimationFrame(doAnimation);

        const secondRender = (currentTime - lastRenderTime) / 1000;  // secondRender is used to control the update per second

        if (secondRender < 1 / speed) {
            return;
        }
        lastRenderTime = currentTime
    }

    window.requestAnimationFrame(doAnimation);

A: requestAnimationFrame fire rate is usually around 60Hz. That is 60 calls per second, giving you a maximum theoretical precision of ~16ms (0.016s).
This means that inside you loop you can make things update at any rate above that. But why would you like to truncate precision?
The whole point of requestAnimationFrame is to know exactly when a repaint will happen and to pass information about your animation at the right time. As an example: if your snake has to move 1000px every second, why would you notify the browser about the update every second? Ideally you should update your view on every frame. So in this example, a 16px variation every 16ms.
Please see the following snippet and note that there are no conditionals, anywhere. But just continuous update.
Obviously final implementation would depend on your use case, but this is only the working principle.

const boxA = document.getElementById('boxA'); // DEMO
const boxB = document.getElementById('boxB'); // DEMO

let xA = 0; // DEMO
let xB = 0; // DEMO

const speedA = 80; // [px/s]
const speedB = 160; // [px/s]

let then = 0;

const animate = function (now) {
    window.requestAnimationFrame(animate);

    const delta = (now - then) / 1000;

    // A
    const a = speedA * delta;
    boxA.style.transform = `translateX(${xA += a}px)`; // DEMO

    // B
    const b = speedB * delta;
    boxB.style.transform = `translateX(${xB += b}px)`; // DEMO

    then = now
}

window.requestAnimationFrame(animate);
.container {
  display: flex;
  flex-direction: column;
}

#boxA,
#boxB {
  display: inline-block;
  height: 50px;
  width: 50px;
  transform: translateX(0);
}

#boxA {
  background-color: #ff0000;
}

#boxB {
  background-color: #0000ff;
}

A:

let then, then2;
(function loop(delta) {
  then = then || delta;
  then2 = then2 || delta;

  let time = delta - then;
  let time2 = delta - then2;

  if (time > 1000) {
    then = delta;
    // in here every second
  }
  if (time2 > 500) {
    then2 = delta;
    // in here every 0.5 seconds
  }

  document.body.innerHTML = time.toFixed(2) + '
' + time2.toFixed(2);
  requestAnimationFrame(loop);
})();


text:
Q: Proof increasing variance when subtracting random variables Some students asked me why variances get added despite two random variables are subtracted. The example looked like this $$y(n)=x(n)-x(n-1)$$ where x(n) is assumed to be iid. We look for the expected value of $y$ and its variance.
I see why the variance has to be added. It is quite intuitive, but I had a hard time explaining it to them. Numerical examples worked, but is there a quick way how one could proof it? Some research on the internet showed me only that it is defined that way.

A: $$
\mathop{\mathrm{Var}}(x-y)=
\mathbb E(x-y)^2 - \Big(\mathbb E(x-y)\Big)^2=\\
\mathbb Ex^2-2(\mathbb Exy)+\mathbb Ey^2-(\mathbb Ex)^2+2(\mathbb Ex)(\mathbb Ey)-(\mathbb Ey)^2\\
$$
Since $x$ and $y$ are independent $\mathbb Exy=(\mathbb Ex)(\mathbb Ey)$. Finally:
$$
\mathop{\mathrm{Var}}(x-y) = \mathbb Ex^2 -(\mathbb Ex)^2 + \mathbb Ey^2 -(\mathbb Ey)^2 =
\mathop{\mathrm{Var}} x+ \mathop{\mathrm{Var}}y
$$


text:
Q: Hardcoding FFMPEG subtitles on MP4 / MKV I am using FFMPEG to hard code subs into a video. Having read many posts on the best approach, and whether to use mkv or mp4, but am still none the wiser. The code below uses an mp4 file. The subtitles appear to be processed, judging by the output, but the size 0kb seems to show that nothing is actually rendered, and the output file has audio and video, but no subtitles.
Metadata in VLC shows that a subtitle file is present - but empty.
Here is an example of my SRT file (not putting an empty line in 1 gives an input error msg):
1
00:00:00,000 --> 00:00:00,001

2
00:00:00,001 –-> 00:00:04,761
He drives to school every morning

3
00:00:04,761 –-> 00:00:13,061
Cause love comes slow and it goes so fast

My command line code is:
`ffmpeg -i #{inputfile} -i #{srt_file}  -filter_complex "[0:v][1:s]overlay" #{outputfile} -y`

I have also tried:
`ffmpeg -i #{inputfile} -i #{srt_file}  -c:v libx264 -preset ultrafast \
-c:s mov_text -map 0 -map 1 #{outputfile}`

And the response:
ffmpeg version 2.5.4 Copyright (c) 2000-2015 the FFmpeg developers
built on Feb 25 2015 15:52:19 with Apple LLVM version 6.0 (clang-600.0.54)
(based on LLVM3.5svn)
configuration: --prefix=/usr/local/Cellar/ffmpeg/2.5.4 --enable-shared --enable-pthreads
--enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --
host-cflags= --host-ldflags= --enable-libx264 --enable-libmp3lame --enable-libvo-aacenc
--enable-libxvid --enable-libass --enable-vda
libavutil      54. 15.100 / 54. 15.100
libavcodec     56. 13.100 / 56. 13.100
libavformat    56. 15.102 / 56. 15.102
libavdevice    56.  3.100 / 56.  3.100
libavfilter     5.  2.103 /  5.  2.103
libavresample   2.  1.  0 /  2.  1.  0
libswscale      3.  1.101 /  3.  1.101
libswresample   1.  1.100 /  1.  1.100
libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from
'/Users/JW/Dropbox/T10/SBRI/_code/videos_final/3rd person present tense (303).mp4':
Metadata:
major_brand     : isom
minor_version   : 512
compatible_brands: isomiso2avc1mp41
encoder         : Lavf56.15.102
Duration: 00:00:43.17, start: 0.036281, bitrate: 862 kb/s
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 720x406 [SAR 406:405 DAR
16:9], 732 kb/s, 23.98 fps, 23.98 tbr, 24k tbn, 47.95 tbc (default)
Metadata:
  handler_name    : VideoHandler
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s
(default)
Metadata:
  handler_name    : SoundHandler
Input #1, srt, from '/Users/JW/Dropbox/T10/SBRI/_code/subs/3rd person present tense (303)/srt_file.srt':
Duration: N/A, bitrate: N/A
Stream #1:0: Subtitle: subrip
[srt @ 0x7fd082005c00] sub2video: using 720x576 canvas
[libx264 @ 0x7fd082801200] using SAR=406/405
[libx264 @ 0x7fd082801200] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 0x7fd082801200] profile High, level 3.0
[libx264 @ 0x7fd082801200] 264 - core 142 r2495 6a301b6 - H.264/MPEG-4 AVC codec - Copyleft
2003-2014 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0
analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1
trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6
lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0
constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0
weightp=2 keyint=250 keyint_min=23 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf
mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00

Output #0, mp4, to '/Users/JW/Dropbox/T10/SBRI/_code/videos_final/3rd person present tense
(303)_subs.mp4':
Metadata:
major_brand     : isom
minor_version   : 512
compatible_brands: isomiso2avc1mp41
encoder         : Lavf56.15.102
Stream #0:0: Video: h264 (libx264) ([33][0][0][0] / 0x0021), yuv420p, 720x406 [SAR 406:405
DAR 16:9], q=-1--1, 23.98 fps, 24k tbn, 23.98 tbc (default)
Metadata:
  encoder         : Lavc56.13.100 libx264
Stream #0:1(und): Audio: aac (libvo_aacenc) ([64][0][0][0] / 0x0040), 44100 Hz, stereo,
s16, 128 kb/s (default)
Metadata:
  handler_name    : SoundHandler
  encoder         : Lavc56.13.100 libvo_aacenc

Stream mapping:
Stream #0:0 (h264) -> overlay:main (graph 0)
Stream #1:0 (srt) -> overlay:overlay (graph 0)
overlay (graph 0) -> Stream #0:0 (libx264)
Stream #0:1 -> #0:1 (aac (native) -> aac (libvo_aacenc))

Press [q] to stop, [?] for help
sub2video: non-bitmap subtitle
frame= 1029 fps= 71 q=-1.0 Lsize=    4319kB time=00:00:43.17 bitrate= 819.6kbits/s
video:3612kB audio:675kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead:
0.751962%
[libx264 @ 0x7fd082801200] frame I:44    Avg QP:17.59  size: 16172
[libx264 @ 0x7fd082801200] frame P:495   Avg QP:22.62  size:  5016
[libx264 @ 0x7fd082801200] frame B:490   Avg QP:23.28  size:  1027
[libx264 @ 0x7fd082801200] consecutive B-frames: 24.2% 34.4%  7.6% 33.8%
[libx264 @ 0x7fd082801200] mb I  I16..4: 27.2% 43.8% 28.9%
[libx264 @ 0x7fd082801200] mb P  I16..4:  5.9% 14.8%  2.9%  P16..4: 31.1% 10.7%  4.3%  0.0%
0.0%    skip:30.3%
[libx264 @ 0x7fd082801200] mb B  I16..4:  0.2%  0.5%  0.2%  B16..8: 26.2%  3.3%  0.6%
direct: 1.1%  skip:67.8%  L0:40.7% L1:52.4% BI: 6.9%
[libx264 @ 0x7fd082801200] 8x8 transform intra:57.6% inter:72.8%
[libx264 @ 0x7fd082801200] coded y,uvDC,uvAC intra: 41.3% 60.2% 22.0% inter: 9.1% 14.5% 0.6%
[libx264 @ 0x7fd082801200] i16 v,h,dc,p: 41% 25% 11% 22%
[libx264 @ 0x7fd082801200] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 29% 20% 23%  4%  5%  6%  5%  5%  4%
[libx264 @ 0x7fd082801200] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 29% 20% 12%  5%  8%  9%  7%  6%  4%
[libx264 @ 0x7fd082801200] i8c dc,h,v,p: 53% 20% 21%  6%
[libx264 @ 0x7fd082801200] Weighted P-Frames: Y:14.1% UV:9.9%
[libx264 @ 0x7fd082801200] ref P L0: 68.6% 14.5% 12.3%  4.2%  0.4%
[libx264 @ 0x7fd082801200] ref B L0: 91.7%  7.5%  0.8%
[libx264 @ 0x7fd082801200] ref B L1: 98.4%  1.6%
[libx264 @ 0x7fd082801200] kb/s:689.28

What am I doing wrong?

A:
sub2video: non-bitmap subtitle

That's your error. You have text-based subtitles, so you need to burn them with the subtitles filter.
ffmpeg -i input.mp4 -filter:v subtitles=subtitles.srt output.mp4

The overlay filter only works when your subtitles are images, which is the case for dvdsub, for example.
Furthermore, the problem seems to be that your subtitle file is not formatted correctly. Your time stamp definition contains an en-dash (–) instead of a normal minus-hyphen (-):
–->

Replace it with a correct minus-hyphen:
-->

A: you need a font config file, viz:

C:\WINDOWS\Fonts

mono
monospace

sans-serif
serif
monospace
sans-serif

Times
Times New Roman
serif

Helvetica
Arial
sans

Courier
Courier New
monospace

serif
Times New Roman

sans
Arial

monospace
Andale Mono

Courier New

monospace

Courier

monospace

save as fonts.xml in ffmpeg bin directory and refer to it in your batch/cml as
set FONTCONFIG_FILE=fonts.xml
set FONTCONFIG_PATH=C:\Program Files\ffmpeg\bin


text:
Q: Navigate through big image I have a big image with coordinate points.
I need to navigate through these points by pressing onscreen buttons.
Only a part of image is seen on the screen at once (shows your location).
By pressing arrow button the view moves to the next part of the same image.
This example looks good.
Please, suggest any way to implement this functionality in Codename One App
Thank You.

A: You can use the Map component but you can place any image as a label icon within a scrollable container and just let the user use the touch/keys to scroll.


text:
Q: Problem importing module using express Not Using Bundler Im building a application using express and I dont want to use a bundler. When I import the axios module it gives me the next error: "Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../"."
I also made a repository of the entire project so far here: https://github.com/klaus4323/Natours-Nodejs.git
The code where I want to use axios is in the login.js (I am doing the nodejs online class of Jonas Schemetmann) file:

import axios from 'axios';
import { showAlert } from './alerts.js';
export const login = async (email, password) => {
try {
const res = await axios({
method: 'POST',
url: 'http://127.0.0.1:3000/api/v1/users/login',
data: { email, password },
});
if (res.data.status === 'success') {
showAlert('success', 'Logged in succesfully');
window.setTimeout(() => {
location.assign('/');
5000);
}
catch (err) {
showAlert('error', err.response.data.message);
}
};
export const logout = async () => {
try {
const res = await axios({
method: 'GET',
url: 'http://127.0.0.1:3000/api/v1/users/logout',
});
if ((res.data.status = 'success')) location.reload(true);
catch (err) {
showAlert('error', 'Error logging out. Try Again!');
}
};

A: Use like this
import * as axios from 'axios'


text:
Q: Upload images to imgur account from Spectacle I use Spectacle
(Screenshot with Spectacle > Share > ImGur)
for screenshots, it has an option to upload to imgur but then its opened in my graphic editor.
How could i upload this to my account instead?
I have read Extra space in Spectacle screenshot
but remember that i did not needed to use FTP. I hope i dont need own FTP-Server for this.


text:
Q: How can put the ChildBrowser plugin into a panel in Sencha Touch 2? I want to put ChildBrowser into a panel in a Sencha Touch 2 webpage. The first time I used an iframe, but the dimensions were very strange. Now I want to put the Childbrowser plugin into a panel, but I don't know how to do it. Any ideas please?

A: This isn't the way ChildBrowser works.  The Sencha Touch stuff lives in your main webview provided by PhoneGap.  ChildBrowser is another webview that you can use to display various things on the internet without hijacking your main app's webview.  No way to put one in the other.


text:
Q: Code Completion with omni completion for wxpython functions in vim i have omni completion working fine for regular python functions, but how do i also get it to work for the wxpython functions?

A: Did you try vim.org? It has a Pydiction project on there that includes wxPython autocomplete as well as several other 3rd party Python libraries.


text:
Q: SVN Versioning: How to have for each project its own revision scheme? Just a small SVN "problem" here.
I setup my own SVN server Setting up Subversion on Windows
Now I made a rep in which all my projects will go.
Now, I checked the rep out in a folder called "Projects".
Now If I make a project and check it in, that project is revision 1. If I make a second project, and check it in, that Project is at revision 2. Thus, if I make a change to Project 1, that project will then be at Revision 3.
What I would really want is for each project to have its own revision scheme. How do I do this?

A: The only way is to have each project in a completely separate repository.  Items within the same repository will always exhibit the behavior you mentioned in your question.
From Here

Unlike those of many other version control systems, Subversion's revision numbers apply to entire trees, not individual files. Each revision number selects an entire tree, a particular state of the repository after some committed change.

A: You have to create a separate repository for each project.  This is in general a good idea anyways so no downside there :)

A: Can you describe why having a single subversion revision number across multiple projects is a problem for you?
There are some legitimate advantages to using a single repository for all of your projects. The biggest one being that you're probably better able to control changes between common code in multiple projects.
If you have a problem with the concept of a single incrementing subversion revision number across multiple projects now, have you considered the situation where you branch one of your projects? (remembering that a normal branch will also have a globally incrementing subversion revision number)
It sounds like you're trying to use the repository revision number as part of the build or release number?
If that's the case perhaps you could consider implementing a different build numbering scheme for your project/s that can then be associated with the subversion revision number.
Such an association can be made by using a convention of creating branches with the release number and putting the subversion revision in the comment for the branch.
Some schemes were discussed in this question

A: You need to create repositories inside your "Projects" folder, and when you do the initial checkout, checkout "???/projects/repo1"... this will keep the working copies separate on your machine, and you will check in/out completely separately of each other.

A: They discuss it a little better here:  http://www.nabble.com/Multiple-Repositories-in-a-Windows-Server-td15014106.html
Basically you can do:
svnserve -r /path/to/repository

svn://hostname/

or
svnserve -r /path/to/directory/containing/many/repositories

svn://hostname/repositoryname/

Alternately, you could go server'less and just host the individual repositories on a local or networked drive.


text:
Q: Changing Variables within a Function in Tkinter I want the X and O animations to switch back and forth upon mouse clicks. The problem is in the function XorO. I don't really understand why, but it will only create Xs when I click it. I think it may have to do with how I wrote the turn variable.  Here is what I have.
from tkinter import *

tk = Tk()
width = 600
third = width / 3
canvas = Canvas(width=width, height=width)
tk.title = ("Tic Tac Toe")

line1 = canvas.create_line(200, 0, 200, 600)
line2 = canvas.create_line(400, 0, 400, 600)
line3 = canvas.create_line(0, 200, 600, 200)
line4 = canvas.create_line(0, 400, 600, 400)

def mouse_click(event):
    col = int(event.x / third)
    row = int(event.y / third)
    XorO(row, col)

def XorO(row,col):
    class XsorOs:
        turn = 1
        if turn is (1 or 3 or 5 or 7 or 9):
            canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)
            canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)

        else:
            canvas.create_oval(col * third + 5, row * third + 5, (col + 1) * third - 5, (row + 1) * third - 5)
        turn += 1

canvas.pack()
canvas.bind("<Button-1>", mouse_click)
canvas.mainloop()

A: The problem here is that the XsorOs object gets created every time you call the XorO method. This means XsorOs.turn is always 1.
One way would be to keep track of turn from outside and call it with global but the use
of global is something one should avoid especially it can get quite messy.
I would recommend keeping track of turn within an own child class of Tk separate "logic" class
I made you an example for the latter:
(please note that this example is super sloppy (particularly the variable naming) and should just show you what I meant)
# stays the same until 'line4 = canvas.create_line(0, 400, 600, 400)'
class XsorOs:
    def __init__(self):
        self.turn = 1

    def click(self, row, col):
        if self.turn is (1 or 3 or 5 or 7 or 9):
            canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)
            canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)
        else:
            canvas.create_oval(col * third + 5, row * third + 5, (col + 1) * third - 5, (row + 1) * third - 5)
            self.turn += 1

def mouse_click(c, event):
    col = int(event.x / third)
    row = int(event.y / third)
    c.click(row, col)

xo = XsorOs()
canvas.pack()
canvas.bind("<Button-1>", lambda event: mouse_click(xo, event))
canvas.mainloop()

EDIT:

*

*lambda is basically a way to create one line functions. In this case, I used it to pass arguments through the event function. Because somewhere internally tkinter does something like if that mouseclick happens do passed_function(event) so you have no chance to use your own arguments. That's why lambda is useful here

*__init__ is maybe not that important here since I saw people putting variables in class bodies before and apparently it works just fine, but I personally prefer it to create all the variables of a class in the constructor

*self is like this in other languages a reference to the class or the object of that class (you can actually name it the way you want by naming the first constructor argument, but self is commonly used). It "pulls" the variable in the scope of the class instead of the function. That means the variable exists and can be manipulated as long as the object exists. A function basically loses everything after execution. That was the main problem in your prior code.

A: I managed to fix it based off a few tweaks from your code. However, I could I make it that if a X is created, an O and X cannot be created on that same tile? Thanks for your help. This is what I have so far.
from tkinter import *

tk = Tk()
width = 600
third = width / 3
canvas = Canvas(width=width, height=width)
tk.title = "Tic Tac Toe"

line1 = canvas.create_line(200, 0, 200, 600)
line2 = canvas.create_line(400, 0, 400, 600)
line3 = canvas.create_line(0, 200, 600, 200)
line4 = canvas.create_line(0, 400, 600, 400)

class XsorOs:
    def __init__(self):
        self.turn = 0
        self.clicked = []

    def click(self, row, col):
        if (row, col) not in self.clicked
            if self.turn is 0:
                canvas.create_line(col * third, row * third, (col + 1) * third, (row + 1) * third)
                canvas.create_line((col + 1) * third, row * third, col * third, (row + 1) * third)
                self.turn += 1
            elif self.turn is 1:
                canvas.create_oval(col * third + 5, row * third + 5, (col + 1) * third - 5, (row + 1) * third - 5)
                self.turn -= 1
            else:
                print("Game Over")
            self.clicked.append((row, col))

def mouse_click(c, event):
    col = int(event.x / third)
    row = int(event.y / third)
    c.click(row, col)

xo = XsorOs()
canvas.pack()
canvas.bind("<Button-1>", lambda event: mouse_click(xo, event))
canvas.mainloop()

Also, if you have a reason to use the method you used that I was talking about in that comment, I would appreciate it if you would explain why.


text:
Q: classical decomposition method(without seasonal component) I understand the following points:
When decomposing, the trend is obtained from the data by a regression line.=> T
A cyclic component containing irregular variations is obtained(series/linear regression data)=> C*I
Smoothing is used to isolate the cyclic component.=>C
Getting an irregular component=(C*I)/C => I
Unclear: how to calculate a typical cyclic component.
Specifically, how to get intervals and observations for the calculation of " typical cyclic component".
In the example, the interval is three, and the observations in each interval are 6.
But, there is no description of how to get these numbers.
To make a prediction for the future I need to get a typical cyclic component


text:
Q: How to set the value of a default attribute of a Mongoose schema based on a condition I have this mongoose schema:
var UserSchema = new Schema({
    "name":String,
    "gender":String,
});

I want to add another field named image. This image will have a default value if gender is male and it will have another default value if gender is female. I found that the default value can be set with:
image: { type: ObjectId, default: "" }

But I do not find how can I set it with condition.

A: You can achieve this with the use of a document middleware.
The pre:save hook can be used to set a value on the document before it is saved:
var UserSchema = new Schema({
    "name":String,
    "gender":String,
});

UserSchema.pre('save', function(next) {
  if (this.gender === 'male') {
    this.image = 'Some value';
  } else {
    this.image = 'Other value';
  }

  next();
});

A: You can set the 'default' option to a function that tests for some condition. The return value of the function is then set as the default value when the object is first created. This is how it would look like.
image: {
    type: ObjectId,
    default: function() {
       if (this.gender === "male") {
          return male placeholder image;
       } else {
        return female placeholder image;
      }
    }
}

For the specific purpose of setting up a default placeholder image, I think using a link as the default value is a much simpler approach. This is how the schema would look like.
image: {
    type: String,
    default: function() {
       if (this.gender === "male") {
          return "male placeholder link";
       } else {
          return "female placeholder link";
       }
    }
 }

These are links to the placeholder images if someone might need them.
https://i.ibb.co/gSbgf9K/male-placeholder.jpg
https://i.ibb.co/dKx0vDS/woman-placeholder.jpg


text:
Q: Python bootstrap times out downloading eggs $ python bootstrap.py
Downloading http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Download error: [Errno 110] Connection timed out -- Some packages may not be found!

I am getting this error. What's odd is there is no problem getting to the file:
$ wget http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
--2012-07-11 05:49:52--  http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
Resolving pypi.python.org... 82.94.164.168
...
2012-07-11 05:49:58 (69.6 KB/s) - `setuptools-0.6c11-py2.6.egg' saved [333447/333447]

Also odd: there is an egg for different version of setuptools in ./eggs: setuptools-0.6c12dev_r88846-py2.6.egg
The log looks like this:
Downloading http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Creating directory '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/bin'.
Creating directory '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/parts'.
Creating directory '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/eggs'.
Creating directory '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/develop-eggs'.
Getting distribution for 'setuptools'.
Got setuptools 0.6c12dev-r88846.
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Generated script '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/bin/buildout'.
Download error: [Errno 110] Connection timed out -- Some packages may not be found!
Develop: '/opt/mytardis/releases/0351b5a804156c3d060c7042ad558e87616dee6d/.'

Any ideas? It's a Django app (not authored by me), which I'm trying to deploy through Vagrant and Chef. This step actually worked just a few hours ago (before I rebuilt the whole VM) so I'm a bit mystified what's changed. The buildout.cfg is here.
EDIT
A bit more info: it looks like the 'download error' is misleading, because the file actually does get downloaded to a temp directory (/tmp/tmpxxxx/). Running the buildout from the command line then immediately breaking shows this:
Downloading http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg
^CTraceback (most recent call last):
  File "bootstrap.py", line 172, in <module>
    ez['use_setuptools'](**setup_args)
  File "<string>", line 103, in use_setuptools
  File "<string>", line 99, in do_download
  File "/tmp/tmpkXNqcy/setuptools-0.6c11-py2.6.egg/setuptools/__init__.py", line 2, in <module>
  File "/tmp/tmpkXNqcy/setuptools-0.6c11-py2.6.egg/setuptools/extension.py", line 2, in <module>
  File "/tmp/tmpkXNqcy/setuptools-0.6c11-py2.6.egg/setuptools/dist.py", line 4, in <module>
  File "/tmp/tmpkXNqcy/setuptools-0.6c11-py2.6.egg/setuptools/depends.py", line 4, in <module>
  File "/usr/lib/python2.6/distutils/version.py", line 63, in <module>
    class StrictVersion (Version):
  File "/usr/lib/python2.6/distutils/version.py", line 101, in StrictVersion
    re.VERBOSE)
  File "/usr/lib/python2.6/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.6/re.py", line 243, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/usr/lib/python2.6/sre_compile.py", line 510, in compile
    code = _code(p, flags)
  File "/usr/lib/python2.6/sre_compile.py", line 495, in _code
    _compile(code, p.data, flags)
  File "/usr/lib/python2.6/sre_compile.py", line 96, in _compile
    _compile(code, av[2], flags)
  File "/usr/lib/python2.6/sre_compile.py", line 107, in _compile
    _compile(code, av[1], flags)
  File "/usr/lib/python2.6/sre_compile.py", line 107, in _compile
    _compile(code, av[1], flags)
  File "/usr/lib/python2.6/sre_compile.py", line 88, in _compile
    _compile(code, av[2], flags)
  File "/usr/lib/python2.6/sre_compile.py", line 63, in _compile
    _compile_charset(av, flags, code, fixup)
  File "/usr/lib/python2.6/sre_compile.py", line 203, in _compile_charset
    if flags & SRE_FLAG_LOCALE:
KeyboardInterrupt

A: More than one page is checked for possible downloadable targets. If one of those is down or generates an error you get to see this warning. But it's only a warning, you'll get a proper error if things really go south.
The warning is issued to let you know setuptools may have selected a different version of a package than it would otherwise have; it collects a list of versions for the package from pypi and pages linked from there, and one of those pages timing out could mean a "better" version was not selected this time.
In other words: don't worry, status-by-design.


text:
Q: Ubuntu 18.04 randomly logs out to black screen / second screen issue This issue appeared outta nowhere. I'm running Ubuntu 18.04 on a Dell Latitude 5591, and I noticed this after I disconnected my second monitor from my PC.
My PC started randomly shutting down (logging off, I get a black screen and I have to press the power button for it to run again, and it prompts me for my password) after every 30 seconds or less, the resolution went a bit wild and if I go to Displays inside Settings it says that it "Can't get screen information".
In addition every time I plug in the external display everything works on that external screen but not on the one on my laptop.
I tried most of the solutions that I could find online but nothing really helped.
Thanks for the help :)
xrandr (without the external display because I'm currently at home):

Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 16384 x 16384
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1920x1080     60.00*+  59.97    59.96    59.93    48.00
   1680x1050     59.95    59.88
   1600x1024     60.17
   1400x1050     59.98
   1600x900      59.99    59.94    59.95    59.82
   1280x1024     60.02
   1440x900      59.89
   1400x900      59.96    59.88
   1280x960      60.00
   1440x810      60.00    59.97
   1368x768      59.88    59.85
   1360x768      59.80    59.96
   1280x800      59.99    59.97    59.81    59.91
   1152x864      60.00
   1280x720      60.00    59.99    59.86    59.74
   1024x768      60.04    60.00
   960x720       60.00
   928x696       60.05
   896x672       60.01
   1024x576      59.95    59.96    59.90    59.82
   960x600       59.93    60.00
   960x540       59.96    59.99    59.63    59.82
   800x600       60.00    60.32    56.25
   840x525       60.01    59.88
   864x486       59.92    59.57
   800x512       60.17
   700x525       59.98
   800x450       59.95    59.82
   640x512       60.02
   720x450       59.89
   700x450       59.96    59.88
   640x480       60.00    59.94
   720x405       59.51    58.99
   684x384       59.88    59.85
   680x384       59.80    59.96
   640x400       59.88    59.98
   576x432       60.06
   640x360       59.86    59.83    59.84    59.32
   512x384       60.00
   512x288       60.00    59.92
   480x270       59.63    59.82
   400x300       60.32    56.34
   432x243       59.92    59.57
   320x240       60.05
   360x202       59.51    59.13
   320x180       59.84    59.32
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
HDMI-2 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
HDMI-3 disconnected (normal left inverted right x axis y axis)

If you want that I run any other commands to get logs or helpful information please let me know.