text:
Q: Working with xml child objects, ElementTree in Python I'm working with a program generated piece of xml that has terrible tagging. I was able to parse out what I am looking for but I don't think it is very pythonic. The goal of the program is to total the totalLines entries, among others. I'm using elementtree to extract the values.
Looking for suggestions on simplifying my syntax.
xml:
<?xml version="1.0"?>
<Status name="System Status">
<Bean name="SLMHandler" cn="com.open.eventCollector.OSLMHandler">
    <Status name="SLF File manager for SODLC2">
        <Prop name="totalLines">1105413065</Prop>
    </Status>
</Bean>

<Bean name="ThreadPool" cn="com.open.util.OThreadPoolBean">
    <Prop name="minThreads">5</Prop>
    <Prop name="maxThreads">25</Prop>
    <Prop name="checkedOutThreads">3</Prop>
    <Prop name="availableThreads">2</Prop>
    <Prop name="maxIdleTime">300000</Prop>
</Bean>

<Bean name="EventCollector" cn="com.open.eventCollector.OEventCollector">
    <Prop name="numUnmatchedLines">785319</Prop>

    <Status name="Adapters">

        <Status name="Logfile_EpilogWin_Generic">
            <Prop name="linesRead">0</Prop>
        </Status>
    </Status>
</Bean>

Python:
import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()

for bean in root.findall('Bean'):
    for status in bean.findall('Status'):
        if 'Adapters' in status.get('name'):
            for status2 in status.findall('Status'):
                for prop in status2.findall('Prop'):
                    if 'linesRead' in prop.get('name'):
                        print prop.text

A: Not sure how do you want your end result to be printed, but you may make it in one go with a single XPath expression:
for lines in root.findall('.//Bean/Status[@name="Adapters"]/Status/Prop[@name="linesRead"]'):
    print(lines.text)

Prints 0 for your sample data.


text:
Q: python error on barcode generation I am using python 2.7 and pyBarcode 0.7 in Windows and I am trying to generate barcode as png image by using following sample code (available in pyBarcode webpage)
>>> import barcode
>>> barcode.PROVIDED_BARCODES
[u'code39', u'ean', u'ean13', u'ean8', u'gs1', u'gtin', u'isbn', u'isbn10',
 u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
>>> EAN = barcode.get_barcode_class('ean13')
>>> EAN
<class 'barcode.ean.EuropeanArticleNumber13'>
>>> ean = EAN(u'5901234123457')
>>> ean
<barcode.ean.EuropeanArticleNumber13 object at 0x00BE98F0>
# Example with PNG
>>> from barcode.writer import ImageWriter
>>> ean = EAN(u'5901234123457', writer=ImageWriter())
>>> fullname = ean.save('ean13_barcode')

Last line generates following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python27\lib\site-packages\barcode\base.py", line 68, in save
    output = self.render(options)
  File "c:\python27\lib\site-packages\barcode\ean.py", line 106, in render
    return Barcode.render(self, options)
  File "c:\python27\lib\site-packages\barcode\base.py", line 103, in render
    raw = Barcode.raw = self.writer.render(code)
  File "c:\python27\lib\site-packages\barcode\writer.py", line 188, in render
    self._callbacks['paint_text'](xpos, ypos)
  File "c:\python27\lib\site-packages\barcode\writer.py", line 280, in _paint_te
xt
    font = ImageFont.truetype(FONT, self.font_size * 2)
  File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 218, in truetype
    return FreeTypeFont(filename, size, index, encoding)
  File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 134, in __init__
    self.font = core.getfont(file, size, index, encoding)
  File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 34, in __getattr__

    raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed

I retried by installing Pillow (but before that I removed PIL); I downloaded "Pillow-4.2.1-win32-py2_7.exe"
and I did also "pip install Pillow".
Now when I try to run
import barcode

I got:
  File "barcode\codex.py", line 12, in <module>

    from barcode.base import Barcode

  File "barcode\base.py", line 9, in <module>

    from barcode.writer import SVGWriter

  File "barcode\writer.py", line 12, in <module>

    import Image, ImageDraw, ImageFont

  File "c:\python27\lib\site-packages\PIL\Image.py", line 27, in <module>

    from . import VERSION, PILLOW_VERSION, _plugins

ValueError: Attempted relative import in non-package

What should I do ?
thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I correctly format a target time for a countdown? Right now I'm trying to enter a time in 24 hour format and initiate a countdown from the current time to the specified time.
So currently the user is entering a target hour and a target minute. I'm not sure what to do with these values to begin a countdown from now until the specified time.
import datetime

now = datetime.datetime.now() # gets the time now, puts it in now

expiringHour = int(input("What hour does the meter expire? Enter 0-23 "))

if expiringHour < 0:
    print("Error. Enter a correct value")
if expiringHour > 23:
    print("Error. Enter a correct value")

expiringMinute = int(input("What minute does the meter expire? Enter 0-59 "))

if expiringMinute < 0:
    print("Error. Enter a correct value")
if expiringMinute > 59:
    print("Error. Enter a correct value")

print(expiringHour, expiringMinute)

A: Well, you convert the values to a datetime, and then eneter a loop where display the remaining time from now to the expiring minute, and then sleep for a while, and then display it again, until it reaches zero.

A: Actually, the correct answer to this involves creating a datetime.datetime object and incrementing the datetime.datetime object till we reach the finish time.
But since you said you wanted a GUI, I had used python wrapper over xdaliclock on Ubuntu to have a countdown timer. Yeah, this is not applicable if you are on a system where xdaliclock is not available.


text:
Q: How can I calc the density from 2D density gradient field; Schlieren exp; integrate total differential; scalar potential from gradient vector field; I did Schlieren experiments with vertical and horizontal cutoff direction.
Now I have the density gradient in both horizontal and vertical direction stored in matrices (I have a value for every pixel in my [m,n] image). The density gradient is a vector and the density is a scalar, so I have a gradient vector field of a scalar potential (=density).
$$\overrightarrow {\nabla \rho} = \frac{\partial\rho}{\partial x} \cdot \overrightarrow{i} + \frac{\partial \rho}{\partial y} \cdot \overrightarrow{j}$$
the total differential reads:
$$d \rho = \frac{\partial\rho}{\partial x} \cdot dx + \frac{\partial\rho}{\partial y} \cdot dy$$
with dx and dy being the size of the pixels in the image $dpix=dx=dy$.
Now I integrate this total differential to get the actual density.
I followed and applied the procedure of partial integration of a total differential here, which I found here.
I integrate one time in x and y separately and add a function which only depends on y and x respectively.
I implemented it like that in Matlab:
$$ \Delta \rho(x,y) = \int_0^{L_x} \frac{\partial\rho}{\partial x} \,dx + \Psi(y) = \Delta \rho_x + \Psi(y) \\
\Delta \rho(x,y) = \int_0^{L_y} \frac{\partial\rho}{\partial y} \,dy + \Phi(x) = \Delta \rho_y + \Phi(x)
$$
I evaluate the integrals numerically, using the cumtrapz() function in matlab:
$$
\Delta \rho_x = \int_0^{L_x} \frac{\partial\rho}{\partial x} \,dx \approx cumtrapz(dpix, \frac{\partial\rho}{\partial x}, 2) \\
\Delta \rho_y = \int_0^{L_y} \frac{\partial\rho}{\partial y} \,dy \approx cumtrapz(dpix, \frac{\partial\rho}{\partial y}, 1)
$$
where the 1  stays for direction of integration along y - the columns of the matrix and 2 stays for direction of integration along x - the rows of the matrix.
Then, to find the functions $\Psi(y)$ and $\Phi(x)$, presupposed that $\frac{\partial (\Delta \rho(x,y))}{\partial y} = \frac{\partial \rho}{\partial y} $ and $\frac{\partial (\Delta \rho(x,y))}{\partial x} = \frac{\partial \rho}{\partial x} $, which are my known partial derivatives:
$$ \frac{\partial}{\partial y}\Psi(y) = \frac{\partial}{\partial y} [\Delta \rho(x,y) - \Delta \rho_x] \\
\Psi(y) = \int_0^{L_y} (\frac{\partial\rho}{\partial y} -  \frac{\partial (\Delta \rho_x)}{\partial y} \,dy $$
and idem for
$$ \Phi(x) = \int_0^{L_x} (\frac{\partial\rho}{\partial x} -  \frac{\partial (\Delta \rho_y)}{\partial x} \,dx$$
This makes sense somehow as it accounts for $\frac{\partial (\Delta \rho_x)}{\partial y}$ and $\frac{\partial (\Delta \rho_y)}{\partial x}$.
So finally
$$ \Delta \rho(x,y) = \Delta \rho_x + \Psi(y)  = \Delta \rho_y + \Phi(x)  $$
and
$$ \rho(x,y) = \rho_{ambient} + \Delta \rho(x,y) $$
Though, applying this procedure to my numerical data, the results given by $\Delta \rho_x + \Psi(y)$ and $\Delta \rho_y + \Phi(x)$ are not the same.
I am wondering if there exists another mathematical procedure/function (like the gradient theorem e.g.) to calculate the scalar potential out of a gradient vector field, robustly applicable also to numeric data.
(There exists a Matlab function on this purpose called potential(), but it works only with symbolic variables)


text:
Q: Build management in C++ & good IDEs on Linux I am starting to write a moderately sized project in C++ requiring a fairly large amount of files and dependencies on other projects.
Do you think manually maintaining a Makefile for this project is the best approach?
Are there other better alternatives for C++ that make build management and dependency management of files really easy to handle?
Also, what IDE is good for C++ development on Linux? I am comfortable with Vim, but do you think there are good IDEs for C++ (like Eclipse for Java) that provide code-completion etc?
Thanks!
Ajay

A: Others have already recommended using CMake.  To my mind you should manage your project with CMake then decide on your favourite IDE.
CMake allows you to describe the project to be built, instead of how to build it.  For example: I want to create a shared library called foo with source files a.cpp, b.cpp and c.h and it requires these link dependencies.  Then on unix you get libfoo.so and on windows you get foo.dll and foo.lib.  All common project settings can be abstracted up to higher levels in the build tree, this keeps most files very simple.  More complicated requirments can be refactored into macros.
Once your project is described like this CMake will generate makefiles and/or IDE projects.  This means each developer can choose their own IDE, as well as allowing you to mandate an IDE if appropriate.
My company use CMake to build the c++ in our product on windows and solaris.  It contains 600 projects and 1.5 million lines of source code.  We originally chose it as a cross platform build utility when porting to solaris, however for a large project like ours it is much easier to manage the build with CMake than with Visual Studio project files.  I would recommend it as a build utility for any c++ project of any size
We use the eclipse cdt on solaris and are very happy with it.  Most of our development is with visual studio on windows.  cmake also works well with other ides I use it with KDeveloper4 on linux at home without a hitch.

A: KDevelop4 (from subversion or rc1 from their site) + CMake makes life so much easier, automake should just die.
If you want a cross-platform solution, netbeans + the c++ plugin are pretty decent, not as good as kdevelop4 though.

A: I suggest you Code::Blocks. I use it on Debian and works gracefully.
http://www.codeblocks.org/
Edit: Added another link
http://wiki.codeblocks.org/index.php?title=The_build_process_of_Code::Blocks

A: I like CMake a lot for the whole building process (but I have almost no experience with scons or Jam).
I use vim or qtcreator. Qtcreator is still in developpment, but very promising I think.

A: Eclipse does C++ as well - through eclipse CDT - not as comprehensive as Java but pretty good.

A: Manually maintaining Makefiles in larger Projects becomes quite painful. If you start using automake/autoconf, you will - after a while of learning all the facets - appreciate the powerful possibilities these tools can offer.
And as IDE simply use Emacs. It's quick, powerful and supports Code completion etc.

A: There's also Code::Blocks as an IDE with its own building system. But I would encourage you to try out other build tools (CMake, Boost.Build, SCons) if you want to be able to build your software "anywhere" without having a fancy schmancy IDE installed. ;-)

A: I found Emacs + Scons works pretty well for me.


text:
Q: Wordpress custom category page not loading javasctipt files and giving 404 error I have started from scratch to develop a theme, now i have a code snippet from one websites where in he is using the script like -
<script>
        head.js(
            { jquery : "js/jquery.min.js" },
            { mousewheel : "js/jquery.mousewheel.js" },
            { mwheelIntent : "js/mwheelIntent.js" },
            { jScrollPane : "js/jquery.jscrollpane.min.js" },
            { history : "js/jquery.history.js" },
            { stringLib : "js/core.string.js" },
            { easing : "js/jquery.easing.1.3.js" },
            { smartresize : "js/jquery.smartresize.js" },
            { page : "js/jquery.page.js" }
        );
</script>

Now i when i try this in my category-{slug}.php it searches these files in the folder wordpress/category/{slug}/
Now i also tried here `
<script>
        head.js(
            { jquery : "<?php bloginfo('template_url')?>/js/jquery.min.js" },
            { mousewheel : "<?php bloginfo('template_url')?>/js/jquery.mousewheel.js" },
            { mwheelIntent : "<?php bloginfo('template_url')?>/js/mwheelIntent.js" },
            { jScrollPane : "<?php bloginfo('template_url')?>/js/jquery.jscrollpane.min.js" },
            { history : "<?php bloginfo('template_url')?>/js/jquery.history.js" },
            { stringLib : "<?php bloginfo('template_url')?>/js/core.string.js" },
            { easing : "js/jquery.easing.1.3.js" },
            { smartresize : "<?php bloginfo('template_url')?>/js/jquery.smartresize.js" },
            { page : "<?php bloginfo('template_url')?>/js/jquery.page.js" }
        );`
</script>

Then also i get a 404 error in firebug but when i try something like this -
{jquery : "../../wp-content/themes/testing/js/literature"},

It works, Now i wanted to know that why it is looking these dependancies in the folder category rather than my theme directory whereas at the same time if i wrote these lines
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/literature/head.min.js"></script>

in my head section and to my surprise they work, can anyone tell me what is going on here

A: Accordingly to your code, you're using a script called head.js, which allows you to add more scripts to your header. If you truly want to use head.js, you have to add that script in your head manually. I discourage using what you don't really need.
Put this PHP code in your functions.php file, which should be located in your theme directory. If not, create it. This is how you usually include scripts to your theme.
add_action('wp_enqueue_scripts', 'mytheme_enqueue_scripts');

function mytheme_enqueue_scripts() {
    // jQuery comes with WordPress, no need to include it

    $dir = get_stylesheet_directory_uri() . '/js';

    // Vanilla scripts
    wp_enqueue_scripts('stringLib',     $dir . '/core.string.js');

    // All these guys depend on jQuery, hence the "array('jquery')"
    wp_enqueue_scripts('easing',        $dir . '/jquery.easing.1.3.js',         array('jquery'));
    wp_enqueue_scripts('easing',        $dir . '/jquery.smartresize.js',        array('jquery'));
    wp_enqueue_scripts('easing',        $dir . '/jquery.page.js',               array('jquery'));
    wp_enqueue_scripts('history',       $dir . '/jquery.history.js',            array('jquery'));
    wp_enqueue_scripts('mousewheel',    $dir . '/jquery.mousewheel.js',         array('jquery'));
    wp_enqueue_scripts('mwheelintent',  $dir . '/jquery.easing.1.3.js',         array('jquery'));
    wp_enqueue_scripts('mwheelintent',  $dir . '/mwheelIntent.js',              array('jquery'));
    wp_enqueue_scripts('jscrollpane',   $dir . '/jquery.jscrollpane.min.js',    array('jquery'));

    // This one happens to rely on jScrollPane
    wp_enqueue_scripts('mwheelintent',  $dir . '/mwheelIntent.js',              array('jscrollpane'));
}

PS. Don't forget that PHP code always starts with <?php

A: Is wp-blog-header.php loaded before you load category-{slug}.php?


text:
Q: In SwiftUI Picker expands to occupy entire space inside a HStack I have a Text and Picker in HStack separated by Spacer. What I want is that the Spacer should should occupy maximum space between picker and text so that the Text and Picker are not the extreme ends of the HStack but, the picker expands to occupy maximum space. Any clue as to how can this can achieved and that the size of Picker is equivalent to its content?
HStack() {
                Text(template.name)
                    .multilineTextAlignment(.leading)
                Spacer()
                if template.oneItemOnly == "1" {
                    if let items = template.items {
                        Picker(selection: $selectedSegment, label:Text("")){
                            ForEach( 0..<items.count) { index in
                                Text(items[index].name)
                                    .tag(index)
                            }
                        }
                        .pickerStyle(SegmentedPickerStyle())
                    }
                }
            }

A: You can set max width of Spacer by adding a .frame modifier:
Spacer().frame(maxWidth: .infinity)

Alternatively you can try using GeometryReader to set the width of the Picker relative to the screen width:
GeometryReader { proxy in
    ...
    Picker(selection: $selectedSegment, label: EmptyView()) {
        ...
    }
    .frame(width: proxy.size.width / 3)
}

You may also try to implement your own Picker like presented here: Custom Segmented Picker


text:
Q: How to modify iOS App Icon with fastlane action?
I use the Fastlane action to upload the app to TestFlight, and I want to modify the app icon. In Xcode, this "Asset Catalog App Icon Set Name" option in the Build Settings of Targets can modify the app icon, but I can't find the action of Fastlane to modify the app icon, and I used the two actions of badge and app_icon below but it didn't work.
the Fastlane file as below:
lane :beta do |values|
badge(custom: './Assets.xcassets/AppIconBeta.appiconset/IconBeta-1024.png')
#badge(path: './Assets.xcassets/AppIconBeta.appiconset/IconBeta-1024.png')
#app_icon('./Assets.xcassets/AppIconBeta.appiconset/IconBeta-1024.png')

match(type: 'appstore',readonly: false,app_identifier:'com.health-beta',force_for_new_devices: false,force: true)
gym(scheme: 'Health - PROD', export_method: 'app-store')
pilot
end

A: In Fastlane script you can explicitly add a badge and some additional changes to your icon using badge https://docs.fastlane.tools/actions/badge/
badge(custom: <badge path>)


text:
Q: Php code that explodes tags from a form, puts commas after each one and breaks them in groups I have a form where I want to submit tags like this:
tag1
tag2
tag3
tag4
...
tag n

*each tag on it's own line.
I get the tags in my php page:
$tags = get_option('tags');

I now separate each tag by the new line criteria:
$tag = explode("\n", $tags);

In a loop, I echo them:
$i = '-1';
while(){ // usually a wordpress loop
    $i++;
    echo $tag[$i];
}

Finally I get:
Tag1
Tag2
Tag3
...
Tag n

Here is where I need help.

*

*I can't find a way to group tags - lets say by 3 and not explode them with every new line - "\n"
That would enable me to get something like this:

***Automatically put a comma after each tag in each line, except the last one.
It would be something like this:
Tag1, Tag2
Tag3, Tag4
....
Tag n-1, Tag n

Any ideas?
Ty!

A: EDIT: Sorry I didn't quite understand your question the first time. This code below should display 3 tags on each own line.
$totalTags = count($tag);
for ($i = 0; $i < $totalTags; $i += 3)
{
    $tagsLine = array($tag[$i]);
    isset($tag[$i + 1]) ? array_push($tagsLine, $tag[$i + 1]) : FALSE;
    isset($tag[$i + 2]) ? array_push($tagsLine, $tag[$i + 2]) : FALSE;
    echo implode(',', $tagsLine), '<br />';
}

So basically, you'll first need to count how many tags exist in the array and then do a for loop and at the end of the loop you use implode to "glue" 3 tags together. In case you're wondering, the two lines above the echo is to push a new element to a temporary array that will be "imploded" together. The temporary array will always contain one tag. That is, the first one on each line.

A: You can group them on the fly.
Here's an example with using the code you provided
$tag = explode("\n", $tags);
$i = '-1';
$tags_in_group = 2;
while(){ // usually a wordpress loop
    $i++;
    echo $tag[$i] . !(($i + 1) % $tags_in_group) ? "\n" : ', ';
}

A: Use the Modulus (%) operator to do a different operation every 3 items. WChange your while loop to something like:
$i=0;
while(){ // usually a wordpress loop
    if(($i+1)%3!=0) {
        echo $tag[$i] . ",";
    }
    else {
        echo $tag[i] . "\n";
    }
    $i++;
}

A: I would keep the explode, but within the loop you can one of two things.
This will display and then increment the variable. Adding in the necessary punctuation as it is displayed.
$i = 0;// I normally start at 0 to allow increments at the end of the loop
while(){// usually a wordpress loop
    echo $tag[$i++] . ", " $tag[$i++] . "\n";
}

or the below code will check the modulus of the current value and determine weather to display a comma or a line feed.
$i = 0;// I normally start at 0 to allow increments at the end of the loop
while(){// usually a wordpress loop
 echo $tag[$i] . ($i%2==0 ? "\n" : ", ");
$i++
//or the more readable approach
   if ($i%2==0){
      echo $tag[$i++] . "\n";
   }
   else{
    echo $tag[$i++] . ", ";
   }
}


text:
Q: Disable Virtual KeyBoard in Android Device I am having an web app which is developed by bootstrap with C#. They will be using this application in the scanner device which got android 10 OS. I want to disable the virtual keyboard popup on the textbox as this device already have the physical keyboard. I tried using the javascript it doesn't work.
>         document.onkeydown = function (e) {
>             return false;


text:
Q: Why MySQL do this: mysql.connector.errors.InterfaceError: No result set to fetch from? I have this error when I use a SELECT sentence: mysql.connector.errors.InterfaceError: No result set to fetch from
My code is:
import mysql.connector as connector

def connect():
    return connector.connect(user="los_manueles", password="", host="localhost",
                             database="sem_2")

def insert_course(name, teacher):
    connection = connect()

    connection.cursor().execute("INSERT INTO course(name, teacher) VALUES (%s, %s)",
                                (name, teacher))
    connection.commit()
    connection.close()

def get_courses():
    connection = connect()
    connection.cursor().execute("SELECT * FROM course")
    courses = connection.cursor().fetchall()
    connection.close()

    return courses

def delete_course(id):
    connection = connect()
    connection.cursor().execute("DELETE FROM course WHERE id = %s", (id,))
    connection.commit()
    connection.close()

def get_course(id):
    connection = connect()
    connection.cursor().execute("SELECT * FROM course WHERE id = %s", (id,))
    course = connection.cursor().fetchone()
    connection.close()

    return course

def update_course(id, name, teacher):
    connection = connect()
    connection.cursor().execute("UPDATE course SET name = %s, teacher = %s WHERE id = %s",
                                (name, teacher, id))
    connection.commit()
    connection.close()

I tried buffered = True, but did not found.
The database is connected correctly since all the functions are working, except those that use SELECT sql statements.


text:
Q: to match the data from database this error is come This code give the error dbpassword variable cannot resolve
   loginbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            // get the user details email or password
            String useremail = emailornumber.getText().toString();
            String password = userpassword.getText().toString();

            //fetch the password from the database
            String storedPassword = databaseAdapter.getUserInfo(dbpassword);

            // check if password is match
            if(userpassword.equals(dbpassword)){
                Toast.makeText(LoginActivity.this, "You are Login", Toast.LENGTH_LONG).show();
                Intent in = new Intent(LoginActivity.this, MainActivity.class);
            }
            else
            {
                Toast.makeText(LoginActivity.this, "Username and Password Does not match", Toast.LENGTH_LONG).show();
            }
        }
    });

DatabaseAdater
  public Cursor getUserInfo(String dbpassword)
               {

             Cursor mCursor =
                     db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                     KEY_FULLNAME, KEY_EMAILID}, KEY_PASSWORD + "=" +  dbpassword , null,
                     null, null, null, null);
                     if (mCursor != null) {
                     mCursor.moveToNext();
                     }
                     return mCursor;
                     }

A: I think the error is located here:
String storedPassword = databaseAdapter.getUserInfo(dbpassword);
Your method getUserInfo returns a Cursor, not a String.


text:
Q: How to evaluate $ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3......+x^n} ; n> 1$ I have found like ;
1.$ \int_{0}^{\infty} \frac{dx}{1+x+x^2} = \frac{2\pi}{3\sqrt3}$
2.$ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3} = \frac{\pi}{4}$
3.$ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3+x^4} = \frac{\pi}{5} \cdot \sqrt{2-\frac{2}{\sqrt5}}$
4.$ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3+x^4+x^5} = \frac{2\pi}{6\sqrt3}$
5.$ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3+x^4+x^5+x^6+x^7} = \frac{2\pi}{8\sqrt3}$
In that way i'm trying to find $ \int_{0}^{\infty} \frac{dx}{1+x+x^2+x^3......+x^n} ; n> 1;$ But get stuck , can anyone help me by showing the process how to evaluate it .

A: Note  that $\sum_{0 \le k \le n} x^k = \frac{1 - x^{n +1}}{1 - x}$. The numerator of this can be factored into linear (complex) factors, partial fractions should take care of your general integral.


text:
Q: Firebase: Listening for like changes of a Tree Lets say I have a query of a list of Objects
-Tree
  -obj1
    -msg: Hi
    -comments: 2
  -obj2
    -msg: Hey
    -comments: 3

Lets say I initially pull down obj1 and obj2. And later on I query again, and obj1 and obj2 both have a different comment count
Is there a way to only pull down the data changes rather than the entire object? This is a minimal example but I would likely have more information in it as well.
Or is this motivation to build everything in trees as flat as possible to minimize data transfer?
I noticed in Cloud Firestore you could query just for changes, but it is in beta so I am trying to avoid using it
Any ideas? Basically I am asking how to query for changes from my last query

A: The Firebase Realtime Database always reads and exposes complete nodes to your listeners.
That means that in your example you can listen for /Tree/obj1/comments to get only notified if the comment count for obj1 changes. But you cannot listen for updates to the comment counts across all objects with a single listener.
If you only want to read comment counts across all objects, you should indeed store a list of comment counts.


text:
Q: Is it possible to change the font size of a UINavigationBar In my application, I don't really have much space in the NavigationBar. Is it possible to change the font size of the text? I saw an answer, but this doesn't work in swift 4.

A: Yes, Possible
As you asked in Swift 4
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica", size: 23)!]

Output:

A: What's about using, this works only with iOS 11
navigationController.navigationBar.prefersLargeTitles = true


text:
Q: Unecessary part of the graph showing in matplotlib I made a simple simulator of stock prices where the price is determined by the number of buyers and sellers. For example, if there are 30 buyers and 10 sellers, 30/40 = 0,75 and 10/40 = 0,25, then the current price will increase by itself times 0,5 (0,75-0,25), that is, decrease by itself times (-0,5) if there are 10 buyers and 30 sellers.
I made it a live graph where you input the number of buyers, sellers and the number on x-axis (b, s, y) in a notepad and the graph updates itself.
Here is the code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    graph_data = open('inputs.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

prices = [30]

for line in lines:
    if len(line) > 1:
        b, s, y = line.split(',')
        b = int(b)
        s = int(s)
        def price():
            x = prices[-1]
            pr = b / (b + s) - s / (b + s)
            global result
            result = x + x * pr
            return result

    price()
    prices.append(result)
    xs.append(y)
    ys.append(result)
    ax1.clear()
    ax1.plot(xs, ys)
    ax1.grid(True)

ani = animation.FuncAnimation(fig, animate, interval=1000)

plt.show()

And this is the problem I get:

The new price is correct and is accurately charted, but then there is an additional part of the graph in a form of a straight line, which only keeps growing as I input new numbers (if the price is falling, the straight line is going down) and decreases the size of my main graph.
I don't know what I need to change in my code for that line not to show, or how i could remove it. I would really appreciate the answer.


text:
Q: How to create a layer to invert a softmax (TensforFlow,python)? I am building a deconvolution network. I would like to add a layer to it which is the reverse of a softmax. I tried to write a basic python function that returns the inverse of a softmax for a given matrix and put that in a tensorflow Lambda and add it to my model.
I have no error but when I doing a predict I only have 0 at the exit. When I don't add this layer to my network I have output something other than zeros. This therefore justifies that they are due to my inv_softmax function which is bad.
Can you enlighten me how to proceed?
I define my funct as this :
def inv_softmax(x):
   C=0
   S = np.zeros((1,1,10)) #(1,1,10) is the shape of the datas that my layer will receive
   try:
      for j in range(np.max(np.shape(x))):
         C+=np.exp(x[0,0,j])
      for i in range(np.max(np.shape(x))):
         S[0,0,i] = np.log(x[0,0,i]+C
   except ValueError:
      print("ValueError in inv_softmax")
      pass
   S = tf.convert_to_tensor(S,dtype=tf.float32)
   return S

I add it to my network as :
x = ...
x = layers.Lambda(lambda x : inv_softmax(x),name='inv_softmax',output_shape=[1,1,10])(x)
x = ...

If you need more of my code or others informations ask me please.

A: Try this:
import tensorflow as tf

def inv_softmax(x, C):
   return tf.math.log(x) + C

import math
input = tf.keras.layers.Input(shape=(1,10))
x = tf.keras.layers.Lambda(lambda x : inv_softmax(x, math.log(10.)),name='inv_softmax')(input)
model = tf.keras.Model(inputs=input, outputs=x)

a = tf.zeros([1, 1, 10])
a = tf.nn.softmax(a)
a = model(a)
print(a.numpy())

A: Thanks it works !
I put :
import keras.backend as K

def inv_softmax(x,C):
   return K.log(x)+K.log(C)


text:
Q: QGIS Load Multiple styles on single layer at once I have a set of qml style files saved that I apply to similar layers across multiple projects.   An example would be a linetype shapefile layer with about a dozen different styles; currently I have to repeat the process of adding a new style and loading the qml file for each of the different styles.  Then I have to do it a few more times in that project and repeat the whole thing again in the next project.
Just trying to see if there's a way to load multiple style files on the same layer at once?  Something like instead of browsing to a single qml, I could multi-select several qml files and load them at once?

A: You can load multiple styles using pyqgis script (explanations in comments):
import os
from qgis.core import QgsMapLayerStyle
from qgis.utils import iface

# set path to your styles here
qml_path = '/home/user/qml'

layer = iface.activeLayer()
style_manager = layer.styleManager()

# read valid style from layer
style = QgsMapLayerStyle()
style.readFromLayer(layer)

for qml_file in [f for f in os.listdir(qml_path)
                 if os.path.isfile(os.path.join(qml_path, f)) and
                 f.endswith('.qml')]:
    # get style name from file
    style_name = os.path.basename(qml_file).strip('.qml')
    # add style with new name
    style_manager.addStyle(style_name, style)
    # set new style as current
    style_manager.setCurrentStyle(style_name)
    # load qml to current style
    (message, success) = layer.loadNamedStyle(os.path.join(qml_path, qml_file))
    print message
    if not success:  # if style not loaded remove it
        style_manager.removeStyle(style_name)

You can run it in the QGIS python console or adapt to a processing script.
(Tested on current LTR version QGIS 2.18)

A: In case someone comes across this from post - 2023 and using 3.28.2 Firenze and above, the QGIS Dev guru's have implemented a Save Mulitple Stlyes to QML.
Feature Request description on Github

An Example process:

*

*Right Click> Add Style: rename to something sensible

*Modify your symbology (this auto-saves)

*Repeat for all styles

*Once happy with all your stlyes. Open Symbology from your layer. Click 'Style'>Save Multiple Styles

*In your next project, Load Styles> Navigate to your .qml file.

*Open and Enjoy.

A: If I am understaning you correctly you just want to be able to apply geometry styles and not necessarily rules or expressions to layers quickly and easily in any project you have open?
If that is the case you could just save your styles in the symbol library using the style manager? Open up the layer style panel and click the "open library" button.


text:
Q: How to hide command prompt in C How can I hide the command prompt that always pops up in my C app?
From a simple ("Hello world") type of view if you don't mind.
And I wanna do it in the app I run, not from the point of view of running another app without prompt.
Thanks.

A: Make it a win-32 application instead of console but don't draw a window.


text:
Q: Android sqlite helper error while getting data back Hi all im using a sqlite helper class, but i have a little problem using a select statement.
I want to get the id of a datebase item by its name.
I use this select method:
public Cursor selectShift (String name){
    SQLiteDatabase db = dbHandler.getReadableDatabase();
    Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
    c.moveToFirst();
    db.close();
    return c;
}

And when i call this i use this:
if(handler.selectShift(name)!=null){
      Cursor c = handler.selectShift(name);
      id = c.getInt(c.getColumnIndex("_id"));
      c.close();
  }

And then is get this error:

android.database.CursorIndexOutOfBoundsException: Index 0 requested,
  with a size of 0

As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.
Can someone help me how to fix this?

A: 1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......
if(handler.selectShift(name)!=null){
      Cursor c = handler.selectShift(name);

if (c.moveToFirst()){ //<--------------
   do{  //<---------if you not need the loop you can remove that
       id = c.getInt(c.getColumnIndex("_id"));
   }while(cursor.moveToNext());
}

  c.close();

}
2- not sure but looks in select query as '<variable>' are not there in where clause with variable
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";

or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});

A: The issue appears to be here
"name="  <-It should be "name = "+name

Following should work
Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name},  null, null, null);

A: Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation.  Maybe something like this
Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);

A: Thanks for your help, i found the problem. It was in the cursor method, the solution is:
public Cursor selectShift (String name){
    SQLiteDatabase db = dbHandler.getReadableDatabase();
    Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
    c.moveToFirst();
    db.close();
    return c;
}


text:
Q: Scaling in d3js If I have a set of data numbers that are percentages ranging from -0.75 to 0.3, and I want to create a heat map where -0.75 are "bright red" tiles and .3 values are "bright green values" and everything in between is scaled between that.
I currently have this:
js
var color = d3.scale.quantize()
.domain([-.7, .3])
.range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));

css
.RdYlGn .q0-11{fill:rgb(255,0,0)}
.RdYlGn .q1-11{fill:rgb(255,50,50)}
.RdYlGn .q2-11{fill:rgb(255,100,100)}
.RdYlGn .q3-11{fill:rgb(255,150,150)}
.RdYlGn .q4-11{fill:rgb(255,200,200)}
.RdYlGn .q5-11{fill:rgb(255,255,255)}
.RdYlGn .q6-11{fill:rgb(200,255,200)}
.RdYlGn .q7-11{fill:rgb(150,255,150)}
.RdYlGn .q8-11{fill:rgb(100,255,100)}
.RdYlGn .q9-11{fill:rgb(50,255,50)}
.RdYlGn .q10-11{fill:rgb(0,255,0)}

But the numbers don't seem to scale right.  The percentages seem to be scaled like so:
.3 = q0  Green
.0 = q2
-.1 = q4
-.5 = q5  White
-.7 = q11 Red

It makes sense that -.5 is my middle value of white, because that is the median of .3 and -.7, but I don't want it to be that.  Any help?

A: Fortunately there is a very simple way to accomplish what you want. Just use a polylinear scale, which is just a regular d3.scale.linear() with anchor points at each value where a new color should start.
To have red for negative values, white at zero, and green for positive, use:
polylinear_color = d3.scale.linear()
    .domain([-0.3, 0, 0.7])
    .range(['rgb(255,0,0)','rgb(255,255,255)','rgb(0,255,0)'])

The scale does all the interpolation and instead of using classes you just set .attr('fill',function(d){return polylinear_color(d);}); on the things being colored.
I made a jsfiddle to illustrate, here.

A: Take a look at d3's built in color interpolators here
In your case it would look something like this:
var interpolator = d3.interpolateHsl('rgb(255,0,0)', 'rgb(0,255,0)');
var scale = d3.scale.linear()
  .domain([-.7, .3])
  .range([0, 1])
// interpolator(scale(0)) will return a color in between red and green


text:
Q: URL rewrite in .htaccess Symfony I'm using Symfony. I have the following files.

*

*/var/www/cheok/web/.htaccess

*/var/www/cheok/web/index.html
My original .htaccess content is
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

I wish, when user provide URL
http://myserver.com/123/456

the URL will be rewrite to
http://myserver.com/index.html#123/456

Hence, I modify the original .htaccess to the following
DirectoryIndex app.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^([0-9]+)/([0-9]+)$ /index.html#$1/$2 [R=301,NC,L,NE]

    ...

*

*R=301 flag tells change the displayed URL at browser.

*NE flag tells mod_rewrite not to encode the URI.

However, it doesn't work as expected. URL rewrite doesn't work
http://myserver.com/123/456 - The server returned a "404 Not Found".
http://myserver.com/index.html#123/456 - (Works fine still)
Is there anything I can try out, to figure out why the URL rewrite doesn't work?
Note, it once work without using Symfony.
hashtag in apache .htaccess
Also, in my /etc/httpd/conf/httpd.conf, it looks like... I'm not sure whether it matters.
<VirtualHost *:80>
    ServerName myserver.com
    #ServerAlias domain.com.localhost
    #ServerAdmin webmaster@localhost
    #ServerPath /api/
    DocumentRoot /var/www/cheok/web
    <Directory /var/www/cheok/web/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ /app.php [QSA,L]
        </IfModule>
    </Directory>
</VirtualHost>

A: Since you're forwarding everything to app.php in Apache config you need to add this 301 rule there itself:
<Directory /var/www/cheok/web/>
    Options +Indexes +FollowSymLinks -MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
    <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteRule ^/?([0-9]+)/([0-9]+)/?$ /index.html#$1/$2 [R=301,L,NE]

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ /app.php [L]
    </IfModule>
</Directory>


text:
Q: Halide Error: Input buffer b0 is accessed at -1, which is before the min (0) in dimension 0 - sobel edge detector I'm trying to develop a sobel edge detector using Halide.
Because I need to compute the 3x3 square around each pixel, I'm trying to realize the function over a smaller rectangle (and avoid the outer border). Here's what I came up with so far:
Buffer<uint8_t> image;
//Read image into buffer (omitted)
gamma(x, y, c) = cast<uint8_t>(255 * pow(image(x, y, c) * 1.0f / 255, gamma_exponent)); //Gamma correction
//Sobel edge detector
h(x, y, c) = gamma(x + 1, y - 1, c) + 2 * gamma(x + 1, y, c) +
             gamma(x + 1, y + 1, c) - gamma(x - 1, y - 1, c) -
             2 * gamma(x - 1, y, c) - gamma(x - 1, y + 1, c);
v(x, y, c) = -gamma(x - 1, y + 1, c) - 2 * gamma(x, y + 1, c) -
             gamma(x + 1, y + 1, c) + gamma(x - 1, y - 1, c) +
             2 * gamma(x, y - 1, c) + gamma(x + 1, y - 1, c);
sobel_ed(x, y, c) = (h(x, y, c) + v(x, y, c)) / 4;
sobel_bounded(x, y, c) = BoundaryConditions::constant_exterior(sobel_ed, 0, 2, image.width() - 4, 2, image.height() - 4)(x, y, c);
Buffer<uint8_t> tmp(image.width() - 4, image.height() - 4, image.channels());
tmp.set_min(2, 2, 0);
sobel_bounded.realize(tmp);

When I run this code, I get the following error:

Error: Input buffer b0 is accessed at -1, which is before the min (0) in dimension 0

It seems like Halide evaluates the statement for every value of x and y, even though I set boundary conditions.
What can I do?


text:
Q: How can I move a gameobject to where the screen was touched? I've tried this UNITY touch position to world position 2D and this https://docs.unity3d.com/ScriptReference/Input.GetTouch.html, it mostly worked, except that the GameObject isn't exactly where the touch occurred, but a bit below and to the left of it

A: My best guess would be that the pivot of your sprite is to the right and up of where you expect it to be, which is why it spawns low and left. You can move the pivot in the sprite editor. This is assuming your game is 2D?

A: ok, it was a pretty dumb issue, the sprite itself had an offset of from the


text:
Q: How to implement a version of css? Sometimes I notice a thing like:
../style.css?v=1.0
How to do this? LESS or PHP?
I want to display different content .css file depending on the version

A: Usually GET-parameter for css and js is added in order to be able to update the cached file.
But if you want it different text css depending on GET-parameters, then it can be implemented by means of php
Apache & PHP:
<FilesMatch "\.css$">
   SetHandler application/x-httpd-php
   Header set Content-type "text/css"
</FilesMatch>

style.css:
<?php
   header('Content-type: text/css')
...

or Nginx:
location /style.css {
    if ($args ~ "v=(\d+)") {
        rewrite ^(.*) style$1?.css redirect;
    }
}


text:
Q: In the difference between the sun and moon's tidal effects on earth, is density or distance a larger factor? This question is inspired by the (now looking at it, improper use of, my bad) comments section here in Physics SE. I'm not sure I could explain better than our short discussion does below:

No, the sun is not extremely dense. The conditions at the center of the sun are quite extreme in terms of pressure and temperature, and the density is quite impressive if one takes into account that the sun is made up mainly of hydrogen (plasma) which under "normal" conditions has a very low density, but in absolute terms the sun has a low density. Indeed the moon has about three times the density of the sun, a fact that, given the curious coincidence that sun and moon disks have almost exactly the same size as seen from the earth, explains why the moon has more tidal effect than the sun has. – Marc van Leeuwen
[unlreated_comment_ommitted]
@MarcvanLeeuwen isn't the increased tidal effect more a result of gravity's strength being inversely proportional to the square of distance between two objects? – TCooper
@TCooper No, since if that were true the sun would easily beat the moon, as it is $p$ times as far away, $p$ times the linear size, and so $p^3$ times as voluminous, for some large factor $p$ of proportionality (I guess around 300, thought I'd need to check the numbers). However tidal effect is proportional to the derivative of the vector-valued gravitational strength (or more properly acceleration), which follows an inverse cube law. That precisely cancels the volume effect, so only density remains. – Marc van Leeuwen
That's very interesting. Frankly I don't follow and will have to read up, so thank you for sharing. I was just referencing some old grade school knowledge... I always understood gravity as a relationship of mass and distance. Not accounting for volume or density at all (highly simplified) though I did find this: https://oceanservice.noaa.gov/education/tutorial_tides/tides02_cause.html Is it simply a case of the noaa needing to update their website? – TCooper

So when it comes to measuring the gravitational effect of the sun and moon on our tides, is the higher density of the moon, or the further distance of the sun, a larger contributing factor to the moon having a greater effect?

A: We get pretty close to answering all your questions here:

I always understood gravity as a relationship of mass and distance. Not accounting for volume or density at all …

Yes, gravity depends on mass and distance. Mass, in turn, depends on volume and density. In fact, mass is the product of volume and density.
As has been pointed out by other users and by the NOAA page you referenced, tidal forces are inversely proportional to the cube of the distance. They are also directly proportional to the mass and therefore directly proportional to the density.
According to the NOAA page, the effect of distance is a factor of about 59 million.
The densities of the Sun and Moon are about $1.4 \text{ } \text{g} \cdot\text{cm}^-3$ and $3.3 \text{ } \text{g} \cdot \text{cm}^-3$, respectively. This means the effect of density is a factor of less than 3.
Clearly, the larger factor, by a huge margin, is distance.
These numbers look a bit silly (59 million vs 3), because they ignore volume. Like Marc van Leeuwen's comment explained, the distance and volume effects cancel out, leaving just the density effect – a factor of a little over 2.

A: The tidal effects is related to the difference between gravitional field on 2 opposite points of the surface of the earth.
As the field is proportional to $\frac{M}{r^2}$, the difference is proportional to its derivative $\frac{M}{r^3}$. (Because the earth diameter is small compared to the distance to moon or sun).
$$F_s \propto \frac{M_{sun}}{r_{sun}^3} $$
$$F_m \propto \frac{M_{moon}}{r_{moon}^3} $$
The relation between that figures is about 0,45. That is: the solar effect on tides of sun is less than half the effect of the moon.
$M = \rho \frac{4}{3}\pi R^3$, where $R$ is the radius of a sphere where the density is being measured. As the density of the moon is bigger than the sun, the tidal effects in the surface of each of those bodies is bigger in the case of the moon.
But in our case of tides on earth, if we apply (for the sun for example):
$$F_s \propto \frac{M_{sun}}{r_{sun}^3} = \frac{\frac{4}{3}\pi \rho_{av} r_{sun}^3}{r_{sun}^3} = \frac{4}{3}\pi \rho_{av}$$
$\rho_{av}$ is not here the density of the sun, but only its mass divided by the volume of a sphere with a radius equal to the distance between sun-earth. (Imagine the sun in its future as a red giant - the effect in our tides doesn't change).
The same can be calculated for the moon.
That reasoning is only to show the effect of density on tides. It is real, but we must use that modified concept of average density, not the density of the bodies properly.


text:
Q: simulate mutil-touch event on MacOSX I want to "simulate" a multi-touch event for another application . e.g :simulate a zoom-in gesture on Preview.
use CGEventPost() can simulate and post the mouse click event . but there is no function for any MultiTouch event.
Also, there is no function like CGEventCreateMultiTouchEvent...(), thus I don't know if it's achievable by CGEventPost().
Any help will be very appreciated :)


text:
Q: prove that e^x is not Lipschitz on R I know that the definition of Lipschitz function is:
If A⊆R and f:A→ R is function. Then, f is said to be Lipschitz on A if there exists a constant K>0 such that,|f(x)−f(y)|≤K|x−y| for all x,y∈A.
but how to prove that e^x is not Lipschitz on R?

A: $e^x$ is not uniformly continuous and so is not Lipschitz. Take for example $x_n=\ln n,\ $ $y_n=\ln(n+1)$ then $y_n-x_n\to 0$ but $e^{y_n}-e^{x_n}\to 1$. Roughly speaking $e^x$ diverges to $+\infty$ with big velocity, bigger than a linear function

A: Because the derivative isn't bounded.
Convexity makes it very straighforward, though still true while being not convex.
$$f(y) - f(x) \geq f'(x) (y-x) $$

A: $\newcommand{\R}{\mathbb{R}}$
This kind of problem can be easily tackled using proof by contradiction.
Suppose $e^x$ is Lipschitz on $\R$. Then, there is a constant $L > 0$ such that for all $x,y \in \R$, $|e^x - e^y| \leq L|x-y|$. But according to the mean value theorem, there is $c\in (x,y)$ such that
$$
\frac{e^x - e^y}{x - y} = e^c
$$
Therefore, if we raise both $x$ and $y$, it can be arbitrarily large and of course, it can be larger than any $L > 0$, which is a contradiction.


text:
Q: Is it possible to use SVG files within SLDS React Datepicker components? I am working in the Quip platform (which runs on React), using the SLDS-React Datepicker component within a SLDS-React DataTableCell but have been unable to render any of the SLDS icons (.SVG files) within the Datepicker. It seems the following code snippet (which is generated from SLDS, and should be rendering the right arrow used to navigate between months) is restricting the SVG icon from displaying at all. I have included these assets in my build and can open & view the asset in another tab using the same link included below.
This code is just an example of icon usage, but this occurs in multiple places.
<button class="slds-button slds-button_icon-container" type="button">
        <svg aria-hidden="true" class="slds-button__icon">
                <use href="dist/assets/right.svg">
                </use>
        </svg>
        Next month
</button>

This is how I am instantiating the Datepicker component:
return (
        <IconSettings onRequestIconPath={({category, name}) => `dist/assets/${name}.svg`}>
                <DatePicker
                 align='right'
                 labels={{}}
                 onChange={(event, data) => {
                 this.state.editMode = false;
                 this.passUpdate(this.state.property, this.state.rowId, this.state.children);
                                }}
                 formatter={(date) => {
                          let newDate = date ? moment(date).format('YYYY-MM-DD') : '';
                          this.state.children = newDate;
                          return newDate;
                 }}
                 menuPosition='overflowBoundaryElement'
                 parser={(dateString) => {
                         return moment(dateString, 'MM-DD-YYYY').toDate();
                 }}
                 value={this.state.children}
                 />
        </IconSettings>
)

I have not added any styling to the components. I have also seen that editing the Button HTML inline from the browser and replacing the <svg component with an <img component, passing in the path to the icon as the src parameter, works perfectly.
Since I cannot modify the SLDS code directly to change these tags and replace the <svg with an <img, how can I get my icons to render within the Datepicker component?

A: I believe the issue here is that you're using IconSettings but not including any sprites. The docs here are admittedly light, but when we've implemented this in the past using webpack, a solution was to include the sprites as symbols on the page, so they can be referenced directly in the SVGs via onRequestIconPath.
<IconSettings onRequestIconPath={({name}) => `#${name}` }>

        <StandardSprite/>
        <ActionSprite/>
        <UtilitySprite/>
        {content}

</IconSettings>


text:
Q: Bluetooth Low energy android app not working all the time I have refereed the below link to create android app.
1)https://www.bignerdranch.com/blog/bluetooth-low-energy-part-1/
2)https://github.com/bignerdranch/android-bluetooth-testbed/tree/a/android-ble-part-1
But the app is not working all the time.

A: you can go through this sample code to get data from ble devices
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mHandler = new Handler();
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "BLE Not Supported",
                Toast.LENGTH_SHORT).show();
        finish();
    }
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

}

@Override
protected void onResume() {
    super.onResume();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
            settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            filters = new ArrayList<ScanFilter>();
        }
        scanLeDevice(true);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
        scanLeDevice(false);
    }
}

@Override
protected void onDestroy() {
    if (mGatt == null) {
        return;
    }
    mGatt.close();
    mGatt = null;
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == Activity.RESULT_CANCELED) {
            //Bluetooth not enabled.
            finish();
            return;
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void scanLeDevice(final boolean enable) {
    if (enable) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT < 21) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } else {
                    mLEScanner.stopScan(mScanCallback);

                }
            }
        }, SCAN_PERIOD);
        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mLEScanner.startScan(filters, settings, mScanCallback);
        }
    } else {
        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        } else {
            mLEScanner.stopScan(mScanCallback);
        }
    }
}

private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        Log.e("callbackType", String.valueOf(callbackType));
        Log.e("result", result.toString());//here you will get the details in ascii format and you have to convert that ascii to actual value
        BluetoothDevice btDevice = result.getDevice();
        connectToDevice(btDevice);
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        for (ScanResult sr : results) {
            Log.e("ScanResult - Results", sr.toString());
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("Scan Failed", "Error Code: " + errorCode);
    }
};

private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi,
                                 byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("onLeScan", device.toString());
                        connectToDevice(device);
                    }
                });
            }
        };

public void connectToDevice(BluetoothDevice device) {
    if (mGatt == null) {
        mGatt = device.connectGatt(this, false, gattCallback);
        scanLeDevice(false);// will stop after first device detection
    }
}

private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        Log.e("onConnectionStateChange", "Status: " + status);
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                Log.e("gattCallback", "STATE_CONNECTED");
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                Log.e("gattCallback", "STATE_DISCONNECTED");
                break;
            default:
                Log.e("gattCallback", "STATE_OTHER");
        }

    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        List<BluetoothGattService> services = gatt.getServices();
        Log.e("onServicesDiscovered", services.toString());
        gatt.readCharacteristic(services.get(1).getCharacteristics().get
                (0));
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic
                                             characteristic, int status) {
        Log.e("onCharacteristicRead", characteristic.toString());
        gatt.disconnect();
    }
};

and you have to add permission for bluetooth
 <uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<usesfeature android:name="android.hardware.bluetooth_le"android:required="true"/>


text:
Q: How to get path with a string filename with digits within in Python? I need to download a file that is automated on SharePoint. The thing is this file has the following filename structure:
fileYYYYMmm.xlsb
Example: file2022M03.xlsb
I must refer to this file using a wildcard or something (I don't know what exactly), to get dynamically that file.
Example: file????M??.xlsb
I'm using the following line code
download_path = sp.create_link(f'https://enterprise.sharepoint.com/:x:/r/sites/GLB-GIS-PERISCPE/Shared%20Documents/TMS_Ch/file/file'+str(yy)+'M'+'??'+'.xlsb')

How can I do this in Python?

A: It's pretty easy with an f string.  You just need to reference the variable in curly braces like this:
the_year = '22'
the_month = '03'

# print(f'https://enterprise.sharepoint.com/:x:/r/sites/GLB-GIS-PERISCPE/Shared%20Documents/TMS_Ch/file/file{the_year}M{the_month}.xlsb')
# https://enterprise.sharepoint.com/:x:/r/sites/GLB-GIS-PERISCPE/Shared%20Documents/TMS_Ch/file/file22M03.xlsb

download_path = sp.create_link(f'https://enterprise.sharepoint.com/:x:/r/sites/GLB-GIS-PERISCPE/Shared%20Documents/TMS_Ch/file/file{the_year}M{the_month}.xlsb')

A: I am assuming you only need one file and you will have variable name for year and month
You can use F-string like this:
download_path = sp.create_link(f'https://enterprise.sharepoint.com/:x:/r/sites/GLB-GIS-PERISCPE/Shared%20Documents/TMS_Ch/file/file{yy_var}M{mm_var}.xlsb')

Here yy_var will have store the year and mm_var will store the month.


text:
Q: How do I reset my Visual Basic Editor Layout? Something has gone terribly wrong with my VBE layout. I originally closed my Project explorer and was trying to figure out how to restore it when I made some changes under the window tab of the ribbon.
I've restored the Project explorer but I can't for the life of me reset my code window to display only the current module I'm working on. The resulting layout is hideous, truly atrocious, and difficult to work with.
disgusting VBE display
I've already tried resetting my registry key for VBA as recommended here to no avail. I believe I clicked on either Cascade or Tile Vertically to make the code block appear this way.
Any help would be greatly appreciated.

A: You've never hit 'Restore Down' before on the Windows controls? Click it again (it will now be called Maximise) to put things right.

A: Click the square box of any of the windows in the upper right corner for it to fill the window, and then you can navigate using the project folder structure to the left, or the Window menu at top.  Windows can be dragged and "docked" at different positions. For step by step instructions on how to dock windows in the VBE, including video see this site, for example

A: Try setting the code windows in your layout to how you like them.  Then add a module to your project, then exit Access.  It seems to save the layout at that point.
You can then delete the empty module.


text:
Q: How do I make my Image go above the Header Hello I want my profile photo / image go over the header area but.
As you can see it is getting cut off.

I tried playing around with the code and I got close I also made the position absolute but it messes up the flex size 2 (for the about me section).
So how can i fix this without messing up the flex 1 and flex 2?
Right now I am using Sass
http://lonestarwebandgraphics.com/

html

About Me

Hello my name is Ruben Esquivel and my dad was a graphic designer so I grew up playing with
                photoshop since I was a kid. For 10 years I worked as a remote graphic designer / web master running entire graphics department by myself providing mockups for getting sales and turning the mockups into print ready graphics to be printed.

                I am an expert in taking directions through phone or email and multi tasking multiple projects at once to meet the deadline. I can handle being under pressure and I am a master of hot keys so I can work fast when needed.

                After working in the industry for 10 years I felt like I knew everything when it came to graphic design so I decided to learn web development because I love learning new things. I love coding and I love taking my web designs and creating beautiful eye catchy websites. To be honest I love both graphic design and coding, being able to take an idea and turn into a design or website is like creating magic for me.

CSS / SASS CODE
#about-me {
    // z-index: 50;
    // overflow: visible;
    // height: 100%;
    // background: red;
    margin-top: -3rem;
    position: relative;

    .container {
        // position: relative;
        display: flex;

        .content-info {
            flex: 2;
        }

        .profile-pic {
            flex: 1;
            margin-top: -5rem;
            // position: relative;
            // position: absolute;
            // right: 0;
            // z-index: 20;

        }

    }

}

A: I think it gets cut off because you have overflow: hidden specified for .container.
An option would be to remove it and decrease a bit the padding of the image element, because it otherwise causes horizontal scrollbar to appear. A good idea might also be to use media queries for the padding, because width of the elements in the container is proportional to the resolution, but padding is not.

A: You should play around with z-index
.container{
position: relative;
z-index: 1;
}
.profile-pic{
position:absolute;
z-index: 2;
top:-25px;
}

You can play around with the top element.


text:
Q: java shift elements in array Hey I am trying to shift elements forward sending the last element in the array to data[0]. I did the opposite direction but I can't seem to find my mistake in going in this direction.
Pos is users inputed shift times amount
temp is the temporary holder.
data is the array
if(pos > 0)
{
   do
   {
        temp = data[data.length -1];

        for(int i =0; i < data.length; i++)
        {
           if(i == data.length-1)
           {
              data[0] = temp;
           }
           else
           {
               data[i+1] = data[i];
           }
        }

        pos--;
   } while(pos > 0);
}

Thanks.

A: A good idea is to use System.arraycopy.
Please refer to this question Java, Shifting Elements in an Array

A: try this
    int temp = data[data.length - 1];
    for (int i = data.length - 1; i > 0; i--) {
        data[i] = data[i - 1];
    }
    data[0] = temp;

or this
    int temp = data[data.length - 1];
    System.arraycopy(data, 0, data, 1, data.length - 1);
    data[0] = temp;


text:
Q: MediaPlayer prepare Failed Error(1,-17) when using recorded file .3gp I am trying record from the AudioRecorder then I am trying to play the same with Media Player, But its giving mediaplayer.prepare() failed to prepare. Could any one tell me what could appropriate reason.
Below is the code I am using
        public void onClick(View v) {

            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            if(case_value==0)
                recorder.setOutputFile(deviceMIC_path);
            else if(case_value==1)
                recorder.setOutputFile(deviceMIC_Handset_path);
            else if(case_value==2)
                recorder.setOutputFile(headsetMIC_path);

            recorder.setOnErrorListener(errorListener);
            recorder.setOnInfoListener(infoListener);

            try {
                recorder.prepare();
                recorder.start();
                if (ENABLE_LOGS)
                    Log.e(LOG_TAG, resources
                            .getString(R.string.record_started));
                Toast.makeText(context,
                        resources.getString(R.string.record_started),
                        Toast.LENGTH_LONG).show();
                recording = true;

            } catch (IllegalStateException e) {
                Log.e("","ILLEAGAL EXCEPTION...");e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("","IO EXCEPTION...");
            }
            catch(Exception e){
                e.printStackTrace();
                Log.e("","UNKNOWN EXCEPTION...");
            }

        }
    });

    stopButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (recording) {
                if (ENABLE_LOGS)
                    Log.e(LOG_TAG, "Record is going to be stoped...");
                recorder.stop();
                if (ENABLE_LOGS)
                    Log.e(LOG_TAG, "Record STOPPED....");
                Toast
                        .makeText(context, "Record STOPPED",
                                Toast.LENGTH_LONG).show();

                recorder.release();
                recorder=null;
            }
        }
    });

    playButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            MediaPlayer mediaplayer = new MediaPlayer();

            try {
                if(case_value==0)
                        mediaplayer.setDataSource(deviceMIC_path);
                else if(case_value==1)
                    mediaplayer.setDataSource(deviceMIC_Handset_path);
                else if(case_value==2)
                    mediaplayer.setDataSource(headsetMIC_path);

            } catch (IllegalArgumentException e) {

                e.printStackTrace();
            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }
            try {
                mediaplayer.prepare();
            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }
            catch(Exception e){
                e.printStackTrace();
            }
            // mAudioManager.setSpeakerphoneOn(false);
            if (ENABLE_LOGS)
                Log.e(LOG_TAG, "CASE VALUE : " + case_value);
            if (case_value == 0) {

                if (MainActivity.headsetState == 0) {

                    if (!mediaplayer.isPlaying()) {
                        mediaplayer.start();
                        if (ENABLE_LOGS)
                            Log.e(LOG_TAG, "PLAY started...");
                        Toast.makeText(context, "PLAY started...",
                                Toast.LENGTH_LONG).show();
                    } else {
                        mediaplayer.stop();
                    }

Below is the Error I am getting
12-12 12:00:01.186: E/com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity(1860): Record started
12-12 12:00:04.467: E/com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity(1860): Record is going to be stoped...
12-12 12:00:04.592: E/com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity(1860): Record STOPPED....
12-12 12:00:06.710: W/MediaPlayer(1860): info/warning (1, 26)
12-12 12:00:06.725: E/MediaPlayer(1860): error (1, -17)
12-12 12:00:06.725: W/System.err(1860): java.io.IOException: Prepare failed.: status=0x1
12-12 12:00:06.725: W/System.err(1860):     at android.media.MediaPlayer.prepare(Native Method)
12-12 12:00:06.725: W/System.err(1860):     at com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity$3.onClick(AudioLoopFtmTestActivity.java:155)
12-12 12:00:06.725: W/System.err(1860):     at android.view.View.performClick(View.java:2364)
12-12 12:00:06.725: W/System.err(1860):     at android.view.View.onTouchEvent(View.java:4179)
12-12 12:00:06.725: W/System.err(1860):     at android.widget.TextView.onTouchEvent(TextView.java:6534)
12-12 12:00:06.725: W/System.err(1860):     at android.view.View.dispatchTouchEvent(View.java:3709)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:883)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:883)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:883)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:883)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:883)
12-12 12:00:06.725: W/System.err(1860):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
12-12 12:00:06.725: W/System.err(1860):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
12-12 12:00:06.725: W/System.err(1860):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
12-12 12:00:06.725: W/System.err(1860):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
12-12 12:00:06.725: W/System.err(1860):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
12-12 12:00:06.725: W/System.err(1860):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-12 12:00:06.725: W/System.err(1860):     at android.os.Looper.loop(Looper.java:123)
12-12 12:00:06.733: W/System.err(1860):     at android.app.ActivityThread.main(ActivityThread.java:4338)
12-12 12:00:06.741: W/System.err(1860):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 12:00:06.741: W/System.err(1860):     at java.lang.reflect.Method.invoke(Method.java:521)
12-12 12:00:06.741: W/System.err(1860):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-12 12:00:06.741: W/System.err(1860):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-12 12:00:06.741: W/System.err(1860):     at dalvik.system.NativeStart.main(Native Method)
12-12 12:00:06.741: E/com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity(1860): CASE VALUE : 0
12-12 12:00:06.749: E/MediaPlayer(1860): start called in state 0
12-12 12:00:06.749: E/MediaPlayer(1860): error (-38, 0)
12-12 12:00:06.749: E/com.brcm.factorymode.audioloop.AudioLoopFtmTestActivity(1860): PLAY started...
12-12 12:00:06.756: I/MediaPlayer(1860): Info (1,26)
12-12 12:00:06.756: E/MediaPlayer(1860): Error (-38,0)

Could any one please tell me the way to resolve this problem.

A: Implement the OnCompletionListener and register it with your MediaPlayer instance.
After the media has been played out it will call this callback method onCompletion
void onCompletion(MediaPlayer mp){
   //Here you stop it.
   mp.stop();
   //Reset the data source path to the new file
   mp.setDataSource(<uri>);
   mp.prepare(); // or mp.prepareAsync();
   // start the mediaplayer after the prepare has completed.
}

Release the mediaplayer instance once you are done playing all the files.


text:
Q: Hide header tags in WKHTMLPDF TOC I'm trying to generate a PDF Catalog including a table of contens with wkhtmltopdf.
To achieve this I create a toc dump, and read it's content through PHP. So long - no problem...
Now I have some headers, that have to be display inside the TOC, but not in the rendered PDF. So I set the mentioned headers to "display: none". If I do so, they don't appear in the TOC.
I need a possibility to render some headers into the TOC without displaying them in the PDF document.

A: This can be achieved using --xsl-style-sheet option and using a customized XSL. You can add any content to it.


text:
Q: Angular 4 HTTP Get Request with authorization header 401 I'm trying to get data from an API that requires an Authorization header. It works great on Postman and Node but when I try to use it in Angular it just returns a 401. Can someone find an error in my request? Spent long time trying but couldn't find a solution.
This is my data.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService{

constructor(private authHttp: HttpClient) {}

  getData()
  {
    return this.authHttp.get('<<API URL>>', {
      headers:
          new HttpHeaders()
          .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')
          .append('Access-Control-Allow-Origin', 'http://localhost:4200')
          .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
          .append('Authorization', "<<my token>>")
          , responseType:'text'})
          .subscribe(data => data);

  }

}

This is the call I'm making to the service to retrieve that data, but the subscribe method is returning an error

Property 'subscribe' does not exist on type 'Subscription'. Did you
  mean 'unsubscribe'?

This is my data.component.ts (cut some lines for brevity)
constructor(private dt: DataService) { }

this.dt.getData().subscribe(result => {

      if (result){

        console.log(result);

      }
      else  {

        console.log('no result');

      }
    });

Appreciated!

A: In getData() it doesn't look like your are actually returning an Observable as you are executing subscribe() within that method. Instead try removing the subscribe and using the map() operator to return an Observable so that when you call getData() in data.component.ts you can subscribe() to the observable stream:
DataService:
getData() {
  return this.authHttp.get('<<API URL>>', {
    headers:
      new HttpHeaders()
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')
        .append('Access-Control-Allow-Origin', 'http://localhost:4200')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
        .append('Authorization', "<<my token>>")
    , responseType: 'text'
  })
  .map(data => data);
}

data.component.ts:
this.dt.getData().subscribe(result => { // do something with the result });

Instead of map() you can also utilize typechecking of the response to specify the data return type and effectively make map() unnecessary unless you need additional processing of the data before getting to data.component.ts:
interface SomeModel {
   foo: string;
   bar: number;
   foobar: string[];
}

getData() {
  return this.authHttp.get<SomeModel>('<<API URL>>', {
    headers:
      new HttpHeaders()
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')
        .append('Access-Control-Allow-Origin', 'http://localhost:4200')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
        .append('Authorization', "<<my token>>")
    , responseType: 'text'
  });
}

Hopefully that helps!

A: The problem is a (useless) .subscribe call in your service. It seems like you're misunderstanding not only how observables work, but also what should happen in subscribe method.
Observables in a nutshell
An Observable is an object which tracks events through time; also called a stream. When you call .get method of HttpClient, you're creating an observable. Think of observables as arrays through time (instead of arrays through space in the memory of a computer).
This is all great, but this stream is useless unless you can read the values which it emits. This is done by subscribing to the stream. You subscribe by using the method .subscribe. The argument of this method is a function that will be executed every time that a value is observed.
Your case
You've made a mistake of subscribing in the service. Moreover, you've made a mistake of doing nothing in your subscription.
Instead of subscribing, your service should just return the observable.
// in the service

getData() {
  return this.authHttp.get(example.com, headers)
}

Then, in your component, you should subscribe to the observable returned from your service.
// in the component

public data: any

ngOnInit() {
  this.service.getData().subscribe(data => {
     // once data arrives, this function will be called.
     // "data" will be data returned from your server,
     // so we can store it permanently in a property of the class
     this.fetchedData = data
  })
}

You can present your data in your template now (or do whatever you want with it).


text:
Q: Which API can I use to format an int to 2 digits? What API can I use to format an int to be 2 digits long?
For example, in this loop
for (int i = 0; i < 100; i++) {
   System.out.println("i is " + i);
}

What can I use to make sure i is printed out like 01, 02, 10, 55 etc (assuming a range of 01-99 )

A: You can use the DecimalFormat object.
DecimalFormat formatter = new DecimalFormat("#00.###");
int test = 1;

System.out.println(formatter.format(test));

Will print "01".

A: You could simply do
System.out.printf("i is %02d%n", i);

Have a look at the documentation for Formatter for details. Relevant parts are:

*

*The format specifiers for general, character, and numeric types have the following syntax:
      %[argument_index$][flags][width][.precision]conversion

(In this particular case, you have 0 as flag, 2 as width, and d as conversion.)

Conversion
'd'    integral      The result is formatted as a decimal integer
Flags
'0'                     The result will be zero-padded

This formatting syntax can be used in a few other places as well, for instance like this:
String str = String.format("i is %02d", i);

A: String class actually do formatting.
For your case, try:
String.format("%02d",i)


text:
Q: How to learn magento Hi I want to learn Magento, I am doing PHP for almost 2 years learn CMS and framework. Now want to learn Magento but I do not found any solid source to understand functionality and DB structure of magento. If any one can give me some books name or good article that will be very helpful thanks..

A: The best way to learn Magento is to solve issues as you go along. Maybe a good place to start is this:
http://www.magentocommerce.com/knowledge-base.
Also the guys at siteground did a nice thing with this: http://www.siteground.com/tutorials/magento/
Other than this, maybe you should actually start working on a task and when you hit a brick wall (this should happen very fast), just see how other people solved the issues.
As for database structure, maybe you should read about the EAV paradigm. This is how the products, categories and customers are stored in the DB.
If you insist on a database structure here it is...but good luck with that.


text:
Q: T4 Templates and Visual Studio Item Templates Is it possible to create a Visual Studio item template that generates from a T4 template?
My google-fu does not seem powerful enough to yield an answer!

A: Yes, you need to use GAX for that. It has a (rather limited implementation of) custom T4 host that allows you to use T4 as a template language.

A: Yes you can, actually ASP.NET MVC uses this approach when creating View item from Controller item
All the Best
Muse VSExtensions


text:
Q: Trouble serializing with to JSON in Java using Jackson Good morning guys!
I have a JSON strings that looks like:
{
   "StatusCode":0,
   "Message":null,
   "ExecutionTime":0,
   "ResponseData":[
        {"Name":"name1","SiteId":"1234","Type":"Type1","X":"1234567","Y":"123456"},
        {"Name":"Name2","SiteId":"2134","Type":"Type2","X":"1234567","Y":"1234567"},
        {"Name":"Name3","SiteId":"3241","Type":"Type3","X":"1234567","Y":"1234567"},
        {"Name":"Name4","SiteId":"4123","Type":"Type4","X":"123456","Y":"123456"}
    ]
}

I want to create an object where I can retrieve the Xand Y values.
I've been trying to use Jackson to serialize the JSON string, without success. I've created two extra classes for Jackson to use. One class for the top layer, StatusCode, Message, ExecutionTime and ResponseData which looks like
public class PL {
private Long statusCode;
private String executionTime;
private String message;
private ResponseData responseData;
public PL(){
}

public void setStatusCode(Long statusCode){
  this.statusCode = statusCode;
}

public Long getStatusCode(){
  return this.statusCode;
}

public void setExecutionTime(String executionTime){
  this.executionTime = executionTime;
}
public String getExecutionTime(){
  return this.executionTime;
}

public void setMessage(String message){
  this.message = message;
}
public String getMessage(){
  return this.message;
}

public void setResponseData(ResponseData responseData){
  this.responseData = responseData;
}
public ResponseData getResponseData(){
  return this.responseData;
}
}

Where ReponseData is returned as an object, and then I have another class for serializing ResponseData which looks like
public class ResponseData {

private String name;
private String siteId;
private String type;
private String x;
private String y;

public ResponseData(){
}

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

public void setSiteId(String siteId){
  this.siteId = siteId;
}
public String getSiteId(){
  return this.siteId;
}

public void setType(String type){
  this.type = type;
}
public String setType(){
  return this.type;
}

public void setX(String x){
  this.x = x;
}
public String getX(){
  return this.x;
}

public void setY(String y){
  this.y = y;
}
public String getY(){
  return this.y;
}
}

I then create an ObjectMapper with
private final static ObjectMapper mapper = new ObjectMapper();

and try to so read the values with
ResponseData e = mapper.readValue(result.toString(), ResponseData.class);

and end up with the exception

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "StatusCode" (class MyClass.ResponseData), not marked as ignorable (5 known properties: "x", "y", "siteId", "name", "type"])

as if it can't parse the first entry, StatusMessage. Even if I remove the second class and only try to parse the first four entries where i return ResponseData as a String I still get the same exception.

A: To start with, in PL you should have a List<ResponseData> not a simple ResponseData attribute. As you can see, in the JSON, ResponseData is an array "ResponseData":[...] so it will be deserialized as a List. Each element of the list will be a ResponseData object as you defined it.
Then you have a case issue, you have upper cases in the JSON that you don't have in your class attributes. You can use the @JsonProperty (See API) annotation to overcome the problem, this way:
class PL {
    @JsonProperty("StatusCode")
    private Long statusCode;
    @JsonProperty("ExecutionTime")
    private String executionTime;
    @JsonProperty("Message")
    private String message;
    @JsonProperty("ResponseData")
    private List<ResponseData> responseDatas;

    public PL(){
    }

    // getters/Setters

}

class ResponseData {

    @JsonProperty("Name")
    private String name;
    @JsonProperty("SiteId")
    private String siteId;
    @JsonProperty("Type")
    private String type;
    @JsonProperty("X")
    private String x;
    @JsonProperty("Y")
    private String y;

    public ResponseData(){
    }

    // getters/Setters

}

Then read your JSON as a PL object, like this:
ObjectMapper mapper = new ObjectMapper();
PL pl = mapper.readValue(json, PL.class);
for(ResponseData rd : pl.getResponseDatas()) {
    System.out.println(rd.getX());
    System.out.println(rd.getY());
}

This outputs:
1234567
123456
1234567
1234567
1234567
1234567
123456
123456

A: It is fairly straightforward. Define your response structure using composition of classes. It is unfortunate to use capitalised fields in JSON, which out-of-the-box requires capitalised field names in the Java DTO. Still those can be easily mapped to conventional low-case names either by using the ACCEPT_CASE_INSENSITIVE_PROPERTIES modifier on the ObjectMapper or by annotating fields with corresponding names. I prefer a property on the ObjectMapper as it keeps the DTO independent of the serialisation code and this technique is used in the test below (the test is green):
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestDeserialization50386188 {

    public static class Response {

        public static class ResponseDataType {
            public String name;
            public String siteId;
            public String type;
            public long x;
            public long y;
        }

        public int statusCode;
        public String message;
        public long executionTime;
        public List<ResponseDataType> ResponseData = new ArrayList<>();
    }

    private static final String data = "{\"StatusCode\":0,\"Message\":null,\"ExecutionTime\":0,\"ResponseData\":[{\"Name\":\"name1\",\"SiteId\":\"1234\",\"Type\":\"Type1\",\"X\":\"1234567\",\"Y\":\"123456\"},{\"Name\":\"Name2\",\"SiteId\":\"2134\",\"Type\":\"Type2\",\"X\":\"1234567\",\"Y\":\"1234567\"},{\"Name\":\"Name3\",\"SiteId\":\"3241\",\"Type\":\"Type3\",\"X\":\"1234567\",\"Y\":\"1234567\"},{\"Name\":\"Name4\",\"SiteId\":\"4123\",\"Type\":\"Type4\",\"X\":\"123456\",\"Y\":\"123456\"}]}";

    @Test
    public void deserialize_response_withJackson_ok() throws IOException {
        ObjectMapper mapper = new ObjectMapper()
          .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

        Response response = mapper.readValue(data, Response.class);

        assertEquals(4, response.ResponseData.size());
        assertEquals(1234567, response.ResponseData.get(2).x);
        assertEquals(1234567, response.ResponseData.get(2).y);
    }
}

You fill find the project with the executable test on this dedicated GitHub repo.
The "Clean Code" book by Uncle Bob does not really recommend the overuse of getters and setters so common in Java for DTOs, which a Response class is. Still you can replace all public fields with getter/setter pairs if you like but the clarity will suffer with no obvious gain on quality.

A: Use List to receive arrays.
private Long statusCode;
private String executionTime;
private String message;
public List<ResponseDataType> ResponseData

and it will do everything automatically.