text:
Q: Calculate the integral of $f(x,y,z)=12xyz$ on $D=\{ (x,y,z) \in R^3 \mid 0I'm learning to solve this kind of problems at the Calculus class, but I couldn't figure out this one.
I think i might have to use cylindrical coordinate, but i couldn't parameterize it.
(Sorry for my bad English.)

A: If you know to use cylindrical coordinates, there is no further difficulty really.
$x = r\cos\theta, y = r\sin\theta, z = z\implies 0<\theta<\frac \pi 2,\,\sqrt{2}r^2<z<\sqrt{3-r^2}.$ This means you need to find the bounds for $r$ by solving the previous inequality:
$2r^4<3-r^2$ or $2r^4+r^2<3\iff (r^2-1)(2r^2+3)<0\implies 0<r<1$, since $r$ is positive by default. Now your integral is:
$$I=\int_0^{\frac{\pi}{2}}\int_{0}^1\int_{\sqrt{2}r^2}^{\sqrt{3-r^2}}12r^3z\cos\theta\sin\theta dzdrd\theta.$$
Do not forget the extra $r$ from the Jacobian when changing to cylindrical coordinates.


text:
Q: ADT, typedef and representation independence in Java I would like to define an ADT that has the same interface as a java.util.Map.
However I read that it is an anti-pattern to make it MyType extends Map as explained here:
Is there a Java equivalent or methodology for the typedef keyword in C++?
Since in Java there is no equivalent to the C/C++ typedef there is no way to define a true type synonym.
I am thinking about these 2 solutions:

*

*Define a concrete wrapper/forwarding class for java.util.Map, but this would force me to code against a class instead of coding against an interface. I was looking at Guava's ForwardingMap but this is a class and not an interface.

*Define my own interface which mimics java.util.Map and an implementation that wraps a java.util.Map.  I don't like this duplication but I don't see any workaround that gives me the benefits of being able to program against an interface and representation independence.
Would it make sense to write something like public interface MyType<K,V> extends Map<K,V> and then:
public class MyTypeImpl<K, V> extends ForwardingMap<K, V> implements MyType<K, V> {

    final Map<K, V> delegate;

    public MyTypeImpl() {
        this(new HashMap<K, V>());
    }

    public MyTypeImpl(Map<K, V> delegate) {
        this.delegate = delegate;
    }

    @Override
    protected Map<K, V> delegate() {
        return delegate;
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double-checked Locking (DCL) and how to fix it I was reading an article about Double-checked Locking. The problem discussed is as follows:
public class MyFactory {
    private static MyFactory instance;

    public static synchronized MyFactory getInstance() {
        if (instance == null)
            instance = new MyFactory();
        return instance;
    }

    private MyFactory() {}
}

One of the suggested ways how to avoid synchronization on every getInstance() call is to use the class loader:
public class MyFactory {
    private static final MyFactory instance;

    static {
        try {
            instance = new MyFactory();
        } catch (IOException e) {
            throw new RuntimeException("Darn, an error's occurred!", e);
        }
    }

    public static MyFactory getInstance() {
        return instance;
    }

    private MyFactory() throws IOException {
        // read configuration files...
    }
}

Author says: "... the JVM ensures that this static initialisation code is called exactly once, when the class is first referred to and loaded." Which I totally agree. But I don't understand the follows: "Using the class loader is generally my preferred way of dealing with lazy static initialisation."
Is the second code snippet a lazy static initialisation?

A: It is not lazy. This is lazy (using class loader):
public class Singleton {

    public static class SingletonHolder {
        public static final Singleton HOLDER_INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.HOLDER_INSTANCE;
    }
}

A: Playing with Double-checked locking is like playing with fire. There are many ways one can get it wrong.
The purpose of Double-checked locking idiom is to avoid unnecessary synchronization. Thus your first code snippet doesn't fit into the category.
Coming to your second code snippet, if the singleton you are creating is static, then there is a compact solution in which you can define the singleton as a static field in a separate class and not in the same class.
class MyFactorySingleton {
  static MyFactory singleton = new MyFactory();
}

This semantics of Java guarantees that the field will not be initialized until the field is referenced, and that any thread which accesses the field will see all of the writes resulting from initializing that field.
But from JDK5 and later, Java has started supporting volatile semantics which says that

the value of a variable which is declared volatile will never be
  cached thread-locally. All reads and writes will go straight to "main
  memory". Access to the variable acts as though it is enclosed in a
  synchronized block, synchronized on itself.

So, a some what fool proof design for a Double-checked looking should look like this:
class MyFactory {
  private volatile MyFactory instance = null;

  public MyFactory getInstance() {
     if(instance == null) {
        synchronized(MyFactory.class) {
           if(instance == null) {
              instance = new MyFactory();
           }
        }
     }
     return instance;
  }
}

Prof. Joshua Bloch and his co-authors explains how Double-checked locking can go wrong in this article. It is worth reading this.

A: Not exactly. The initialization happens when MyFactory class was loaded, not when getInstance() was called. If you want to initialize the instance when the method was called, you can use a holder class.
public class MyFactory {
    private static final class Holder {
        private static final MyFactory instance = new MyFactory();
    }

    public static MyFactory getInstance() {
        return Holder.instance;
    }
}


text:
Q: Why am I getting "undefined reference to `glibtop_init'" during linking? I'm building a very small C/C++ project using eclipse and i'm getting the following during build:

make all
Building file: ../Metric.cpp
Invoking: GCC C++ Compiler
g++ -I/usr/include/glib-2.0 -I/usr/include/libgtop-2.0 -I/usr/lib/glib-2.0/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Metric.d" -MT"Metric.d" -o"Metric.o" "../Metric.cpp"
Finished building: ../Metric.cpp

Building target: linuxMonitor
Invoking: GCC C++ Linker
g++ -L/usr/lib -o"linuxMonitor"  ./Metric.o
./Metric.o: In function main':
/home/mike/workspace_c/linuxMonitor/Debug/../Metric.cpp:27: undefined reference toglibtop_init'
collect2: ld returned 1 exit status
make: *** [linuxMonitor] Error 1

What I can't figure out is why the linking is failing, or which linking flags to use to make this darn thing work!  -L/usr/lib should be point the linker to the directory where the library is, but it still fails.  When I do -l/usr/lib/myLibrary.a it still fails saying that it can't find -l/usr/lib/myLibrary.a
Any tips or advice on using the right commands for the linker would be appreciated!  I'm stuck!
-Mike

A: Your library file should be libsomething.a and the g++ option -lsomething
The manpage of g++ is more specific about this :
-l library

...

The linker searches a standard list of directories for the library,
which is actually a file named liblibrary.a.  The linker then uses
this file as if it had been specified precisely by name.

The directories searched include several standard system
directories plus any that you specify with -L.

...

The only difference between using an -l option and
specifying a file name is that -l surrounds library with lib and .a
and searches several directories.

A: In
g++ -L/usr/lib -o"linuxMonitor" ./Metric.o

you're not specifying any library.
Also, -l/usr/lib/myLibrary.a is wrong, you should rename your library to libmyLibrary.a and then use -lmyLibrary.  If you can't do that, then you need g++ -o linuxMonitor ./Metric.o /usr/lib/myLibrary.a.


text:
Q: Qt4 PySide: QPainter cross-platform pixel accuracy In trying to track down the differences in rendering between my two target platforms (Linux and OSX), I came across an apparent inconsistency in the way ellipses are rendered on each platform.
Here are the results: Linux vs OSX
And here is the program I used to generate this:
from PySide.QtGui import (QApplication, QGraphicsView, QGraphicsScene,
                          QMainWindow, QPixmap, QPainter)
from PySide.QtCore import Qt
import sys

if __name__ == '__main__':
    app = QApplication(sys.argv)
    scene = QGraphicsScene()
    view = QGraphicsView(scene)
    view.scale(15, 15)

    pix = QPixmap(200, 50)
    pix.fill(Qt.white)
    p = QPainter(pix)
    p.setPen(Qt.black)
    for i in range(1, 10):
        p.drawEllipse(0, 0, i, i)
        p.translate(i+5, 0)
    p.end()
    pixItem = scene.addPixmap(pix)

    win = QMainWindow()
    win.setCentralWidget(view)
    win.resize(700, 200)
    win.show()

    sys.exit(app.exec_())

Is this the result of my method of drawing or an incompatibility in the rendering engines?
My goal is to have a program that can color pixels accurately. For example, zoom in and color pixels individually or using a circular "brush", color a group of them (this is how I discovered the difference in rendering).
Is there a better way to approach this problem rather than drawing to pixmaps and relying on Qt for scaling pixels properly?


text:
Q: Trouble installing certain Paw extensions I'm unable to install almost any of the Paw extensions. Unfortunately several of the ones that won't install are the ones I really want! :)
I've tried almost all the code generators, and only found one that would install. e.g.

*

*Swift + NSURLSession Code Generator — does not install

*JavaScript + jQuery Code Generator — does not install

*Objective-C + NSURLConnection Code Generator — does not install

*WordPress Code Generator — does not install

The one that works:

*

*Betamax.py Generator — does install

For those that don't work, the following appears in the console:
30/09/15 7:21:11.328 PM Paw[9673]: NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

A: It seems to be a "problem" with El Capitan. According to this question, iOS 9 and OSX 10.11 require TLSv1.2 SSL for all hosts you plan to request data from unless you specify exception domains in your app's Info.plist file.
I tried to manually edit Info.plist and add
<key>NSAppTransportSecurity</key>
<dict>
    <!--Connect to anything (this is probably BAD)-->
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

But, after that, I just could not start Paw anymore and got the following line on console
07/10/15 00:39:15,398 com.apple.xpc.launchd[1]: (com.luckymarmot.Paw.103392[905]) Service exited due to signal: Illegal instruction: 4

A: It's now fixed in Paw 2.2.5, which is ready now on the website, or in a couple of days on the Mac App Store.


text:
Q: Order by top five repeated IDs There is a table in my database duplicate_id which contains multiple ids and also contains many duplicate ids in it. What I have been trying to do is to sort top five ids which are being repeated the most in the table duplicate_id. Kindly let me know how can i do that
Table Structure: ID | Message
Expected output:
ID    |   Number of repeats
201             8
212                  7
205                  5
209                  3
229                  2

A: SELECT ID, COUNT(*) AS `Number of repeats`
FROM duplicate_id
GROUP BY ID
ORDER BY COUNT(*) DESC
LIMIT 5

A: Try the order by so sort your results:
Select * from table order by repeats desc limit 5

A: well... try this (I don't know mysql, so I have to guess)
select ID,
       count(*) as 'Number of Repeats'
from   duplicate_ID
group  by ID
order  by 2

Another approach would be
select ID, 'Number of Repeats'
from (
  select ID,
         count(*) as 'Number of Repeats'
  from   duplicate_ID
  group by ID
  ) x
order by 'Number of Repeats'


text:
Q: Javascript/ jQuery solution to sum values from drop down lists in form Im just learning the ropes with javascript and jQuery but cant get my head around this. I have 3 drop down menus with a few products in them and each has a different value. All I want to do is have the user select one item on each of the drop downs and when they hit the submit button the values are added and a total is displayed in a text box.  I have now spent 14 hours trying to do this with no success so any help will be mostly grateful!

A: Its hard to know exactly what you're looking for but this attached JSFiddle does what you're describing - let me know if you want any part of it explained.
http://jsfiddle.net/FdZDP/1/
heres the gist:
$("#button").click(function() {
    var total = 0;
    $.each($(".summable") ,function() {
        total += parseInt($(this).val());
    });
    $("#sum").val(total)
});

A: This should be the gist of it:
$(function(){
    $('#my_form').submit(function(e){
        e.preventDefault();
        var val1 = $("#dropdown1").val();
        var val2 = $("#dropdown2").val();
        var val3 = $("#dropdown3").val();
        var total = parseInt(val1) + parseInt(val2) + parseInt(val3);
        $("#my_textbox").val(total);
    });
});

You're grabbing the selected value from each of the dropdowns. Then, you add them together, ensuring that they are integers (convert to a number in some way if you don't want integers). then, you place that value into the textbox.

A: For a variant of coffman's answer:
$("#button").click(function() {
    var total = $('.summable').toArray().reduce(function(a, e) {
        return a + parseInt($(e).val(), 10);
    }, 0);
    $("#sum").val(total)
});

which uses the ES5 Array.reduce() function to handle the summation of the values

A: I want to sum the values selecting from multi-select dropdown list box and display the total in another text field ...
my html code:
<select   class="multi-select" multiple name="amt[]" id="amt" onChange="update_price(this)">

    <option value=""></option>
    <option value="5">5Rs</option>
    <option value="10">10Rs</option>
    <option value="15">15Rs</option>

</select>

<input type="text" class="form-control" id="hidden" name="hidden" placeholder="Hidden" autocomplete="off"/>

javascript:
<script>

    function update_price(e) {
       var price = 0;
      $('option:selected', $(e)).each(function() {

       price += $(this).data('hidden');

      });
      $('#hidden').val(price);

    }

</script>


text:
Q: Best way to send user location updates to the server in the background(Android) My app needs to send the user location update frequently even when he is not using the app. So I created a service that returns start_sticky and I am using Google location services to send the data as specified here
android location updates. My service is implementing ConnectionCallbacks, OnConnectionFailedListener, LocationListener So whenever onLocationChanged(Location location) is being called I am sending the location to server. I want to know if doing this way can cause faster battery drain. If so what is the better way to do. While asking this question stackoverflow gave me a warning saying that the question appears subjective amd might be closed. But I cant figure out another way to ask this question. Hope  someone might help me with this. Thanks in advance

A: I can think of 2 methods for it:
1- I assume when the location of the user has changed, the app sends the server the lat and lng. So, you can save the lat and lng changes and send a group of them to the server every 20 lat/lng have been collected.
2- You can check if the lat/lng of the location update varies greatly from the previous ones and accordingly you can determine the rate of which you send the data to the server. For example, if the lat/lng are approximately the same, then lower the onLocationChange Listener rate (for instance the user is at home). And when the changes are great, then increase the location listener rate (for instance the user is driving).
However, this all depends on what the data of location is being used for. Hope this helps!


text:
Q: How to upload and retrieve pdf file in sqllite database I want upload pdf file into sqlite and retrieve the pdf file into listview how can I do that please send me the code after I retrieve the pdf file in list view it as to open in pdf file how can I do that please help me out
Thank in advance

A: I personally suggest you to use the cloud firestore to your application which will be helpful to upload or access the contents of files.
you can save the files in the firebase storage and then use the links to access them and list into the listview


text:
Q: While loop, can't seem to get it to get the proper data Write a class that asks for a whole number num make sure it is greater than 0 (data validation), and that calculates and returns the sum of the following series of numbers:
1/num + 2/num-1 + 3/num-2 + …. (num-1)/2 + num/1

Don't get caught in integer division!
Test your method by invoking it with num = 2; you will expect the result to be 2.5.
    public class LengthSeries
{
    public static void main (String[] args)
    {
    //variable declarations
    Scanner keyboard =  new Scanner(System.in);
    int num;
    int sum = 0; // sum
    int ctr = 1 ; //counter

    //Accept the required data

    System.out.print ("Enter a whole number greater than 0 :  ");
    num = keyboard.nextInt();

    //Process the data in order to determine data
    while ( num <= 0){
                     System.out.println ("Sorry number invalid");
                     System.out.println ("please write a whole number greater than 0 :  ");
                     num = keyboard.nextInt();
                  }

    while (num <= 0){

                    sum += (ctr / num);
                    num -= ctr;
                    ctr++;
                }

    //Display the output
    System.out.println ();
    System.out.println ("Your sum is:  "         +sum);
    System.out.println ("\n\nWritten by: KinnahRose Lopez");

    } //end main method
} //end LengthSeries class

A: You can try this:
public static void main(String[] args) throws Exception {
    Scanner keyboard =  new Scanner(System.in);
    System.out.print ("Enter a whole number greater than 0 :  ");
    int num = keyboard.nextInt();
    while (num<1) {
        System.out.print ("Enter a whole number greater than 0 :  ");
        num = keyboard.nextInt();
    }

    double sum = 0;
    double d = num; // convert num to double to get the correct result.
    for (int i = 1; i <= num; i++) {
        sum += i/(d-(i-1));
    }
    System.out.println("sum = " + String.format("%.2f", sum));
}

Example:
Enter a whole number greater than 0 :  2
sum = 2.50

A: import java.util.Scanner;`enter code here`
public class Test
{
    public static void main (String[] args)
    {
        //variable declarations
        Scanner keyboard =  new Scanner(System.in);
        int num;
        double sum = 0; // sum
        //Accept the required data
        System.out.print ("Enter a whole number greater than 0 :  ");
        num = keyboard.nextInt();
        //Process the data in order to determine data
        while ( num <= 0){
            System.out.println ("Sorry number invalid");
            System.out.println ("please write a whole number greater than 0 :  ");
            num = keyboard.nextInt();
        }
        int temp = num;
        for (double i = 1; i <= num; i++)
        {
            sum = sum + (i/temp);
            temp--;
        }
        //Display the output
        System.out.println ();
        System.out.println ("Your sum is:  "         +sum);
        System.out.println ("\n\nWritten by: KinnahRose Lopez");

    } //end main method
} //end LengthSeries class

A: double sum =0;
for(double i=1.0; i<= num; i+=1.0) {
    sum+=i/(num-i-1);
}


text:
Q: Landscape : Can't create an account : Personal server I have just installed Canocial Landscape and have followed this guide.
After i am going to https://10.0.2.44 do i have to create account
So far so good,  but when i am clicking the Sign Up button do i get redirected to https://landscape/new-standalone-user and getting an "Server Not Found"

A: You have a hostname/DNS issue. A quick fix would be to add an entry for "10.0.2.44 landscape" in the /etc/hosts file of the machine you are using to access landscape from.


text:
Q: Why is foo object not changing? var foo = {'bar': 1};

function overwriteFoo(obj) {
   obj = foo;
   obj = {'bar': 2};
}

overwriteFoo(foo)
console.log(foo)

I thought that assigning foo to obj would make this work how I wanted. I thought that objects in javascript were sent by reference so why cant I reassign foo?

A: As some people say, everything is pass-by-value, and objects' values are their reference. When you do obj = {'bar': 2}, you are reassigning obj to point to {'bar': 2} instead of pointing to foo. In fact, there is no way to just swap out an entire object like that. You can, however, change properties, as they essentially "dereference" the value:
function overwriteFoo(obj) {
    obj.bar = 2;
}
overwriteFoo(foo);
console.log(foo); // will now be {bar: 2}

A: Assining a variable to another variable just returns the assigned variable's content.
Example:
var obj1 = {hello: 'hello'};
var obj2 = obj1;

alert(obj2);// will return hello: 'hello'

// BUt if you try to change obj2 to an object then obj1 will be just unassigned from obj2 but is not changed.


text:
Q: How to make two independent instance of a ControlTemplate In a window? i have a controltemplate with a textbox and a button,the button open a sub form to select something and show selected item in the textbox,like this:
    <Window.Resources>
    <ControlTemplate x:Key="CreateParam">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>
            <Button Content="select" Command="{Binding ShowSpecItemViewommand}"  Grid.Column="0" Margin="2"/>
            <TextBox Margin="2" Text="{Binding Param}" Grid.Row="0" Grid.Column="1"/>
            <TextBlock Margin="5" Text="patameter" Grid.Row="0" Grid.Column="2"/>
        </Grid>
    </ControlTemplate>
    </Window.Resources>

and i have a property in the viewmodel like this:
 public string param;
    public string Param
    {
        get
        {
            return param;
        }
        set
        {
            param = value;
            RaisePropertyChanged("Param");
        }
    }

and now i want to create two independent instance of that control in a window,but when i select a value for the first instance,both of them have been changed.should i define two property?and how can i bind them to the control template?
i'm not sure that every one can understand what i mean,so i hope someone edit my question:)

A: How do you use the Control Template? To which Control do you attach this template? Is it a template for a custom control you have? Is it a template to a known control?
How do you instantiate the DataContext for the Control Template?
While you can implement what you want using ControlTemplate (and a custom control), and if you have many (i.e. much more than two, and all over) instances of your object a ControlTemplate may be the right paradigm, you'll be way better off using DataTemplate, or UserControl. There is more than one way to achieve what you want, but the code below is considered the "canonical" solution:
Say Param is a property of MyVM object. Then your XAML file should be:
<Window
    x:Class="SO.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:so="clr-namespace:SO"
    Height="200" Width="350"
    Title="SO Sample"
    >
    <Window.Resources>
        <DataTemplate DataType="{x:Type so:MyVM}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="3*"/>
                </Grid.ColumnDefinitions>
                <Button Content="select" Command="{Binding ShowSpecItemViewommand}"  Grid.Column="0" Margin="2"/>
                <TextBox Margin="2" Text="{Binding Param}" Grid.Row="0" Grid.Column="1"/>
                <TextBlock Margin="5" Text="patameter" Grid.Row="0" Grid.Column="2"/>
            </Grid>
        </DataTemplate>
    </Window.Resources>

    <StackPanel>
        <ContentControl>
            <so:MyVM Param="1234" />
        </ContentControl>
        <ContentControl>
            <so:MyVM Param="5678" />
        </ContentControl>
    </StackPanel>

</Window>


text:
Q: SQL db type of comment and classic ASP stored procedure I have this error thrown when I'm trying to execute stored procedure with classic ASP code:
ADODB.Command error '800a0d5d'

Application uses a value of the wrong type for the current operation.

This is the line where the compiler is complaining:
cmdStoredProc.parameters.append cmdStoredProc.createparameter("@Comments",201,1,16,strComments)

@Comments is of sql db type 'text'.
The stored procedure is expecting this parameter:

@Comments text = null

I did some response write lines to debug and make sure that the app is reaching the line above so its something wrong with this parameter.
Anything you see wrong for declaring the stored procedure parameter for type of 'text' as it is in my case?

A: The Stored Procedure has already been defined on the SQL Server... no need to append the parameter, just set it:
cmdStoredProc.parameters("@Comments") = strComments
Set rsTheResultingRS = cmdStoredProc.Execute

... assuming that's the only parameter.
At least, this is how my currently-running server calls SPs.


text:
Q: Which Laptop is best for Android studio I have system with 2gb ram and core i5 processor.Is it compatible with android studio.Which one will be the best system for android studio.
Problems Faced in my curent system
1.I find my gradle build really slow.
2.During starting of emulator on console error is coming that is related to heap size.
Solution i tried
1.Update Android sdk tools
2.From bin folder changed the maximum size to 1024m and minimum to 256m
Still facing the problem and Its taking too much time.
If its an system issue then please provide me a laptop name with proper system requirements within 60k.
Thanks
Pranap

A: You really should add some more RAM to your system.
It's not a config solution, you're facing hardware limitations, so I'll really recommend you to upgrade your system up to 8gb RAM.It's a really cheap invest and it will improve your working time.

A: You need to upgrade your hardisk to SSD also.
Which helps to improve performance of your laptop around 40-50% faster.
You can look here for new laptop check below link
https://yourchoicestore.in/?s=i5+laptop


text: Q: How to detect any modal window on site Python selenium? I make script which open site from text document (in document it about 150+ sites) and make screenshot of first screen. I have two problems. It is cookie alert and modal popup windows like "subscribe on our newsletter", "10% discount on this weekend" and something like this. Cookie alert was handeled by add crx extension before  driver launch ( Pop up blocker for Chrome™ - Poper Blocker). But i not found something like this for modal windows. All modal windows have different xPath and class names. Like "modal", "ui-diaglod", "popup", etc. I have a question how to handle modals and dimming the background and after closing them make screenshot. I tried handle it by adding JavaScript script that searching  modals by class names, but it so many classes that my solution didn`t work properly


text:
Q: ImageMagick Watermark in PHP - How can I scale watermark with % of original image size instead of % of watermark image size? So I took ImageMagick Watermark in PHP code as available in www.rainbodesign.com and adjusted it so that it fits my needs: adding an overlay watermark image on the bottom right corner of the original image. This link triggers the conversion mywebsite.com/watermark.php?src=filepath-to-image and returns the new watermarked image. Here's the full code:
    <?php
// ImageMagick Watermark in PHP
// Copyright 2010-2011 by Richard L. Trethewey rick@rainbo.net
// http://www.rainbodesign.com/pub/watermark/
// 10/28/11 RLT
// If you use this script, I'd appreciate a link!  Thanks!

// 05/16/11 Updated to support text rotation, top/bottom/center
// 05/28/11 Updated to sanitize inputs
// 10/25/11 Added 'auto' color, inspired by Mikko's Blog http://valokuva.org/?p=59
//          RGB to HSL code by EasyRGB.com and http://serennu.com/colour/rgbtohsl.php

// 11/10/20 Deleted all references to text overlay and its settings
//          Added bottomright support

// Constants
$bContent = "Content-type: image/bmp";   // for BMP files
$jContent = "Content-type: image/jpeg";  // for JPEG files
$gContent = "Content-type: image/gif";   // for GIF files
$pContent = "Content-type: image/png";   // for PNG files
$tContent = "Content-type: image/tiff";  // for TIFF files
$old_image = '';    // Default base image filepath.

// User Settings and Defaults
$wm_image = 'images/watermark.png';     // Default watermark image file (include a path/URL, if necessary)
$wm_type = 'img';               // Set to 'msg' for text watermark.  Set to 'img' for image watermark.
$position = 'bottomright';   // Default watermark position - bottom left corner
$wm_opacity = 80;   // Default watermark image overlay opacity
$wm_rotate = 0;     // Default watermark image overlay rotation (in degrees)
// $gravity = 'SouthWest'; // Default watermark Imagemagick gravity - bottom left corner
$padding = 0;       // Default padding in pixels for watermark positioning.  Both top/bottom and left/right.

// Handle Query String option parameters
// src
 if (isset($_GET['src'])) { $old_image = $_GET['src']; }

// Block script hacking.
 $matches = array();
  if (preg_match('/([;\n\r])/i', $old_image, $matches)) { die; }

  switch(strtolower($position)) {
   case('bottom'):
    $gravity = 'SouthWest';
    break;
   case('bottomcenter'):
    $gravity = 'South';
    break;
   case('bottomright'):
      $gravity = 'SouthEast';
    break;
   case('top'):
    $gravity = 'NorthWest';
    break;
   case('topcenter'):
    $gravity = 'North';
    break;
   case('center'):
    $gravity = 'Center';
    break;
 } // end switch($position)

$dot = strrpos($old_image, '.');    // Set image type based on file name extension.  I know. Sorry, but it's fastest.
$extension = substr($old_image, $dot);
  switch($extension) {
   case('.jpg'):
   case('.jpeg'):
   $theContent = $jContent;
   $theWMType = 'jpg:-';
   break;
   case('.gif'):
   $theContent = $gContent;
   $theWMType = 'gif:-';
   break;
   case('.png'):
   $theContent = $pContent;
   $theWMType = 'png:-';
   break;
   case('.bmp'):
   $theContent = $bContent;
   $theWMType = 'bmp:-';
   break;
   case('.tif'):
   $theContent = $tContent;
   $theWMType = 'tif:-';
   break;
 } // end switch($extension)

// Image Overlay Watermark
 if ($wm_type == 'img') {
  $wmCmd = "convert $wm_image -background transparent -rotate $wm_rotate";
  $wmCmd .= " -scale 35%";
  $wmCmd .= " miff:- |";
  $wmCmd .= " composite -gravity $gravity -geometry +0+0 -blend " . $wm_opacity . "%";
  $wmCmd .= "  - $old_image $theWMType";
  } // endif $wm_type == 'img'

$test = 0; // set to 1 to view ImageMagick command being executed
 if ($test) {
 header('Content-type: text/plain');
 echo("$wmCmd\n");
 die;
}

  header($theContent);
  passthru($wmCmd);  // use passthru() to output binary data

exit;

?>

With this code I managed to add a watermark overlay image to the original images. But I need the watermak image to be 35% of original image size, not 35% of watermark image size! (Of course, with the watermark image mantaining it's aspect ratio)
// Image Overlay Watermark
 if ($wm_type == 'img') {
  $wmCmd = "convert $wm_image -background transparent -rotate $wm_rotate";
  $wmCmd .= " -scale 35%"; // here is where I need the magic to happen!
  $wmCmd .= " miff:- |";
  $wmCmd .= " composite -gravity $gravity -geometry +0+0 -blend " . $wm_opacity . "%";
  $wmCmd .= "  - $old_image $theWMType";
  } // endif $wm_type == 'img'

Does anybody know how to achieve this? Thanks in advance!! <3

A: I would get the size of the original with getimagesize() ( I know that is a GD command ) and use the width from that to resize the watermark.
$size = getimagesize($old_image);
$watermakSize = $size[0]*.3; ( you can work out what 35% is )

$wmCmd .= " -resize {$watermakSize}x"; // here is where I need the magic to happen!

There are other ways but this is a simple one.
It is always good to mention what version of Imagemagick you are using.


text:
Q: Vmware linux automated install Does vmware products has a linux automated installing feature? (like windows auto install)
Or if not how implement this feature?

A: Every major Linux distribution has an automatic installation process. For Debian based distributions the search term is "preseed", for RedHat based distributions it is "kickstart", other distributions have other processes.
In VMware you can take a look at guest customizations. This only works for some major distributions that are supported by VMware, but it allows you to make certain modifications when cloning a VM, like the hostname, network settings, hard disk modifications.
All these processes are extensively documented.


text:
Q: PHP: выделение элементов массива в отдельный массив и последующая сортировка Приветствую
подскажите, есть ли в php функционал:

*

*найти в массиве элементы по некоторому алгоритму (описанный как
функтор) и выделить в отдельный массив

*отсортировать найденный массив по некоторому алгоритму (описанный как функтор)
подозреваю, что одной такой функии нет, но хотя бы по 1 функции на 1 этап есть?
очень не хочется этап 1 через for делать

A: *

*array_column()

*array_multisort()
Пример использования:
$arr = [
    ["menu" => "ббббб", "link" => "/catalog/6"],
    ["menu" => "яяяяя", "link" => "/catalog/5"],
    ["menu" => "ааааа", "link" => "/catalog/10"],
    ["menu" => "ууууу", "link" => "/catalog/2"]
];

$key = 'link'; // Ключ, по которому сортировать
array_multisort(array_column($arr, $key), SORT_NATURAL, $arr);

var_dump($arr);

Результат:
array (size=4)
  0 =>
    array (size=2)
      'menu' => 'ууууу'
      'link' => '/catalog/2'
  1 =>
    array (size=2)
      'menu' => 'яяяяя'
      'link' => '/catalog/5'
  2 =>
    array (size=2)
      'menu' => 'ббббб'
      'link' => '/catalog/6'
  3 =>
    array (size=2)
      'menu' => 'ааааа'
      'link' => '/catalog/10'

A: *

*array_filter (http://php.net/manual/ru/function.array-filter.php)

*usort (http://php.net/manual/ru/function.usort.php)
Тут сравнение всех функций сортировки:
http://php.net/manual/ru/array.sorting.php


text:
Q: Can anyone explain the error message "Rank-deficient equality constraint subproblem HFTI" from scipy miminize? I am trying to make sense of the scipy function scipy.optimize.fmin_slsqp and came across the error: Rank-deficient equality constraint subproblem HFTI.
The error can be found in this official document from here.
Can anyone explain what is going on with this error?

A: You can try tracing through the source: https://github.com/scipy/scipy/blob/master/scipy/optimize/slsqp.py
In general, I would interpret "rank deficient" as "you don't have enough constraints, or some of your constraints are not linearly independent (and therefore disappear after reduction)".


text:
Q: How to set individual state of child component which is added through loop in react? I have a Parent react component where i am iterating a list of "tasks" using map function. Inside this function i am calling Child component to render(Passing each "taskId" as props).
Inside the Child component, i am calling redux to return the chart data based on the "taskId" from the parent props to rendering the chart.
I was expecting all the child component will return different chart but i am getting same chart in all of the child component.
How to set individual chart data/state of my child component?
If chart data cannot be retrieved inside the child, then how to do it in parent and pass it to child?
class Parent extends React.Component {
      componentDidMount() {
            this.props.getTasks(id);
      }

      render() {
            {this.state.tasks && this.state.tasks.length > 0
                  ? this.state.tasks.map((task, index) => {
                        <Child key={task.id} taskId={task.id}>
                  }) : ""
            }
      }

      const mapStateToProps = state => ({
            tasks: state.task.get("tasks")
        });

      const mapDispatchToProps = dispatch => ({
        getTasks: id => dispatch(taskOperations.getTasks(id))
      });

}

class Child extends React.Component{
      componentDidMount() {
         let taskId = this.props.taskId
         this.props.getChartData(taskId)
      }

      componentWillReceiveProps(nextProps) {
         // Anything to do here?
      }

      render() {
            // Showing same chart data for every child
            {this.props.chartData &&
            <Chart
                  options={this.props.chartData.options}
                  series={this.props.chartData.series}
                  type="line"
                  height={255}
            />
            }
      }

      const mapStateToProps = state => ({
            chartData: state.chart.get("chartData")
        });

      const mapDispatchToProps = dispatch => ({
             getChartData: id => dispatch(chartOperations.getChartData(id))
      });

}


text:
Q: Cannot get table height to contstrain with in div I've played around with a number of options, but I can't keep the table height from growing as I add lines dynamically.
This is a small section, part of a more complex page. Basically I have several div tags within the larger container div.
As more lines are added the table pushes the button below outside the boundaries of the div.  Run the code snippet to observe the problem.

function onBodyLoader(obj) {
  g.c.assignEventListners();
}
var g = {};

g.formClass = function() {
  /*
  ----------------------------------
  Properties for formClass
  ----------------------------------
  */
  this.tr;
  this.td;
  this.elist = [];

  /*
  ----------------------------------
  Methods for formClass
  ----------------------------------
  */

  this.assignEventListners = function() {
    this.tbody = document.getElementById('emailDist');

    g.sbAddELine = document.getElementById('sbAddELine');
    g.sbAddELine.addEventListener("click", function(evt) {
      g.c.addBlank();
    }, false);

    /*event listener for all links on the email list body*/
    g.dataUpdate = document.querySelector("#emailDist");
    g.dataUpdate.addEventListener("click", g.c.tableBodyRouter, false);

  };

  this.tableBodyRouter = function(e) {
    /*
    called from clicks on keyTable or task links
    */
    if (e.target !== e.currentTarget)
      if (e.target.id.indexOf('eRemove') > -1)
        g.c.removeEmail(e);
    e.stopPropagation();
  };

  this.redrawElist = function() {

    /*delete current table*/
    while (this.tbody.rows.length > 1)
      this.tbody.deleteRow(1);

    /*redraw table*/
    for (var i = 0; i < this.elist.length; i++) {
      this.rowLayout();
    }
  };

  this.addBlank = function() {
    /*add blank to this.elist array*/
    this.elist.push({
      eEmail: '',
      eFirst: '',
      eLast: '',
    });

    this.rowLayout();

  }
  this.removeEmail = function(e) {
    var x = e.target.id.substr(7);

    this.elist.splice(x, 1);
    this.redrawElist();

  };

  this.rowLayout = function() {
    var rowCnt = this.tbody.rows.length - 1;
    this.tr = this.tbody.insertRow(this.tbody.rows.length);

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eFirst' + rowCnt + '" maxlength="20" size="20" value=""/>';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eLast' + rowCnt + '" maxlength="20" size="20" value="" />';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eEmail' + rowCnt + '" maxlength="50" size="50" value="" />';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="button"  id="eRemove' + rowCnt + '" value="Remove" ">';
    document.getElementById("eFirst" + rowCnt).focus();
    document.getElementById("eFirst" + rowCnt).select();
  }

}
g.c = new g.formClass;
table {
  height: 60%;
  max-height: 60%;
  width: 100%;
  display: inline-table;
  border-style: none;
}

tbody {
  font-size: 10pt;
  display: block;
  height: 90%;
  overflow-y: scroll;
}

#container {
  position: absolute;
  width: 98%;
  top: 40px;
  height: 90%;
}

#dataEntryDiv {
  border: medium groove;
  position: absolute;
  top: 0.5em;
  height: 95%;
  padding-left: 1em;
  padding-right: 1em;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Email List</title>

  <form id='intactRolesForm' method="post" action="" onSubmit="return false;">

        <input type="button" id='sbAddELine' value="Add non-company contact">

Email Distribution List

              First Name
              Last Name
              email
              remove from list

        <input type="button" id='SaveEmailList' value="Save email List">

  </form>

A: This is the basic behavior of a table. it shrinks and expand acording to its content.
What you can do to manage height is to reset the display.
it can be anything but  table/inline-table/table-cell/table-row/.. . nor inline.
You used inline-table, inline-block might be fine:

function onBodyLoader(obj) {
  g.c.assignEventListners();
}
var g = {};

g.formClass = function() {
  /*
  ----------------------------------
  Properties for formClass
  ----------------------------------
  */
  this.tr;
  this.td;
  this.elist = [];

  /*
  ----------------------------------
  Methods for formClass
  ----------------------------------
  */

  this.assignEventListners = function() {
    this.tbody = document.getElementById('emailDist');

    g.sbAddELine = document.getElementById('sbAddELine');
    g.sbAddELine.addEventListener("click", function(evt) {
      g.c.addBlank();
    }, false);

    /*event listener for all links on the email list body*/
    g.dataUpdate = document.querySelector("#emailDist");
    g.dataUpdate.addEventListener("click", g.c.tableBodyRouter, false);

  };

  this.tableBodyRouter = function(e) {
    /*
    called from clicks on keyTable or task links
    */
    if (e.target !== e.currentTarget)
      if (e.target.id.indexOf('eRemove') > -1)
        g.c.removeEmail(e);
    e.stopPropagation();
  };

  this.redrawElist = function() {

    /*delete current table*/
    while (this.tbody.rows.length > 1)
      this.tbody.deleteRow(1);

    /*redraw table*/
    for (var i = 0; i < this.elist.length; i++) {
      this.rowLayout();
    }
  };

  this.addBlank = function() {
    /*add blank to this.elist array*/
    this.elist.push({
      eEmail: '',
      eFirst: '',
      eLast: '',
    });

    this.rowLayout();

  }
  this.removeEmail = function(e) {
    var x = e.target.id.substr(7);

    this.elist.splice(x, 1);
    this.redrawElist();

  };

  this.rowLayout = function() {
    var rowCnt = this.tbody.rows.length - 1;
    this.tr = this.tbody.insertRow(this.tbody.rows.length);

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eFirst' + rowCnt + '" maxlength="20" size="20" value=""/>';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eLast' + rowCnt + '" maxlength="20" size="20" value="" />';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="text" id="eEmail' + rowCnt + '" maxlength="50" size="50" value="" />';

    this.td = this.tr.insertCell(this.tr.cells.length);
    this.td.innerHTML = '<input type="button"  id="eRemove' + rowCnt + '" value="Remove" ">';
    document.getElementById("eFirst" + rowCnt).focus();
    document.getElementById("eFirst" + rowCnt).select();
  }

}
g.c = new g.formClass;
  table {
    height: 60%;
    max-height: 60%;
    width: 100%;
    display: inline-block;/*... or block : do not use table display if you need to constrain height */
    border-style: none;
  }

  tbody {/* this CSS could have been set to table directly :) */
    font-size: 10pt;
    display: block;
    height: 90%;
    overflow-y: scroll;
  }

  #container {
    position: absolute;
    width: 98%;
    top: 40px;
    height: 90%;
  }

  #dataEntryDiv {
    border: medium groove;
    position: absolute;
    top: 0.5em;
    /*left: 37em; removed for demo */
    height: 95%;
    padding-left: 1em;
    padding-right: 1em;
  }

  <form id='intactRolesForm' method="post" action="" onSubmit="return false;">

        <input type="button" id='sbAddELine' value="Add non-company contact">

Email Distribution List

              First Name
              Last Name
              email
              remove from list

        <input type="button" id='SaveEmailList' value="Save email List">

  </form>

Note: You did use display:block on tbody, you could have apply this directly to the table element and reset tbody to display:table :) (defaut is table-row-group )

A: Add
#dataEntryDiv {
    overflow: auto;
}

A: To get a simplified version of the situation, I would suggest writing something like this - instead of putting in the code from your actual project. This way, you can get away from trying to 'fix' something - and possibly see a better way to build the layout - or at least make the use-case more specific.
https://stackoverflow.com/help/how-to-ask

markup

    I'm a table wrapper thing

    <button>button (add row)</button>

styles
.table-wrapper {
  height: 300px; /* arbitrary */
  border: 2px solid red;
}

.table-wrapper main {
  height: 260px; /* likely you'd use flexbox or percentages or JS */
  border: 2px solid blue;
  overflow: auto;
}

js
var $table = $('.table-wrapper').find('table');
var $moreButton = $('.table-wrapper').find('button');

var counter = 0;

function addRow() {
  counter = counter + 1;
  $table.prepend('
row and data ' + counter + '
');
}

addRow();
// populate some things to start

$moreButton.on('click', function() {
  addRow();
});

https://jsfiddle.net/sheriffderek/b6z4ep46/


text:
Q: Failed to save options error in Liquid XML Studio When saving the settings using Tools->Options you may see an error:
"Cannot create a file when that file already exists."

A: This is typically due to your anti-virus program or security permissions.
Specifically, we have seen error when McAfee Real-Time Scanner is active.
To resolve this issue, add the following file to the Excluded File list in the Anti-virus software:

%APPDATA%\Liquid Technologies Ltd\Liquid XML Studio
  2015\UserSettings.xml

But also check that your account has read/write access to the containing folder

%APPDATA%\Liquid Technologies Ltd


text:
Q: Jekyll not updating all files I have the following setup:
NAS with GIT Server ---> Raspberry Pi with Jekyll ---> rsync to web-server

When the NAS receives a Git commit, it logs into my Pi and activates a script. This script calls Jekyll:
#!/usr/bin/env bash
MYDATE="$(date)"
PROJECT=website.git
REMOTE=username@username.example.com:html
NAS=username@nas.internal.example.com:333

# Log commit
logger "[GIT] Received commit in $PROJECT on $MYDATE"

# Change to git directory
cd ~/$PROJECT
if [ $? -ne 0 ]; then
        logger "[GIT] Directory ~/$PROJECT does not exist on $MYDATE"
        cd ..
        exit
fi

# Pull new version from the server
git pull origin master #ssh://$NAS/~/$PROJECT
if [ $? -eq 0 ]; then
        logger "[GIT] Successfully pulled new code from $PROJECT from NAS"
else
        logger "[GIT] Unable to pull code from $PROJECT from NAS"
        exit
fi

# Build Website
export JEKYLL_ENV=production
bundle exec jekyll build  --incremental
if [ $? -eq 0 ]; then
        logger "[GIT] Successfully built website from repository $PROJECT"
else
        logger "[GIT] Jekyll returned an error on $PROJECT"
        exit
fi

# Upload to hoster
rsync -aP -e ssh /home/username/$PROJECT/_site/ $REMOTE --delete
if [ $? -eq 0 ]; then
        logger "[GIT] Successfully synced website $PROJECT with remote host"
else
        logger "[GIT] Unable to sync folder of site $PROJECT with remote host"
        exit
fi

From my outputs to the log and console, everything is in order, as far as return codes are concerned. Jekyll is updating articles, but it is not updating the overview where the articles are linked.
This is the front matter of my latest article:
---
layout: post
title: redacted
date: 2019-08-23 10:00:00
categories: gist
post_image: /images/cpp.jpg
excerpt: redacted
---

As you can see, it is not a front matter issue. The overview page in /g/index.html, which is supposed to be updated when I push a new article, is this:

  {% for post in site.categories.gist limit:20 %}

{{ post.excerpt }}

          Read

  {% endfor %}

I am at a loss why Jekyll is not updating the overview with the new article. If I look at the output, you can see that it is building the new article, but not updating /g/index.html, which it is supposed to.
This is the output I get when pushing new content:
remote:  * branch            master     -> FETCH_HEAD
remote:    39dea32..4f0ada5  master     -> origin/master
remote: Merge made by the 'recursive' strategy.
remote:  _posts/gist/2019-08-23-articlename.md | 2 +-
remote:  1 file changed, 1 insertion(+), 1 deletion(-)

remote: Configuration file: /home/username/project.git/_config.yml
remote:             Source: /home/username/project.git
remote:        Destination: /home/username/project.git/_site
remote:  Incremental build: enabled
remote:       Generating...
remote:                     done in 7.49 seconds.
remote:  Auto-regeneration: disabled. Use --watch to enable.
remote: Welcome to the lima-city SSH service.

A: Its difficult to spot the problem here, but if I understand your setup, it can be a time issue : a time difference between your development computer and your Raspberry.
In order to check this, you can change your script and tell jekyll to publish all posts, even ones with a future date.
Change : bundle exec jekyll build  --incremental note: incremental works only with jekyll serve.
To : bundle exec jekyll build  --future
If your post appears : it's a time problem.
In order to avoid this problem, you can set your timezone (see timezones list) in jekyll.
_config.yml
timezone: Europe/Paris

This will force jekyll to render depending on your original timezone and will calculate posts dates accordingly.


text:
Q: WordPress profile page is not accessed after user logs in from iframe embedded in other domain I have created a particular user role that is redirected to his/her profile page when logging in. This seems to work fine when the user logs in from the website login but is not working when doing so from an iframe embedded in a chatbot.
Having checked the browser search console as suggested below, I found the following:
Refused to display 'https://staging.xxx.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
I understand that this is a security implementation and I would therefore like to allow only the chatbot's domain to access the profile page. Any ideas on how I could achieve this?


text:
Q: Link to image in separate folder I am hoping this is a simple question.
I have a homepage where i have an image of the facebook icon.
I want that icon to link to another page called facebook.html.
this works by saying

On the facebook.html page, I am trying to set the background saying:

The html pages are in the clue_links folder and the bg images are in the clue_images folder. Does anyone know why this won't work?
Thanks

A: background-image: url("../clue_images/facebook.jpg");

A: your path for the background image is incorrect on the style. try this
background: url("../clue_images/facebook.jpg");


text:
Q: Django отображаемое имя для NULL поля Есть такой код
#models.py
class Authors(models.Model):
    name = models.CharField(max_length=30, blank=False, null=False)
    def __str__(self):
         return self.name

class Books(models.Model):
    name = models.CharField(max_length=30, blank=False, null=False)
    author = models.ForeignKey(Authors, null=True, blank=True)

Как сделать, чтобы в случае, когда author == NULL запрос Books.objects.all() значение author выводил не None, а нужный мне текст?

A: Поковырял мануалы, решение, оказывается, намного проще. Есть стандартный фильтр default_if_none. Используется в шаблоне следующим образом:
{{ book.author|default_if_none:"Не известен" }}

Если автор указан, то будет выведен он, если не указан, то выведется "Не известен".

A: 2 варианта решения:

*

*1 В template делайте проверку и вписывайте то что вам нужно

*2 Производить во вьюхе проверку и присваивать то - что вам нужно, предварительно перегнав в словарь все необходимые объекты


text:
Q: Python: Is there a way to reflectivly list all attributes of a class Given a class such as
class MyClass:
    text = "hello"
    number = 123

Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the class I am to get it's attributes for are generate using SWIG (so they are hidden in .so :) ).
So I am really looking for something equivalant to Java's [Class.getDeclardFields][1]
Any help would be appreciated, otherwise I'll have to solve this problem with SWIG + JAVA instead of SWIG + Python.

A: I usually just use dir(MyClass). Works on instantiated objects too.
edit:
I should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically.
Also it may not work on linked libraries.

A: >>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> cmath.atan
<built-in function atan>

is dirable and
open("/usr/lib/python2.6/lib-dynload/cmath.so", O_RDONLY) = 4
read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\17\0\0004\0\0\0"..., 512) = 512
fstat64(4, {st_mode=S_IFREG|0644, st_size=32176, ...}) = 0
mmap2(NULL, 43824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x268000
mmap2(0x26f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x6) = 0x26f000
mmap2(0x271000, 6960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x271000
close(4)

is dynamically loaded

A: Please write actual, executable code snippets; don't expect people answering your question to first fix your code.
class MyClass(object):
    text = "hello"
    number = 123

for a in dir(MyClass):
    print a


text:
Q: IEEE conference title font size I have downloaded the IEEE template for the conference - using bare_conf.tex.
My supervisor thinks that the font size of the title is big. So how can I change the title font size?

A: The default title is set using \Huge and the easiest way to change this would be to issue the updated font size within the title. That is (say)
\title{\large Bare Demo of IEEEtran.cls \\ for IEEE Conferences}

For other font size switches and their respective point sizes, see What point (pt) font size are \Large etc.?


text:
Q: Django - Access pre-existing data in mySQL database What I'm trying to do is this: I have a csv file containing some public transport data. I want to use this in my Django app, so I imported the csv to my mySQL database. Then, I created a Django model for the table (I also compared my model against the output of python manage.py inspectdb to make sure it was correct. Then I ran python manage.py makemigrations and finally python manage.py migrate. From what I understand (and I am new to Django, so sorry if I've missed something obvious), the table in my database should now be accessible to Django.
It's not working though. I've tried using the Django shell (python manage.py shell) and returning the table contents with Stops.objects.all(), which returns an empty set. Similarly, I was able to make a HttpResponse with the value of Stops.objects.all() and, though it didn't give an error, no data was returned. I've confirmed that I'm accessing the correct database in settings.py, and that the data is in fact there via mysql terminal.
I've been trying to fix this for ages, but haven't found any solutions. I think there's probably some small step I've missed out, that hopefully someone here will know. Thanks in advance!

A: If I were you, I would verify my tables are named as expected.
Using MySQL, something like
USE mydb
SHOW TABLES;

I assume your django tables will be using the default naming scheme of f"{app_label}_{model}" so if your app is named "my_app" and your model is "stops" then you can expect django to be managing a table named "my_app_stops"
You can verify this with the django shell
$ ./manage.py shell
from my_app.models import Stops
Stops._meta.db_table

I hope this helps. Without more information, I can only show you how to investigate the most obvious flaw.
EDIT
If you do identify that this is the discrepancy, you have a couple of options:
(1) Rename your table to match Django, or
(2) Force django to look at your existing table using a Meta class
from django.db import models
class Stops(models.Model):
    class Meta:
        db_table = 'some_table_name'


text:
Q: stop junit class from autodeploying I am testing my eclipse web project on Jboss which I have set up in an integrated environment in Eclipse.
I have set the hot-deploy flag to yes, for development reasons.
However since the junit branch is under the same source tree, my server keeps restarting when I change my unit tests.
Is there any way to ignore a folder under src?
Thanks.

A: Put your unit tests in a separate source folder named tests.


text:
Q: reading a file from text file using numpy I have a text file which is rather simple, I want to read this using numpy.I need to read the numbers in the rows with more than 2 columns where the line doesn't start with a "#".
   12

 C     0.000000     0.000000     0.000000
 C     0.000000     0.000000     1.400000
 C     1.212436     0.000000     2.100000
 C     2.424871     0.000000     1.400000
 C     2.424871     0.000000     0.000000
 C     1.212436     0.000000    -0.700000
 H    -0.943102     0.000000     1.944500
 H     1.212436     0.000000     3.189000
 H     3.367973     0.000000     1.944500
 H     3.367973     0.000000    -0.544500
 H     1.212436     0.000000    -1.789000
 H    -0.943102     0.000000    -0.544500

I have tried the following code:
import numpy as np
class mol:

import numpy as np
class mol:

    def __init__(self):
        self.masses = {'H': 1, 'D': 2, 'C': 12, 'O': 16}

    def read_xyz(self, filename):
        self.filename = filename
        with open(self.filename) as f:
            for line in f:
                if not line.startswith("#") and len(line.split())>3:
                    print np.loadtxt(line)

if __name__ == "__main__":
    test = mol()
    test.read_xyz('benz.xyz')

but my code crashes and if I print the line I get an empty line between the each row I dunno why.
Any help will be great!

A: I would suggest you to use a regex instead, something like:
import numpy as np
class mol:

    def __init__(self):
        self.masses = {'H': 1, 'D': 2, 'C': 12, 'O': 16}

    def read_xyz(self, filename):
        self.filename = filename
        regexp = r'\s+\w+' + r'\s+([-.0-9]+)' * 3 + r'\s*\n'
        data = np.fromregex(self.filename, regexp, dtype='f')
        print(data)

if __name__ == "__main__":
    test = mol()
    test.read_xyz('benz.xyz')

In this case, I obtained:
[[ 0.        0.        0.      ]
 [ 0.        0.        1.4     ]
 [ 1.212436  0.        2.1     ]
 [ 2.424871  0.        1.4     ]
 [ 2.424871  0.        0.      ]
 [ 1.212436  0.       -0.7     ]
 [-0.943102  0.        1.9445  ]
 [ 1.212436  0.        3.189   ]
 [ 3.367973  0.        1.9445  ]
 [ 3.367973  0.       -0.5445  ]
 [ 1.212436  0.       -1.789   ]
 [-0.943102  0.       -0.5445  ]]

You need to modify the regex if you want to keep the first column with the character.


text:
Q: POST request Not returning DATA to Express i.e. to server I have a form validation for Email and Password if that matches it will replace with some other code and shows the Email and password in serverconsole. Flow of program is onclick() of submit it goes go to main.js and executes newFunction() it returns POST data to server i.e Server.js and replace the html content.But in my case the /Login url is handled but the email and password are not entering to my if condition in Server.js*
if( emailid == 'abc@g.com' && password == '123' )
        {
         console.log('Success'+emailid+password);
        }
I have tried all the POST request handlers but it is not working.
 Home.html
     `

                <button class="btn btn-primary btn-lg btn-block active" type="button" data-toggle="collapse" data-target="#existingUser" aria-expanded="false" aria-controls="existingUser">
                    Existing User

                </button>

                            Hello Arkodian Please Log in.
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                ×
                            </button>

                        <form>

                                Email address
                                <input  type="email" class="form-control" id="LoginEmail" aria-describedby="emailHelp" placeholder="Enter email" data-toggle="tooltip" data-placement="top" title="Email Id" required>
                                We'll never share your email with anyone else.

                                Password
                                <input  type="password" class="form-control" id="LoginPassword" placeholder="Password" required>

                            <button onclick="newsFunction()" id="Login" class="btn btn-primary">Submit</button>
                        </form>

`

main.js
  function newsFunction() {
     var Request = new XMLHttpRequest();
     Request.onreadystatechange = function(){
      if (Request.readyState == XMLHttpRequest.DONE){
        if (Request.status == 200){
             let  loginHtml = Request.responseText;
             let  ul = document.getElementById('Loginchange');
             ul.innerHTML =loginHtml ;
             console.log(loginHtml);
           }
       }
     };

     Request.open('POST', '/Login', false);
     Request.send({
        extid: document.getElementById('LoginEmail'),
        extpsd:document.getElementById('LoginPassword')
       });
    }

Server.js
 var express = require('express');
 var bodyParser = require('body-parser');
 var app = express();
 app.use(bodyParser.urlencoded({extended :false}));
 app.use(bodyParser.json());

 app.post('/Login',function(req,res){
   var emailid = req.body.extid;
   var password = req.body.extpsd;
    if( emailid == 'abc@g.com' && password == '123' ){
        console.log('Success'+emailid+password);
      }
    else {
       console.log('user not found');
      }
    var loginHtml = `<p>Hello World</p>`
    res.status(200).send(loginHtml);
 });

A: Try something like this stringify the data object and add header "Content-Type": "application/json
function newsFunction() {
     var Request = new XMLHttpRequest();
     Request.onreadystatechange = function(){
      if (Request.readyState == XMLHttpRequest.DONE){
        if (Request.status == 200){
             let  loginHtml = Request.responseText;
             let  ul = document.getElementById('Loginchange');
             ul.innerHTML =loginHtml ;
             console.log(loginHtml);
           }
       }
     };

     Request.open('POST', '/Login', false);
     Request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
     Request.send(JSON.stringify({
        extid: document.getElementById('LoginEmail').value,
        extpsd:document.getElementById('LoginPassword').value;
       }));
    }

A: It got worked when I added .value to the JSON object.


text:
Q: Undefined reference to _rpoly_ while linking C++ program with Fortran library I've compiled the netlib implementation of the Jenkins and Traub rpoly formula for finding the zeros of a real polynomial) into a library as follows
f77 -c toms493.f
ar r rpoly.a toms493.o

Next I tried to compile and link the following C++ program with rpoly.a
extern "C" void rpoly_( double *op_ , int* degree_ , double* zeror_ , double* zeroi_ , bool* fail_ );

int main()
{
    bool fail;
    int degree = 2;
    double zeror[2] , zeroi[2];
    double op[] = {1 , -5 , 6};     // x^2 -5x + 6

    rpoly_( op , &degree , zeror , zeroi , &fail );
    return 0;
}

Done as follows
 g++ Foo.cpp -L /path/to/rpoly.a

But I got the linker error undefined reference to _rpoly_
This is perticularly odd since the name _rpoly_ appears in rpoly.a, as the command nm rpoly.a shows
toms493.o:
00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
0000186c T _calcsc_
         U _exp
00000cc5 T _fxshfr_
00001090 C _global_
         U _log
00001c64 T _newest_
00001ab2 T _nextk_
00001eb5 T _quad_
00001117 T _quadit_
00001e0b T _quadsd_
0000208d T _r4_epsilon__
0000207a T _r4_huge__
0000150e T _realit_
00000000 T _rpoly_

A: The command line invocation of g++ is incorrect.  The -L option specifies a directory to search for libraries specified via an -l option.
You could simply delete -L and then the command line will specify the library directly.
gcc foo.cpp /path/to/rpoly.a


text:
Q: setRecycledViewPool method in RecyclerView I am trying to understand what the setRecycledViewPool method actually does along with the RecyclerView in the following line of code where mrecyclerView is a RecyclerView object:
mrecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());

I read the Android documentation link and I still don't understand what it does clearly. Can someone explain to me its use and when to use it?

A: When the RecyclerView is expected to show more than 5 views on the screen at the same time (5 is the current default), it's recommended to enlarge it to what you think will be the max. This will allow to do an actual recycling (the purpose of RecyclerView...) when scrolling, to avoid re-creation of Views.
In fact, because I actually think that it's almost never known how many will be be shown on the screen (different screens resolutions, etc...) , I think it's best to just set it to be the max :
fun RecyclerView.setMaxViewPoolSize(maxViewTypeId: Int, maxPoolSize: Int) {
    for (i in 0..maxViewTypeId)
        recycledViewPool.setMaxRecycledViews(i, maxPoolSize)
}

Usage:
    recyclerView.setMaxViewPoolSize(MAX_TYPE_FOR_THE_ADAPTER_YOU_MADE, Int.MAX_VALUE)

I personally don't understand why it's not the default behavior. The whole point of using a RecyclerView is to recycle the Views. When scrolling, it should, by default, recycle views that were just used.

A: setRecycledViewPool(...) can be useful when we have a nested RecyclerView. See this blog post for details. A short description of the same link is added here.
Consider a case where you have a nested RecyclerViews and inner RecycleViews share the same view structure. RecycledViewPool provides a seemless way to share views between these inner (nested) RecyclerViews.
An example of such case could be seen in the following image:

As you can see the types of views for both lists are same.

A: I haven't used it myself, but from what I can understand reading the docs its a way to use views you recycle in one RecyclerView with another.
So if you have a RecyclerView with a bunch of decked out CardViews, and you would like to recycle those same views for another RecyclerView you could pass it a shared RecycledViewPool. Now both RecyclerView will take from the shared view pool.

A: From docs:

Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. This can be useful if you have multiple RecyclerViews with adapters that use the same view types, for example if you have several data sets with the same kinds of item views displayed by a ViewPager.

By default, 5 ViewHolders are retained in the pool for a particular viewType. If you want to change that count, it may be done this way:
recyclerView.getRecycledViewPool()
            .setMaxRecycledViews(SOME_VIEW_TYPE, POOL_CAPACITY);

From this blog post:

So how do we choose the optimal size of the pool? It seems that the optimal strategy is to extend the pool right before you'll need it to be big, and shrink it right afterwards. One dirty way to implement this is the following:

recyclerView.getRecycledViewPool().setMaxRecycledViews(0, 20);
adapter.notifyDataSetChanged();
new Handler().post(new Runnable() {
    @Override
    public void run() {
        recyclerView.getRecycledViewPool()
                    .setMaxRecycledViews(0, 1);
    }
});


text:
Q: How to convert Calendar to JSON I'm development a rest application like this
@XmlRootElement
@Entity
@Table(name = "tb_verarq")
public class Verificacao implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ultima_verificacao")
    private Calendar dataHoraUltimaVerificacao;
}

On XML will see this:
 <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <verificacao>
  <dataHoraUltimaVerificacao>2017-04-04T20:57:46.490-03:00</dataHoraUltimaVerificacao>
  <id>1</id>
  </verificacao>

But in my web page only appears a number

update
this is my Angular
var professoresModulo = angular.module('arquivocopemModulo',[]);

professoresModulo.controller("arqcopem-controller", function($scope,$http){

    urlVerificacao="http://localhost:8080/monitoriabnb/rest/verificacaocopem";

    $scope.buscaVerificacao  = function (){
        $http.get(urlVerificacao).success(function(verificacao) {
            console.log(verificacao);
            $scope.verificacao = verificacao;
        }).error(function(erro) {
            alert(erro);
        });
    }

    $scope.buscaVerificacao();

});

I try this but don't work either
$scope.verificacao.dataHoraUltimaVerificacao = Date.parse($scope.verificacao.dataHoraUltimaVerificacao);

I try to convert with Angular but don't work
any suggestions for me?

A: Try using momentjs which handles DATE TIME efficiently. You can modify your code as below
$scope.verificacao.dataHoraUltimaVerificacao = moment($scope.verificacao.dataHoraUltimaVerificacao, 'YYYY-MM-DD HH:mm').toDate();

You can as well convert to custom format by extracting date, month , year, hours, minutes etc using moment functions.
var dd = $scope.verificacao.dataHoraUltimaVerificacao.getDate();
var mm = $scope.verificacao.dataHoraUltimaVerificacao.getMonth();
var yy = $scope.verificacao.dataHoraUltimaVerificacao.getUTCFullYear();

return ((dd) + "/" + (mm+1) + "/" + yy);

I hope this helps....


text:
Q: Visual Studio Code disable angular auto complete can someone explain how you disable angular auto complete on visual studio code?
Cheers

A: Open the editor settings and search for the 'angular1' you will find a config:

"html.suggest.angular1": true

copy this line to user setting and edit it to:

"html.suggest.angular1": false

Angular1 suggestion will be disable.


text:
Q: Why can't I return an IPagedList to my Post action This sounds simple in theory (and it probably is)
I have a view from a Get ActionResult using @model IPagedList
As the model.
I also have a form on the view and when user clicks submit, the code jumps to the post action,
However it throws an error when I try to include IPagedList traclerlist as a parameter in the Post ActionResult.
"Cannot create an instance of an interface"
Tried ICollection and IList and get the same result ?
Any Ideas?  Need code ?
Please note this is an MVC 3 application using razor views.

A: IPagedList is an interface.  You cannot create an instance of this class.  It is designed to be a definition for a class for you to inherit from.

A: Think about what the model binder is doing. The model binder constructs instances of a class and then uses form values, etc. to populate your model. You are telling the model binder to construct an instance of an interface, which it cannot do. Is it supposed to choose a random class that implements IPagedList? How do you expect that to work?


text:
Q: Field gets radio button's item id instead of its value I have snippet:
<%= f.input :purpose, as: :radio_buttons, collection: category.subcategories,
             wrapper: :vertical_collection_inline %>

which lines values of category.subcategories horizontally how I want

The problem is, when I select either of option, it assigns that option's ID, but not its value.
How should I refactor the code?

A: Using IDs has advantages as warned in the comments, however what you're trying to do should work with either:
category.subcategories.collect(:&values)

Where values is the name of the field which hols "Rent" etc.
The more railsy way to do this is with collection_radio_buttons, like this:
f.collection_radio_buttons(:purpose, category.subcategories, :value, :value)

Again where "value" is the field name.


text:
Q: Return a document with the largest value I've got a series of documents that have a version field.
{
 "_id": "xxx",
 "_rev": "6-4bdeb530234c454ae2f16d77ba577428",
 "name": "glossary",
 "locale": "en-us",
 "version": "186.0",
 "title": "Glossary",
 ...
}

I'd like to be able to return the document where name is glossary that has the largest version.
If I make the map function like this:
function(doc) {
  emit(doc.name, doc);
  }

and do a reduce on it, I can figure out which document has the latest version, but when I try to return it (return latest_doc), I get a reduce_overflow_error error.
It seems like I need to do this via a map function only, but I can't figure out how to return a single document with the highest value from the map.
I'm sure there's an easy way to do this, but I haven't been able to figure it out.
Can you help me get the latest version of my glossary document?

A: reduce_overflow_error is couchdb's way of telling you that you are not using reduce in a way it is supposed to be used. From the wiki

Reduce is a powerful feature of CouchDB but is often misused which leads to performance problems. From 0.10 onwards, CouchDB uses a heuristic to detect reduce functions that won't scale to give the developer an early warning. A reduce function must reduce the input values to a smaller output value. If you are building a composite return structure in your reduce, or only transforming the values field, rather than summarizing it, you might be misusing this feature

Try this map function
function(doc) {
 emit([doc.name,doc.version], doc._id);

}
query it with
/view-name?include_docs=true&startkey=["glossary",{}]&endkey=["glossary"]&descending=true&limit=1
This will give you the the file with the highest version number. Remove the limit parameter if you want more files.


text:
Q: My code decompiled a strange format, how do i fix it? I have decompiled and old LUA I had, but when i read it , its not text anymore.
This lua had instructions in JSON about some settings read by my app, but i lost the source code
Ive looked on the internet for solutions and they said maybe its my decompiler version.
My code was compiled with lua(5.1.4) and I used unluac with support to 5.1.x
Could someone help me?
Here is a sample of my lua
_G["7S\241\167\161\130\229\224\217J\017]\2204?\172"] = {
  ["\000\014\229\130\208\191%7\224\226Q\145\203\165I\142"] = {
    ["%7\188\003\019s\237\136\155\221\162\015}*QV"] = "\253\020N\161\192\021\238[<\138\020\248\244\171=\138\148\142\230\a\015_D\219CGq\vP\028?&",
    ["tq\204\255\175$l\223\197\219\216\149\248\206:\253"] = "9\128\227#\002\133\216\246\135\238v7\023nO\191",
    ["t\184.\b\030\155Y(\204?dO\131\182\222\129"] = "\001\165\249\154\2184k\a\151\150\028_\025=\173\134",
    ["\169\127\159\172\206\018r3\233\191\160\006\173\\\020\166"] = "\197g{\218\001\"&\169\170|/\233$\190\220T",
    ["\174\006\v9\251\220`^\1280\171\190\r\185\222\238"] = " t\023\019EUw\249\228\028\021N\2359;G",
    ["\197\v\026\171\188\002\233\023\031\132\253\159\223e\249\145"] = "\127\160L6\237Xze\r\194j\1933\255\245w",
    ["\214c\195\207p0\237\198\219D\129\171\243@5\210"] = "f5\001\250\164`\200\231\a\186\1582a\215D\230\026\243\022\146y\226\025\"\248\170\224\016@\240\209\143"


text:
Q: Firebase Cloud Functions increment value in Cloud Firestore on Create User I would like to use Firebase Cloud Functions to update a value inside my Cloud Firestore database everytime a new user is created. I already got my Cloud Function to log when a new user is created and it is working as expected:
const functions = require("firebase-functions");
// The Firebase Admin SDK to access Firestore.
const admin = require("firebase-admin");
admin.initializeApp();

exports.accountCreate = functions.auth.user().onCreate((user) => {
  console.log(user.data);
});

Now I want to increment a value inside my Firestore (path: data/userCounter, field: userCounter).
But how I have no idea how I can do that. I know  the best way to do this is to use the new increment() method from Firebase. But how exactly do I implement that in my example? I am absolutely new to Cloud-Functions and JS...
Any help is appreciated. I couldn't find an exact example that is like my case. Let me know if you need any more info!


text:
Q: CSS - Evenly distributed navigation bar I'm trying to evenly distribute the navigation bar so it spreads across the entire page as opposed to leaving a gap towards the right hand side as it is currently doing.
How would I be able to achieve this with CSS?
HTML

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        Toggle navigation

        </button>

Find Your Home

About Us

Helping You Move

News

Get in Touch

CSS
/* Navigation
-------------------------*/
.navbar-default {
    background-color: #002e5d;
    border-radius: 0;
    font-size: 18px;
}

#toggle-navbar {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 100px;
    line-height: 95px;
    font-size: 2em;
    font-weight: 900;
    color: #fff;
    text-align: center;
    background: #ffcd00;
}

#toggle-navbar:hover {
  cursor: pointer;
}

.navbar {
    border-radius: 0;
    border: none;
    margin-bottom: 0;
}

.navbar-default .navbar-nav li {
    padding: 0 32px;
    height: 40px;
    margin: 10px 0;
}

.navbar-default .navbar-nav li:not(:last-child) {
    border-right: solid 1px #FFF;
}

.navbar-default .navbar-nav li a {
    color: #FFF;
    padding: 10px;
}

.navbar-default .navbar-nav li a:hover, .navbar-default .navbar-nav li a:focus {
    color: #e8e8e8;
}

.navbar-collapse {
    display: table;
    float: right;
    height: auto !important;
    max-height: none;
    overflow: hidden;
    padding: 0;
    position: relative;
}

.navbar-collapse.in {
  overflow: hidden;
}

.navbar-default .navbar-toggle .icon-bar {
    background-color: #FFF;
}

.navbar-default .navbar-toggle {
    border-color: #FFF;
}

.navbar-default .navbar-toggle .icon-bar:hover {
    background-color: #FFF;
}

.navbar-default .navbar-toggle:focus, .navbar-default .navbar-toggle:hover {
    background-color: #1b66b2;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:focus, .navbar-default .navbar-nav>.active>a:hover {
    background-color: #1b66b2;
    color: #FFF;
}

.navbar .current_page_item {
    background: #1b66b2;
    border-right: none !important;
    height: 60px !important;
    margin: 0 !important;
    font-weight: 700;
}

.navbar .current_page_item:not(:first-child) {
    margin: 0 -1px !important;
}

.navbar .current_page_item a {
    line-height: 40px !important;
}

.menu-main-menu {
    font-size: 17px;
}

I've made a jsfiddle: https://jsfiddle.net/xfj7ummm/

A: The default Bootstrap styles do not support your desired behavior, so you will want to overwrite a couple of them.  For ease, and to prevent these new styles from (potentially) affecting other elements, I have added an id field to your navbar:

I then overwrite the unwanted styles with my own:
#myNavbar {
    float: none;
}
#myNavbar > .navbar-collapse {
    float: none;
}
#menu-main-menu {
    float: none;
    text-align: center;
}
#menu-main-menu > li {
    float: none;
    display: inline-block;
}

As you can see in this jsfiddle update, the navigation tabs are now centered on the page.

A: To evenly distribute your links you can use display:table for the navbar and display:table-cell for the li which I would use inside a media query above 768px to avoid altering the navigation on mobile viewports.
There are also some media queries added to compensate for the font-size and length of the link titles.
*You also have some inconsistencies with your HTML. Your closing navbar-header div should be before .navbar-collapse not after.
See example Snippet at Full Page.

.navbar.navbar-default {
  background-color: #002e5d;
  border-radius: 0;
  font-size: 18px;
}
.navbar.navbar-default .navbar-nav > li > a {
  color: #fff;
}
.navbar.navbar-default .navbar-nav > li > a:hover,
.navbar.navbar-default .navbar-nav > li > a:focus {
  color: #e8e8e8;
}
.navbar.navbar-default .navbar-nav > .active > a,
.navbar.navbar-default .navbar-nav > .active > a:focus,
.navbar.navbar-default .navbar-nav > .active > a:hover {
  background-color: #1b66b2;
  color: #FFF;
}
.navbar.navbar-default .current_page_item {
  background: #1b66b2;
  font-weight: 700;
}
.navbar.navbar-default .navbar-toggle .icon-bar,
.navbar.navbar-default .navbar-toggle .icon-bar:hover {
  background-color: #fff;
}
.navbar.navbar-default .navbar-toggle {
  border-color: #fff;
}
.navbar.navbar-default .navbar-toggle:focus,
.navbar.navbar-default .navbar-toggle:hover {
  background-color: #1b66b2;
}
@media (max-width: 991px) and (min-width: 768px) {
  .navbar.navbar-default .navbar-nav > li > a {
    padding-left: 5px;
    padding-right: 5px;
    white-space: nowrap;
  }
}
@media (min-width: 768px) {
  .navbar.navbar-default .navbar-nav {
    margin: 0;
    display: table;
    width: 100%;
  }
  .navbar.navbar-default .navbar-nav > li {
    display: table-cell;
    float: none;
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .navbar.navbar-default .navbar-nav > li > a {
    text-align: center;
  }
  .navbar-default .navbar-nav li:not(:last-child) {
    border-right: solid 1px #FFF;
  }
  .navbar.navbar-default .navbar-header .navbar-brand {
    display: none;
  }
}
@media (max-width: 767px) {
  .navbar.navbar-default {
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .navbar.navbar-default .navbar-collapse {
    border: none;
    box-shadow: none;
  }
  .navbar.navbar-default .navbar-header .navbar-brand {
    color: #fff;
    font-size: 28px;
    font-weight: bold;
  }
}
@media (max-width: 360px) {
  .navbar.navbar-default .navbar-header .navbar-brand {
    font-size: 24px;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-ex1-collapse" aria-expanded="false"> Toggle navigation

      </button>Find Your Home

Find Your Home

About Us

Helping You Move

News

Get in Touch


text:
Q: Is any non-singular positive semidefinite matrix positive definite? Consider the following problem. (The question and the reasoning remains identical if negative is replaced by positive everywhere.)

Suppose A is an $n\times n$ symmetric matrix with distinct eigenvalues. Suppose further that A is non-singular and negative semidefinite. Is A a negative definite matrix?

*

*A is symmetric, so all its Eigenvalues are real.

*A is non-singular, so all of its Eigenvalues are non-zero.

*A is negative semidefinite, so all of its Eigenvalues are non-positive.

Combining 2 and 3, A is negative definite.
My question is, what is the significance of the fact that all Eigenvalues are distinct in the context of this question? Am I missing something?
Thanks in advance.

A: There is no significance of the fact that all eigenvalues are distinct in the context of this question; it is a superfluous hypothesis. A symmetric real matrix is always diagonalisable, whether or not its eigenvalues are distinct.
Maybe a failed attempt to put the student at ease by giving a supposedly reassuring hypothesis?


text:
Q: Volume inside loop using Green's theorem. Let $\mathcal{C}$ be the curve defined by the vector function $\vec r(t)=(1-t^2)\vec i+(t-t^3)\vec j$ with $t\in \Bbb R$. I need to find the area confined in the closed loop $\gamma$ formed by $\mathcal{C}$, using Green's theorem.
$\gamma$ is smooth, closed, simple and arbitrarily oriented counter clockwise, so :
$$\int\int_DdA=\frac{1}{2}\oint_\gamma xdy-ydx$$
We have : $\begin{cases}
x=1-t^2\\
y=t-t^3
\end{cases}$
And by the figure I have of the curve (I don't know how we could plot it otherwise), I can tell that the loop starts at $(0,0)$ and ends at $(1,0)$ so that $t\in[0,1]$.
Which leads to :
$$\int\int_DdA=\frac{1}{2}\oint_{0}^{1} ((1-t^2)(1-3t^2)-(t-t^3)(-2t))dt$$
$$=\frac{1}{2}\oint_{0}^{1} (t^4-2t^2+1)dt=4/15$$
I think this was simple enough and that I got it right. However, now, knowing this result, I must calculate the following integral :
$$\oint_{\gamma}\sqrt{1+x^3}dx+2xdy$$
We know that, as per Green's theorem, it can be rewritten as :
$$\int\int_D\Big(\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}\Big)dA=\int\int_D(2-0)dA$$
Sweet, the root vanishes ! But I don't know how to define domain $D$.
Here is a figure of domain $D$ :

Any help would be much appreciated. Thanks !

A: There are two values of t that give the origin for that parameterization: t =-1 and t =1. I believe if you just evaluate the line integral with those limits you'll get the area inside the closed part of the curve.

A: We have the curve $C$ defined parametrically as
$$\begin{align}
\vec r(t)&=\hat xx(t)+\hat yy(t)\\\\
&=\hat x(1-t^2)+\hat yt(1-t^2)\\\\
&\implies x(t)=1-t^2\,\,\text{and}\,\,\,y(t)=t(1-t^2)\tag 1
\end{align}$$
for $t\in [0,1]$.

NOTE:
For $t\in[0,1]$, we see that $y$ is greater than $0$.  The closed curve $\gamma$ is formed by two parts; (i) the curve $C$ defined by the aforementioned parameterization and (ii) the line segment $C_x$ along the x-axis from $(0,0)$ to $(1,0)$.  However, we note that on the line segment, $y=0$ and $dy=0$ and the contribution from the integration over $C_x$ is zero.  We therefore have$$\oint_{\gamma}(xdy-ydx)=\int_{C}(xdy-ydx)+\int_{C_x}(xdy-ydx)=\int_{C}(xdy-ydx)$$

Now, using the first relationship in $(1)$ we find that
$$t^2=1-x \tag 2$$
while using both relationships in $(1)$ simultaneously we find that
$$t^2=(y/x)^2 \tag 3$$
Noting that the right-hand sides of $(2)$ and $(3)$ are equal reveals
$$y^2=x^2(1-x)$$
We recall that $t\in[0,1] \implies x\in[0,1]\,\,\text{and}\,\,y\ge0$.
Thus, the area $A$ inside the region bounded by $y=0$ and $y= x\sqrt{1-x}$ is given by
$$\begin{align}
A&=\int_0^1\int_{0}^{x\sqrt{1-x}}dydx\\\\
&=\int_0^1\,x\sqrt{1-x}\,dx\\\\
&=-\frac{2}{3}\left.x(1-x)\right|_0^1+\frac23\int_0^1\,(1-x)^{3/2}\,dx\\\\
&=-\frac23\,\frac{2}{5}\,\left.(1-x)^{5/2}\right|_0^1\\\\
&=\frac{4}{15}
\end{align}$$
as expected!!


text:
Q: Reading data from Excel in Haskell I would like to get data from .xls files without manually opening Excel.
One possibility is to use COM automation.
There are the com-1.2.3 and hdirect packages, but I can't find any examples of how to use these packages with Excel.
Does anyone have a solution for this?

A: With something like this, if your needs are relatively simple, I've found that it's more straightforward to find/write a command line executable that just pulls out a csv from the xls file. Then you invoke that executable from haskell, and proceed with its output from there.

A: In Ruby, I use rjb (ruby java bridge) and use a library from Java for excel (e.g. JExcelAPI as explained in http://www.slideshare.net/weyus/rjb).
It seems that there are some Java bridges for Haskell? http://www.haskell.org/haskellwiki/Applications_and_libraries/Interfacing_other_languages#Java
Though I have no experience with them...
I wonder whether that's the best solution...

A: Now there is also xlsx on Hackage (for the Office Open XML xlsx format), although I haven't yet tried it myself.


text:
Q: How to find minimum$(|a_n|+|a_{n-1}|+\cdots+|a_0|)$ if $f(x)=0$ has at least one root $x\in (0,r)$? Let $f(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots+a_0,a_i\in\mathbb Z,n\in\mathbb N.$
How to find minimum$(|a_n|+|a_{n-1}|+\cdots+|a_0|)$ if $f(x)=0$ has at least one root $x\in (0,r)$?
(For example, $r=10^{-10}$)
How about if we need all the roots of $f(x)=0$ are real numbers? Thanks in advance!


text:
Q: Real sequences, proof with banach space theory Can someone help me with this?
Let $(x_n)$ be a real sequence, and suppose that $\sum_{i=1}^{\infty} x_i y_i$ does converge for every real sequence $(y_n)$ such that $lim_{n \to \infty} y_n =0$.
Prove that $\sum_{i=1}^{\infty} |x_i|< \infty$
I've found this exercise in a banach space chapter, but a purely calculus proof would be good aswell.

A: Equivalently, RTP that if $\sum_{n\in \Bbb N}|x_n|=\infty$ then there exists a sequence $(y_n)_{n\in \Bbb N}$ converging to $0$ such that $\sum_{n\in \Bbb N} x_ny_n$ does not converge.
Notation: $sgn(x)=|x|/x$ if $x\ne 0$ and $sgn(0)=0.$ (Latin: signum.)
If $\sum_{n\in \Bbb N}|x_n|=\infty $ then there exists a strictly increasing sequence $(M_j)_{j\in \Bbb N}$ of natural numbers with $M_1=1$ and such that for every $j$  we have $$\sum_{n=M_j}^{M_{j+1}-1}|a_n|\geq 1.$$
For $M_j\leq n < M_{j+1}$ let $y_n=j^{-1}sgn (x_n).$ Then $\lim_{n\to \infty}y_n=0$. Since $x_ny_n\geq 0$ for all $n,$ we have  $$\sum_{n=1}^{\infty}x_ny_n=\sum_{j=1}^{\infty}\sum_{n=M_j}^{M_{j+1}-1}x_ny_n=\sum_{j=1}^{\infty}j^{-1}\sum_{n=M_j}^{M_{j+1}-1}|x_n|\geq \sum_{j=1}^{\infty}(1/j)=\infty.$$


text:
Q: TKINTER: I can't copy a string output I created a simple GUI application that returns a string after taking a user input. I want to be able to copy the string once it's printed on the GUI but I can't, I think it's because initally I used Label:
d = 'some string that I want to copy'
data = Label(main, text=d)
data.pack()

I tried doing Text instead so that I can copy the output from a text box but I keep getting this error message:
bad wrap "some string that I want to copy" must be char, none, or word.
code:
data = Text(main, wrap=d)
data.pack()

A: This works?
from tkinter import  *
main = Tk()

d='This is the input'

data = Label(main, text=d)
data.pack()

main.mainloop()

All though it would help if you posted your full code

A: The wrap option takes one of the following three strings: word, none, or char.  You're passing something else.
If your goal is to insert the value of d in a text widget, you must use the insert method after creating the widget:
data = Text(main, wrap="word")
data.insert("end", d)


text:
Q: How to print ring type output in c? I have c program problem to print the ring type output.
When user enter the number 5, then program output is look like;
1     2      3     4    5
16    17    18    19    6
15    24    25    20    7
14    23    22    21    8
13    12    11    10    9

I use following logic but i really failed i not have any idea.
 int main()
    {
        int a[50],i,j=0,n,k;
        printf("Enter the number=");
        scanf("%d",&n);

        for(i=1;i<=n;i++)
        {

            if(i>n)
            {
                j=j+5;
            }
            else if(i>((2*n)-1))
            {
                j--;
            }
            else if(i>((3*n)-2))
            {
                j=j-5;
            }
            else if(i>(4*n-4))
            {
                j++;
            }
        }
    }

Sorry for asking whole program logic but
,I really dont have any idea,Please help me.....

A: A simple way to solve this problem is to allocate an array of size N*N and to populate it with a straight forward loop that follows the spiral.  Then you can print the array contents N elements per row.

A: here's what you are looking for
#include <stdio.h>

#define max 25

int main()
{
    int spiral[max][max] = {{0}}; // initializing array with 0
    int r, c, i = 0, j = -1, count = 1;

    printf("\nEnter the row and column for spiral matrix:\n");
    scanf("%d%d", &r, &c);

    while (count <= r * c)  // this loop executes till all the blocks of
    {
        // array r*c are filled with 0
        while (j < c - 1) // Filling the location from left to right
        {
            // with value of variable count
            if(spiral[i][j+1]!=0)  // Here we are checking if that location
                break;                 // is already occupied
            spiral[i][++j] = count++;
        }

        while (i < r - 1)    // Filling the location from top to bottom
        {
            if (spiral[i+1][j] != 0)
                break;
            spiral[++i][j] = count++;
        }

        while (j > 0)     // Filling the location from right to left
        {
            if(spiral[i][j-1] != 0)
                break;
            spiral[i][--j] = count++;
        }

        while (i > 0)       // Filling the column from bottom to top
        {
            if (spiral[i-1][j] != 0)
                break;
            spiral[--i][j] = count++;
        }
    }

    for (i = 0 ; i < r ; i++)
    {
        for (j = 0 ; j < c ; j++)
        {
            printf("%3d",spiral[i][j]); // print the matrix
        }
        printf("\n");
    }
    return 0;
}

reference is here from more details


text:
Q: create list of objects and present them as tiles Right now I have this being produced

I want them to be next time to each like a 3x3 cube
The below code is generating the stuff in the image.

@foreach (var m in Model.FilteredMatches)
{

@m.Username

@m.Age year old @m.Gender.WhatGender | Seeking

@m.City, @m.State.Name,@m.State.Country.Name

 }

I am also not sure why bootstrap isnt placing the span next to eachother.

A: You have a bunch of divs, which are block elements and will not display next to each other by default. You can give these a width, and then add float: left; to your CSS. Your other option is to actually change your divs to spans.

A: @foreach (var m in Model.FilteredMatches)
{

@m.Username

@m.Age year old @m.Gender.WhatGender | Seeking

@m.City, @m.State.Name,@m.State.Country.Name

}

Added pull-left to the top div in the above code and it did exactly what I wanted it to do.


text:
Q: black berry web works i am using webworks tool for devolepping a web application in blackberry... the jquery  command $.getJSON is not working in it .. please help me by giving a good solution for that

A: Check the BlackBerry Support Community Forums, I think PlayBook Webworks cannot read local files will help.


text:
Q: SMS handling with regards to Priority settings and Ordered vs. Unordered Broadcast I'd like to ask questions related to handling of android.provider.Telephony.SMS_RECEIVED.
Q:

Is android.provider.Telephony.SMS_RECEIVED an ordered or non-ordered
  broadcast? Where is the official documentation to identify whether is
  a non-ordered or ordered broadcast?

<receiver android:name="com.nttdocomo.android.msg.chats.SmsReceiver">
            <intent-filter android:priority="10">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Q:

With reference to the above code where the priority is set to "10". Is
  it possible for another SMS app to hijack my app, by setting to "11"
  or any higher value, to change the SMS message context or even delete
  it so it would never reach my app?

Q:

if I set to highest possible priority - ie.
  'android:priority="2147483647" ' - and what happens if yet another app
  also set to the same highest priority "2147483647"?

Thanks!


text:
Q: How can I get my system to boot after cloning used Macrium Reflect? I got a new SSD and I was trying to migrate my OS from my HDD to my new SSD and I ran into a problem: The PC didn't want to boot from the new SSD even after changing the boot sequence and running the boot fix from the USB flash drive that I created earlier using Macrium Reflect.
But when I was looking online I found that for most people, the system disk is only 100MB-ish size.
So I figured I might have messed things up during my Windows 10 installation, is there any way to fix this without messing it up even more?
Macrium Reflect interface:

Diskpart results:

A: To make a disk bootable, you need to clone everything.
Most serious cloning software AOMEI adjust for different disk sizes.
Macrium probably does it, and
AOMEI Backupper Freeware.


text:
Q: Pegar o diretório do executável e salvar imagem em uma pasta dentro deste diretório Eu precisava pegar o caminho do executável e salvar em uma pasta dentro do diretório raiz onde está o ".exe", servindo tanto na programação do arquivo na pasta "bin" e "debug" quanto na hora de criar o instalador com o "inno setup" e abrir em qualquer pasta designada pelo usuário na hora de instalar o arquivo. Está pegando o nome do arquivo e salvando no formato "bmp" mas não está funcionando a parte de pegar e salvar a pasta no diretório do executável vejam o meu código abaixo;
 string pastaimagem = "imagem";
 string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
 Bitmap bmp = new Bitmap(openFileDialog1.FileName);
            Bitmap bmp2 = new Bitmap(bmp, pictureBox2.Size);
            pictureBox2.Image = bmp2;
            string pasta = appPath + pastaimagem;
            if (!Directory.Exists(pasta))
            {

                Directory.CreateDirectory(pasta);

            }

            pictureBox2.Image.Save(pasta + txtCod.Text + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);

A: Para pegar o caminho do diretório tanto no debug ou quando o programa já estiver rodando em algum PC use o comando a seguir:
System.Environment.CurrentDirectory

Ex: txtCaminhoRaiz.Text = System.Environment.CurrentDirectory;