text:
Q: Text not showing in sidebar in Chrome / Safari Text in the sidebar is not showing on load in Chrome or Safari at www.signinblue.com/blog. Once you inspect the element in Chrome the text shows up. The sidebar displays perfectly in IE7+ and Firefox.
I was previously using Cufon, which I thought was the issue, however, I have removed the Cufon .js and the problem persists.
I have also displayed inline throughout multiple elements to make sure there was nothing hiding the element.

A: You need to specify position:
#secondary {
  position: relative;
  float: right;
  margin-right: 7.6%;
  width: 18.8%;
}

A: It's a nesting issue; as the primary div is set to width="100%" it overlaps the secondary div.
Currently the sections are nested as:

Here's the nesting I have used in the Chrome developer tools, this works fine for me:


text:
Q: Eloquent query on relationship table Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
    protected $table = "Adressen";
    protected $primaryKey = 'Adresse';
    public $timestamps = false;

    public function scopeSearchAdress($query, $searchTerm)
    {
        return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
                     ->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
                     ->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
    }

    public function kontokorrent()
    {
        return $this->hasOne(Kontokorrent::class, 'Adresse');
    }
}

Kontokorrent Model
class Kontokorrent extends Model
{
    protected $table = "Kontokorrent";
    protected $primaryKey = 'Adresse';
    public $timestamps = false;

    public function scopeSearchKto($query, $searchTerm)
    {
        return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
    }

    public function adress()
    {
        return $this->belongsTo(Adress::class, 'Adresse');
    }
}

Controller
class AdressesController extends Controller
{
    public function index(Request $request)
    {
        $searchTerm = $request->input('searchTerm');

        $adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
            $query->where('KtoArt', 'D')
                  ->searchKto('K75688'); // this is working
                  // -> searchKto($searchTerm); this is NOT working
        })->orderBy('Name1')
        ->searchAdress($searchTerm)
        ->paginate(60);

        return view('adresse.index', compact('adresses', 'searchTerm'));
    }
}

The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
@section('content')

        <form role="search" method="GET" action="/adresses">

                <input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">

                    <button type="submit" class="btn btn-search btn-default">
                       Suchen...
                    </button>

        </form>

                    #
                    Name
                    Straße
                    Ort
                    PLZ
                    Land

                @if(count($adresses) > 0)
                    @foreach($adresses as $adress)

                            {{ $loop->iteration }}

                                Adresse}}">{{$adress->Anrede}} {{ $adress->Name1}}
                                @if($adress->kontokorrent)
                                {{ $adress->kontokorrent->Kto }}
                                @endif

                            {{ $adress->LieferStrasse }}
                            {{ $adress->LieferOrt }}
                            {{ $adress->LieferPLZ }}
                            {{ $adress->LieferLand }}

                    @endforeach
                @else

Kein Eintrag gefunden.

                @endif

{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
@endsection

I don't understand why I get an empty table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: zsh: permission denied (MacOS) I am trying to use a tool from Openai (train a data model).
I installed openai and now try to execute this command:
/Users/finnborchers/Library/Python/3.8/lib/python/site-packages/openai tools fine_tunes.prepare_data -f /Users/finnborchers/Desktop/Code/GPT3_Training_data/training.jsonl

I get this error:
zsh: permission denied: /Users/finnborchers/Library/Python/3.8/lib/python/site-packages/openai

I had the same problem from this article, but now I am stuck:
openai command not found (mac)
I am new to the terminal commands, but here is the output of echo $PATH:
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Users/finnborchers/Flutter_api/flutter/bin

To allow execution I tried this command:
sudo chmod +x /Users/finnborchers/Library/Python/3.8/lib/python/site-packages/openai

But then nothing happens (There is no feedback message) and I still get the permission denied message.
Maybe the chmod did not work because of the PATH?
I am thankful for any help!

A: Solution: I had to run the first installation with sudo.


text:
Q: Magento 2 social share facebook messenger button? How can add url link for facebook messenger social share icon on product detail page?

Check for reference other social icons:
https://magento.stackexchange.com/questions/226323/magento-2-social-share-buttons/226332

A: Add this code in catalog_product_view.xml
<referenceContainer name="product.info.social">
    <block class="Magento\Catalog\Block\Product\View" name="product.info.socialmedia" template="Magento_Catalog::product/view/socialmedia.phtml"/>
</referenceContainer>

And Create new phtml file at following path:

app/design/frontend/Custom/theme/Magento_Catalog/templates/product/view/socialmedia.phtml

Add below code in it.
<?php $_product = $block->getProduct(); ?>

    <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($_product->getProductUrl());?>&t=<?php echo urlencode($_product->getName())?>" onclick='javascript:window.open(this.href,"","width=640,height=480,left=0,top=0,location=no,status=yes,scrollbars=yes,resizable=yes");return false' title="Share on facebook">
        <img src=""<?php echo $this->getViewFileUrl('Magento_Catalog::images/facebook-share.jpg'); ?>" alt="Facebook" width="12%">


text:
Q: How to override natural navigation in c# winforms Domain understanding
I'm making an application for dentists and at one point I have to show the teeth of the patient and allow the dentist to register information about several points around each tooth.
To make the application dynamic I create the teeth depending on the patient (some have more or fewer teeth).
So the mouth has a number of teeth and depending on the settings each tooth has a number of measurement points.
The dentists register the points in different orders depending on preference (set in settings). Some register all points on a tooth and then move to the next, others register all points along the front of all teeth and then all the points along the back of the teeth.
The issue
As I create each tooth and add the measurement points to it, the natural tab order is: all the points on one tooth, move to next tooth [repeat].
I need to control this in a different way.
I need to be able to navigate (tab) to a control in another usercontrol and then return later for the rest of the points.
Both tab and the arrow keys cause navigation, so I have to deal with both (well all navigation, but these are the ones I've discovered to far)
Trial and error
I tried to override OnKeyUp/Down/Press and handle the events for the key press, but to no avail.
In stead I get a double effect; both my navigation AND the natural navigation.
What is the smartest and easiest way to be in complete control of the navigation?

A: For Tab there is a ContainerControl function called ProcessTabKey. This is where the natural navigation for Tab happens. If you override this you can provide our own navigation: (or just return true and do it somewhere else)
protected override bool ProcessTabKey(bool forward)
{
    return forward ? this.NextPoint() : this.PreviousPoint();
}

As for the arrow-navigation, I've found that to be a little trickier. There are a number of overridable functions that register key presses.
I think the best one is ProcessCmdKey. This function must return "true if the character was processed by the control; otherwise, false":
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Right)
        {
            this.NextField();
            return true;
        }
        if (keyData == Keys.Left)
        {
            this.PreviousField();
            return true;
        }
        if (keyData == Keys.Down) return true;
        if (keyData == Keys.Up) return true;
        return base.ProcessCmdKey(ref msg, keyData);
    }

This will cause my own navigation to happen and let the framework know 'I already dealt with this' (or I could just return true and handle it somewhere else). Any other 'command' keys can be handled the same (like Tab), however this does not handle the modifiers!
Both Tab and the Arrow keys navigate if Shift is pressed. If I want to handle all my navigation here it should look something like this:
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Right:
            case Keys.Right|Keys.Shift:
            case Keys.Enter:
                // move to next field
                this.NextField();
                return true;
            case Keys.Left:
            case Keys.Left|Keys.Shift:
                // move to previous field
                this.PreviousField();
                return true;
            case Keys.Down:
            case Keys.Down|Keys.Shift:
            case Keys.Up:
            case Keys.Up|Keys.Shift:
                // disable native navigation
                return true;
            case Keys.Tab:
                // move to next point
                return this.NextPoint();
            case Keys.Tab|Keys.Shift:
                // move to previous point
                return this.PreviousPoint();
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

Handling Tab in ProcessCmdKey negates the need to override ProcessTabKey .


text:
Q: How many steps to get zero Can someone solve this in Javascript?
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Also is this an example of a recursion question?
var numberOfSteps  = function(num) {

};

///What I have tried

var numberOfSteps  = function(num) {
    if(Math.sign(num) === -1){
      console.log('Number has to be positive')
    }
    else if(num % 2 === 0){
      num = num/2
      if(num % 2 !== 0){
        num = num - 1
        if(num !== 0){
           num = num / 2
           if(num % 2 !== 0){
              num = num - 1
             if(num % 2 === 0)
           }
        }
      }
    }
};

console.log(numberOfSteps(14))

A: You can simply simulate the process by continuously halving and decrementing the number (as appropriate) until it reaches 0 while counting the number of iterations.

var numberOfSteps  = function(num) {
    let steps = 0;
    while(num > 0){
        if(num % 2 === 0) num /= 2;
        else --num;
        ++steps;
    }
    return steps;
};
console.log(numberOfSteps(123));


text:
Q: Some problems adding data to ldap I'm trying to add some data to the ldap directory, but i get the following error.
sudo slapadd < ldapdata.txt
slap_sasl_init: auxprop add plugin failed
slapadd: slap_init failed!

Where is the problem ?

A: Judging from the error message, it seems the problem is during some internal initialization process, having not much to do with slapadd (ie. I guess you will get the same error with just slaptest). And according to here,  you might have to install a newer version of OpenLDAP.


text:
Q: Order criteria on explicit two-stage RK method I have the following exercise:
Consider an explicit two-stage Runge-Kutta method given by the Butcher table:
$$
A = \begin{pmatrix} 0 & 0 \\ a & 0 \end{pmatrix}, \quad \vec{c} = \begin{pmatrix} 0 \\ c \end{pmatrix}, \quad \vec{b} = \begin{pmatrix} b_1 \\ b_2 \end{pmatrix}.
$$
Write down equations for the parameters such that the method is consistent of order two. Show that the order of consistency cannot be higher.
I don't know how to start this exercise. Can someone provide some idea?
NB: I want only an idea to start the exercise, not a complete step-by-step solution! Thank you.

A: Consistency is given by
$$\sum_{j=1}^{i-1} a_{ij} = c_i$$
for $j=2,\ldots, s$, and $s$ is the number of stages of the method.
So this should be straightforward.
Also, for order $p$, you must choose the $b_i$ such that you have a nonzero $h^p$ term in the expansion, leaving only $\mathcal{O}(h^{p+1})$.
So, writing out
$$y_{m+1} = y_m + \sum_{i=1}^s b_ik_i$$
with $k_i = hf(t_i+c_ih,y_i+\sum_{j=1}^{i-1}a_{ij}k_j)$,
for each step in an order 2 method, you should get some very clear conditions for $b_i$, given what you know about $c$.


text:
Q: Перенос кода из
A: Вам надо скачать этот файл script.js и подключить непосредственно из файловой системы по абсолютному или относительному пути.

A: <script type="text/javascript" src="ПУТЬ К ФАЙЛУ С JS"></script>

Пример: <script type="text/javascript" src="js/menu.js"></script>. Эта строка подключает  файл menu.js из папки js.


text:
Q: Jquery .on click not working on first click I have a text field that I need to set the value for when a user either chooses an option from a select field or enters text in a text field and hits a link. Both events then close the div that contains the select and text field/link.
The select option works
$(document).on("change", ".select_choice", function(event) {
    var string = $(this).find("option:selected").text();
    $(this).closest(".select_toggle_area").find(".toggle_choices").toggle();
    $(this).closest(".select_toggle_area").find(".target_input").val(string);
});

The text field/link works on the second click. Any time something is entered into the field the link doesn't work on the first click. It hides the div, but doesn't update the value of the target field.
$(document).on("click", ".text_choice_button", function(event) {
    event.preventDefault();
    var string = $(this).closest(".select_toggle_area").find(".text_choice").val();
    $(this).closest(".select_toggle_area").find(".target_input").val(string);
    $(this).closest(".select_toggle_area").find(".toggle_choices").toggle();
});

A: Unable to replicate
I have fiddled with this and am unable to replicate it: http://jsfiddle.net/DCM48/
Please upload a full fiddle with the issue for further help.
-Lededje

A: try using delegate
$(document).ready(function() {
    $("body").delegate("click", ".text_choice_button", function() {
           your code......
    });
});

A: I had issues with 'onclick' handler usign jquery. i find mousedown a more reliable solution.
Kind of catch the clicks better i find. http://api.jquery.com/mousedown/

A: I always use this pattern, maybe you should try it too.
$(element).click(function() {});

Also post here html code you use javascript for.

A: $(function(){
    $("body").click("a, div", function(){
        $("body").append("ping");
    });
});

A: try it with "live"
$(".text_choice_button").live('click', function(event) {
    event.preventDefault();
    var string = $(this).closest(".select_toggle_area").find("text_choice").val();
    $(this).closest(".select_toggle_area").find(".target_input").val(string);
    $(this).closest(".select_toggle_area").find(".toggle_choices").toggle();
});


text:
Q: Who responds to flags on Area 51? I flagged a post on Area 51 Discussion as spam on the 5th of May. I thought spam flags went to the front of the queue, but this one still has yet to be processed.
Looking at the post again, it actually might not be spam. I thought it was at the time, but am less sure now. Either way, though, the flag should have been handled by now.

A: Since A51 doesn't have it's own moderators, SE staff handles flags on that site. As for the handling time, I'm inclined to agree with you. But CMs are busy people, so...

A: Several of us on the Community team handle those flags. Unlike a regular site, Area 51 isn't often hit with true spam.1 Therefore, flags are not quite so urgent on Area 51 as they are on other sites. The basic timeline on the post is:
Mar 5 '13 at 3:2 answered
Jun 27 '13 at 23:24 spam flag
Jun 30 '13 at 3:01 flag cleared
The "person" who cleared the flag was the Community user, which is what happens after 48 hours if the spam thresholds are not reached. I don't know if anyone saw the flag2 or if it just wasn't seen the next two days (Friday and Saturday). In any case, the flag expired before enough people flagged it for spam or a community manager deleted it.3
In any case, the post was deleted by votes from 3 non-moderators today.
We have turned off automatic expiration for spam/offensive flags on Area 51, so this shouldn't happen again in the future.

*

*Arguably the post you link to isn't spam in the traditional sense. Certainly the author mentioned their affiliation with the site they linked to and they certainly intended their answer to be relevant to the question.

*Which amounts to a sort of pocket veto.

*The question has been viewed 197 times, including any attention that has been drawn to it today.


text:
Q: Limit the amount of records in a spark context I would like to reduce the number of records for each reducer, and keep the resulting variable a rdd
Using takeSample seemed like the obvious choice, however, it returns a collection and not a SparkContext object.
I came up with this method:
rdd = rdd.zipWithIndex().filter(lambda x:x[1]<limit).map(lambda x:x[0])

However, this method is very slow and not efficient.
Is there a smarter way to take a small sample and keep the data structure an rdd ?

A: It you want a small example subset and cannot make any additional assumptions about the data then take combined with parallelize can be an optimal solution:
sc.parallelize(rdd.take(n))

It will touch a relatively low number of partitions (only one in the best case scenario) and the cost of network traffic for small n should be negligible.
Sampling (randomSplit or sample) will require a full data scan same as zipWithIndex with filter.
Assuming there is no data skew you can try something like this to address that:
from __future__ import division  # Python 2 only

def limitApprox(rdd, n, timeout):
    count = rdd.countApprox(timeout)
    if count <= n:
        return rdd
    else:
        rec_per_part = count // rdd.getNumPartitions()
        required_parts = n / rec_per_part if rec_per_part else 1
        return rdd.mapPartitionsWithIndex(
            lambda i, iter: iter if i < required_parts else []
        )

*

*this will still access every partition but will try to avoid computing content if not necessary

*won't work if there is large data skew

*

*can take much more than required if distribution is uniform but n << than an average number of records per partition.

*may undersample if distribution is skewed towards high indices.

If data is representable as a Row you can try another trick:
rdd.toDF().limit(n).rdd


text:
Q: Installing XpsDrv sample under the Windows XP this article helped me to install "XpsDrv sample" under the Windows XP. But I'd like to ask if it's possible to automate step No. 6

As you go on, the wizard can ask you for some files it cannot find. But this should be no big trouble if you have SP3 or XPS Extension Pack installed.
  If the wizard asks you for xdsmpl.gpd, click Browse and find this file in [sample root]\install\x86.
  If it asks for xdwmark.dll, navigate to [sample root]\install\x86 as well.
  For msxpsinc.gpd go to c:\windows\Driver cache\i386.
  The xpssvcs.dll file should be found in c:\windows\system32.

I need to install XPS driver during the installation process of my App and it's not acceptable for my customer to find missing files manually...

A: The easiest way is copy the x86 folder and rename it to i386. Then find missing files (msxpsinc.gpd, xpssvcs.dll) and copy them to the [sample root]\install


text:
Q: 'ForeignRelatedObjectsDescriptor' object has no attribute 'all' I'm moving my web application to Django 1.7 and I have a very curious mistake, perhaps one of you know is happening.
class Product(models.Model):
    title = models.CharField(max_lenght=100)
    slug = models.SlugField()
    content = models.TextField()

class Gallery(models.Model):
    product = models.ForeignKey(Product, related_name="images")
    original = models.ImageField()

class MyView(DetailView):
    model = Product

   def get_context_data(self, **kwargs):
       ....
       # My error is here, when use this context and parse template
       context["galleries"] = Product.images.all()

Givin the following error message:
'ForeignRelatedObjectsDescriptor' object has no attribute 'all'
    response = wrapped_callback(request, *callback_args, **callback_kwargs)

A: Try:
context["galleries"] = self.object.images.all()

You'll want to call it on a specific instance of your Product model, which should be your object.


text:
Q: KeyBinding, can't get the String of the pressed key Ok so here is the code
     Gui.java
      package mainProgram;

    import javax.swing.*;

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    public class Gui extends JFrame {
        final private static JButton numberButtons[] = new JButton[10];
        private JButton sum = new JButton("+");
        private JButton substract = new JButton("-");
        private JButton divide = new JButton("/");
        private JButton multiply = new JButton("*");
        private JButton sqrt = new JButton("√");
        private JButton square = new JButton("x^2");
        private JButton cubic = new JButton("x^3");
        private JButton percentage = new JButton("%");
        private JButton divideByOne = new JButton("1/x");
        private JButton C = new JButton("C");
        private JButton OK = new JButton("=");
        private JButton point = new JButton(".");
        private JButton plusMinus = new JButton("+-");
        private JTextArea output = new JTextArea();
        private JTextField inputOne = new JTextField();
        private JPanel panel = new JPanel();
        functions fn = new functions();
        GuiUpdate gridBagConstr = new GuiUpdate();
        HandlerClass handler = new HandlerClass();

        public Gui() {

            super("Calculator");
            setLayout(new GridBagLayout());
            requestFocus();

            output.setEditable(false);
            output.setBackground(Color.GREEN);
            // keyBinding for 0-9
            for (int i = 0; i <= numberButtons.length - 1; i++) {
                String text = String.valueOf(i);
                JButton button = new JButton(text);
                button.addActionListener(numberAction);
                numberButtons[i] = button;
                add(button);

                // Support Key Bindings

                KeyStroke pressed = KeyStroke.getKeyStroke(text);
                InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                inputMap.put(pressed, text);
                button.getActionMap().put(text, numberAction);
            }// keyBinding for NUMPAD 0-9
            for (int i = 0; i <= numberButtons.length - 1; i++) {
                String text = String.valueOf(i);
                KeyStroke pressed = KeyStroke.getKeyStroke(0x60 + i, 0);
                InputMap inputMap = numberButtons[i]
                        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                inputMap.put(pressed, text);
                numberButtons[i].getActionMap().put(text, numberAction);

            }

            // add Key Bindings listeners
            substract.addActionListener(numberAction);
            sum.addActionListener(numberAction);
            divide.addActionListener(numberAction);
            multiply.addActionListener(numberAction);
            //keyBinding for divide button
            KeyStroke pressed1 = KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, 0);
            divide.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(pressed1,"divide");
            divide.getActionMap().put("divide", numberAction);
            //keyBinding for sum button
            KeyStroke pressed2 = KeyStroke.getKeyStroke( 0x6B, 0);
            sum.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(pressed2, "add");
            sum.getActionMap().put("add", numberAction);
            //keyBinding for equal button
            KeyStroke pressed3 = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, 0);
            OK.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(pressed3, "=");
            OK.getActionMap().put("=", numberAction);

            gridBagConstr.setConstrains("HORIZONTAL", 4, 1, 0, 0, 30);
            add(output, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 4, 1, 0, 1, 15);
            add(inputOne, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 0, 2, 0);
            add(divide, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 1, 2, 0);
            add(multiply, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 2, 2, 0);
            add(substract, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 3, 2, 0);
            add(sum, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 4, 2, 0);
            add(divideByOne, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 0, 3, 0);
            add(numberButtons[7], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 1, 3, 0);
            add(numberButtons[8], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 2, 3, 0);
            add(numberButtons[9], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 3, 3, 0);
            add(sqrt, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 0, 4, 0);
            add(numberButtons[4], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 1, 4, 0);
            add(numberButtons[5], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 2, 4, 0);
            add(numberButtons[6], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 3, 4, 0);
            add(square, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 0, 5, 0);
            add(numberButtons[1], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 1, 5, 0);
            add(numberButtons[2], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 2, 5, 0);
            add(numberButtons[3], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 3, 5, 0);
            add(cubic, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 0, 8, 0);
            add(numberButtons[0], gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 1, 8, 0);
            add(point, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 2, 8, 0);
            add(C, gridBagConstr.c);
            gridBagConstr.setConstrains("HORIZONTAL", 1, 1, 3, 8, 0);
            add(OK, gridBagConstr.c);
            // actionListeners for other operations and for input from the program not from keyboard
            inputOne.addActionListener(handler);
            divide.addActionListener(handler);
            multiply.addActionListener(handler);
            substract.addActionListener(handler);
            sum.addActionListener(handler);
            divideByOne.addActionListener(handler);
            sqrt.addActionListener(handler);
            square.addActionListener(handler);
            cubic.addActionListener(handler);
            point.addActionListener(handler);
            C.addActionListener(handler);
            OK.addActionListener(handler);

        }

        public void eraseData() {
            fn.setA(0);
            inputOne.setText("");

        }

        public void saveInput() {
            if (fn.isNumeric(inputOne.getText())) {
                fn.setResult(Double.parseDouble(inputOne.getText()));
                output.setText(inputOne.getText());
            }
        }

        Action numberAction = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {

                String x = e.getActionCommand();
                String op = null ;
                switch (x) {
                case "0":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "1":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "2":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "3":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "4":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "5":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "6":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "7":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "8":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "9":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case ".":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "/":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "*":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "-":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "+":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "=":
                    switch (op) {
                    case "/":
                        fn.divide(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "*":
                        fn.multiply(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "+":
                        fn.sum(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "-":
                        fn.substract(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                }
            }
        };

        private class HandlerClass implements ActionListener {
            String op;

            public void actionPerformed(ActionEvent e) {

                String x = e.getActionCommand();
                switch (x) {
                case ".":
                    inputOne.setText(inputOne.getText() + x);
                    break;
                case "/":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "*":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "-":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "+":
                    op = e.getActionCommand();
                    saveInput();
                    eraseData();
                    break;
                case "√":
                    if (outputCheckZero(inputOne.getText())) {
                        fn.sqrt(output.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    } else {
                        fn.sqrt(inputOne.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                case "x^2":
                    if (outputCheckZero(inputOne.getText())) {
                        fn.square(output.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    } else {
                        fn.square(inputOne.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                case "x^3":
                    if (outputCheckZero(inputOne.getText())) {
                        fn.cubic(output.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    } else {
                        fn.cubic(inputOne.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                case "%":
                    break;
                case "1/x":
                    if (outputCheckZero(inputOne.getText())) {
                        fn.divideByOne(output.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    } else {
                        fn.divideByOne(inputOne.getText());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                case "C":
                    eraseData();
                    output.setText("");
                    fn.setResult(0);
                    break;
                case "=":
                    switch (op) {
                    case "/":
                        fn.divide(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "*":
                        fn.multiply(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "+":
                        fn.sum(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    case "-":
                        fn.substract(inputOne.getText(), fn.getResult());
                        output.setText(Double.toString(fn.getResult()));
                        eraseData();
                    }
                    break;
                case "+-":
                    break;
                default:
                    break;
                }

            }

            public boolean outputCheckZero(String x) {
                if (x.isEmpty())
                    return true;
                else
                    return false;
            }
        }
    }

     functions.java
    package mainProgram;

    import java.math.*;
    import java.util.*;

    public class functions {

        private double a;
        private double result = 0;

        public boolean isNumeric(String x) {
            try {
                Double.parseDouble(x);
                return true;
            } catch (NumberFormatException nfe) {
            }
            return false;

        }

        public double getNumber(String x) {
            if (isNumeric(x)) {
                this.a = Double.parseDouble(x);
            }
            return a;
        }

        public double sum(String a, double b) {
            if (isNumeric(a)) {
                double c = getNumber(a);
                result = b + c;
                return result;
            } else
                return b;

        }

        public double divide(String a, double b) {
            if (isNumeric(a)) {
                double c = getNumber(a);

                result = b / c;
                return result;
            } else
                return b;

        }

        public double multiply(String a, double b) {
            if (isNumeric(a)) {
                double c = getNumber(a);

                result = b * c;
                return result;
            } else
                return b;
        }

        public double substract(String a, double b) {
            if (isNumeric(a)) {
                double c = getNumber(a);

                result = b - c;
                return result;
            } else
                return b;
        }

        public double sqrt(String a) {
            if (isNumeric(a)) {
                double c = getNumber(a);
                result = Math.sqrt(c);
                return result;
            } else
                return 0;
        }

        public double square(String a) {
            if (isNumeric(a)) {
                double c = getNumber(a);
                result = c * c;
                return result;
            } else
                return 0;
        }

        public double cubic(String a) {
            if (isNumeric(a)) {
                double c = getNumber(a);
                result = c * c * c;
                return result;
            } else
                return 0;
        }

        public double divideByOne(String a) {
            if (isNumeric(a)) {
                double c = getNumber(a);
                result = 1 / c;
                return result;
            } else
                return 0;
        }

        public double getA() {
            return a;
        }

        public void setA(double a) {
            this.a = a;
        }

        public double getResult() {
            return result;
        }

        public void setResult(double result) {
            this.result = result;
        }
    }

package mainProgram;

import java.awt.GridBagConstraints;

public class GuiUpdate extends GridBagConstraints {

    GridBagConstraints c = new GridBagConstraints();

    public void setConstrains (String FILL, int gridwidth, int gridheight, int gridx, int gridy, int ipady ){
        if(FILL.toUpperCase().equals("HORIZONTAL")){
            this.c.fill = GridBagConstraints.HORIZONTAL;
            }else if(FILL.toUpperCase().equals("VERTICAL")){
                c.fill = GridBagConstraints.VERTICAL;
            }else if (FILL.toUpperCase().equals("BOTH")){
                c.fill = GridBagConstraints.BOTH;
            }else c.fill = GridBagConstraints.NONE;
            this.c.gridwidth = gridwidth;
            this.c.gridheight = gridheight;
            this.c.gridx = gridx;
            this.c.gridy = gridy;
            this.c.ipady = ipady;

    }

}

package mainProgram;
import javax.swing.JFrame;
public class mainClass {

    public static void main(String[] args) {

        Gui go = new Gui();
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(250,400);
        go.setVisible(true);
    }
}

I get this error " Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at mainProgram.Gui$1.actionPerformed(Gui.java:225)". My best guess is that my String op has no value, so when I click the "=" button on my keyboard the compiler has no idea which case to switch to. But what I don't understand is why the op doesn't take the value of the ActionCommand from my "/","*","-","+" cases.
For example if I write a number in my program then I click the "/" button on my keyboard the program seems to do whatever is in the "/" case from the AbstractAction method, but then I write the second number and click the "=" button on the keyboard I get this error. Any quick fix for it?

A: op must be null in that line.
Define a op variable outside of actionPerformed.
Thus it will always contain the last operation performed.
If you start a debugger and step into actionPerformed you will notice why.
When the method is called the variable op is created, then you assign a value to it. Then the method ends and so does the variable.
The next time the method is created, a new variable is created with the value null. You then reach the lines
            case "=":
                switch (op) {

where op must be null, because it has not been assigned a value since it was created.
If you place op outside of actionPerformed it keeps its value after the method finished. It should be called lastOp to reflect that it was assigned at the last run of the method.
(Please be aware that in multi-threadding environments this approach may be hazardous, for GUIs it should be good enough, though.)
As a suggestion on how you could improve your actionPerformed method. Remember the concept: Don't repeat yourself.
        String lastOp = null ;
        public void actionPerformed(ActionEvent e) {

            String x = e.getActionCommand();
            switch (x) {
            case "/": // an empty case line will execute the elements of the next case.
            case "*": // repeatative, so all operator cases here will execute the
            case "-": // "+" case, but with their operator.
            case "+":
                lastOp = e.getActionCommand();
                saveInput();
                eraseData();
                break;
            case "=":
                switch (op) {
                case "/":
                    fn.divide(inputOne.getText(), fn.getResult());
                case "*":
                    fn.multiply(inputOne.getText(), fn.getResult());
                case "+":
                    fn.sum(inputOne.getText(), fn.getResult());
                case "-":
                    fn.substract(inputOne.getText(), fn.getResult());
                }
                output.setText(Double.toString(fn.getResult()));
                eraseData();
                lastOp = null;
                break;
            }
            default: // this handles all number cases.
                inputOne.setText(inputOne.getText() + x);
                break;
        }


text:
Q: Simple SQL count with distinct query I have a table(Student) with the entities 'StudentID' and 'ProgrammeID' in phpmyadmin. I am trying to figure out how to do a query which lists the number of students in each particular programme and also displays the programmeID itself, but cant seem to figure it out.
SELECT count(`StudentID`) FROM Student WHERE `ProgrammeID` = DISTINCT

gives a synthax error near distinct.
Im sure its fairly straightforward but its beyond me at this hour.
Any help appreciated.

A: I think you want to count the number of Student for every ProgrammeID. In this case, use GROUP BY clause.
SELECT ProgrammeID, COUNT(StudentID) TotalStudentCount
FROM   Student
GROUP  BY ProgrammeID


text:
Q: Можно ли создать свою версию игры используя авторские ресурсы? Очень захотелось написать свою копию игры (Mappy, вышла в 1983 - под платформу Nintendo). Соответственно все ресурсы хочу взять оттуда (текстуры, музыку).
Является ли это нарушением авторского права? (насколько я понимаю, по истечении 28 лет - нет)

A: Нашел ответ - https://www.nintendo.com/corp/legal.jsp#expired
Права на игру истекут в течение 75 лет со дня первого релиза

A: Я не юрист
Обычно все ресурсы принадлежат кому-то (создателю, компании разработчику, компании издателю, третьим лицам). В ходе разработки, издания, перепродажи прав, они могут не раз сменить владельцев.
Первая большая проблема, найти в чьем-же они ведении сейчас. А точнее - кто обладает на них правами. Например, музыкант мог написать музыку и передать издательству права на ее однократное использование, сохранив за собой права на ее переиздание.
Вторая проблема - получение разрешения. За редкими исключениями, ни один правообладатель не будет лишать себя ценных владений, которые "лежат и есть не просят". Это касается в первую очередь торговых марок, названий, художественных образов. Подумайте, в чем ценность правообладателю передавать права?
Первое решение, нереальное, - найти, договориться, компенсировать.
Второе решение, реалистичное - придумать свою игру "по мотивам", сделать ресурсы самому.
Третье решение, простое - придумать свою игру "по мотивам" и использовать общедоступные ресурсы (по типу CC0).
P.S. Речь выше о ресурсах. Игровые механики и идеи, обычно (за исключением Тетриса, например), не подлежат патентованию. Поэтому в игрострое так много клонов и разработок существующих идей.
P.P.S. Имейте ввиду, что подать в суд может любая компания, почувствовшая, что её ущемили, и соотношение сил будет далеко не в вашу пользу. Даже если вы 100 раз правы, для разрабатываемой игры это, скорее всего, будет катастрофично.


text:
Q: Port unrecognized in DOT file? I am trying to create a PNG from DOT file

dot -Tpng  -o temp.png

and  I am getting the below errors:

Warning: node s1, port eth2 unrecognized
Warning: node s2, port eth2 unrecognized
Warning: node s2, port eth3 unrecognized
Warning: node s3, port eth2 unrecognized
Warning: node s4, port eth4 unrecognized
Warning: node s3, port eth3 unrecognized

DOT FILE 1:

graph G {
    node [shape=record];
    graph [hostidtype="hostname", version="1:0", date="04/12/2013"];
    edge [dir=none, len=1, headport=center, tailport=center];
    "s1":"eth2" -- "s2":"eth2";
    "s2":"eth3" -- "s3":"eth2";
    "s4":"eth4" -- "s3":"eth3";
}

When I try with the below topology file, it works.
DOT FILE 2

graph G {
    node [shape=record];
    graph [hostidtype="hostname", version="1:0", date="04/12/2013"];
    edge [dir=none, len=1, headport=center, tailport=center];
    "R1":"swp1" -- "R3":"swp3";
    "R1":"swp2" -- "R4":"swp3";
}

What is the difference here. For what reason is DOT FILE 1 giving errors ?

A: Your example is missing some information (a description of the nodes). Assuming those are somewhere and have just been omitted from your example,
maybe the problem is that using node [shape=record] doesn't work with the port HTML attribute. For example, try node [shape=plaintext].

A: The port positions are "compass points".  From the doc at http://www.graphviz.org/doc/info/attrs.html#k:portPos

If a compass point is used, it must have the form
  "n","ne","e","se","s","sw","w","nw","c","". This modifies the edge
  placement to aim for the corresponding compass point on the port or,
  in the second form where no portname is supplied, on the node itself.
  The compass point "c" specifies the center of the node or port. The
  compass point "" specifies that an appropriate side of the port
  adjacent to the exterior of the node should be used, if such exists.
  Otherwise, the center is used. If no compass point is used with a
  portname, the default value is "_".


text:
Q: How do I initialize a variable instance which is an object properly? I am an Objective C newbie and I'm sure this is an easy question but I can't figure this out:
I have a class which declares an instance variable called myDeck, which is part of a custom class I created called Deck. Right now I have this in my code:
In the @interface:
Deck *myDeck;

In my init method:
Deck *ourDeck = [[Deck alloc]init];
myDeck = ourDeck;

So this seems to create the myDeck just fine, and I can stick values in it and run it's methods for a while, but I'm running into a spot where it ceases to exist and I get an EXC_BAD_ACCESS error when trying to use it.
I have tried adding
[myDeck retain];

to no avail, it still fails in the same spots. I don't really know how I should be alloc and initting this, I have a feeling I am missing something, anyone?

A: Everything you're doing there seems right; except I think you might have a typo in your first example - the instance variable is called myDeck, not deck, right?  If your object is disappearing it's because you called release or autorelease too many times.  Memory management in Cocoa is pretty straightforward.  Go check out the documentation for all the information you could ever want.


text:
Q: Reformatting json file I'm trying to reformat a JSON file so I can convert it into a Python dictionary. The file contains line-separated JSON objects with different product info (looks like this):
{"asin": "7301113188", "category": ["Appliances", "Refrigerators, Freezers & Ice Makers"], "description": [], "fit": "", "title": "Tupperware Freezer Square Round Container Set of 6", "also_buy": [], "image": [], "tech2": "", "brand": "Tupperware", "feature": ["Each 3-pc. set includes two 7/8-cup/200 mL and one 1-3/4-cup/400 mL.", "Use them to keep sandwich fillings, salads or leftovers fresh in the refrigerator.", "Gently twist the container to \"pop\" out frozen foods for reheating.", "Dishwasher Safe.", "Set weights less than 13 oz!"], "rank": [">#39,745 in Appliances (See top 100)"], "also_view": [], "details": {}, "main_cat": "Appliances", "similar_item": "", "date": "November 19, 2008", "price": ""}
{"asin": "7861850250", "category": ["Appliances", "Refrigerators, Freezers & Ice Makers"], "tech2": "", "brand": "Tupperware", "feature": ["2 X Tupperware Pure & Fresh Unique Covered Cool Cubes Ice Tray in Purple With Opening Lid Contain 14 Cubes - HerbalStore_24*7", "Package Contain :- 2 Tray", "Each ice tray has a specially designed seal that allows you to fill from the faucet with no spills on the way to the freezer. While freezing, this seal helps keep flavor in and freezer odors out, ensuring you have pure ice every time. For something special, try freezing lemonade, tea or fruit juices in these Ice Tray to give your beverages an extra-flavorful kick. Or add a piece of fruit to each cube for a stylish touch of elegance.", "Sold By:- HerbalStore_24*7", "Free Shipping"], "rank": [">#6,118 in Appliances (See top 100)"], "also_view": ["B004RUGHJW"], "details": {}, "main_cat": "Appliances", "similar_item": "", "date": "June 5, 2016", "price": "$3.62"}

I want the dict to contain key-pair values where each "asin" is a key and the rest of the product info is a value. What's the most optimal way to do this?

A: You can parse JSON dictionaries using json.loads.
import json

final = {}

for line in lines:
    d = json.loads(line)
    final[d['asin']] = d
    del d['asin']

It's also possible to parse some JSON-like text using ast.literal_eval. The JSON-like text has to not have any boolean or null values, as is the case with your example. Below is the changes needed:
from ast import literal_eval

...
    d = literal_eval(line)
    ...


text:
Q: Accessing elements properties in a EMF Compare Diff Model I have used EMF Compare to compare 2 models comforming to a custom metamodel.
I generated and saved the Diff model to an .xmi file.
Currently, I am working on how to use the Diff Model within ATL to transform the differences to another model.
The problem is that I can't figure out how to access the properties of the element ( defined in my custom metamodel) being changed. I could access the kind of change like this :
diffModel.kind

but I cannot access the properties of the element who has been changed.

A: To know the element that have change in a diff block, you have to query wich is the match element where is contained the diff, in this element have two attributes: left and right, that references the source and the target elements.
To access the match element where is contained the diff block, you can use the ATL operation refImmediateComposite(). Example: diff.refImmediateComposite().
Also you need to define as input model the source and target model compared.


text:
Q: Jsoup parsing - Java I'm trying to parse data from IMDB and Rotten Tomatoes using Jsoup.  I've gotten most of the info I need but there is some data I don't know how to get.
For example in the movie The Expendables 2 I need to get the number for User Reviews: 313,393 (just the number) but using something like
Elements links19 = doc5.select("p[class=critic_stats]");

gets the whole p class="critic_stats"

Average Rating: 5.8/10 Reviews Counted: 123 Fresh: 80 | Rotten: 43 Average Rating: 5.3/10 Critic Reviews: 23 Fresh: 13 | Rotten: 10 liked it Average Rating: 3.7/5 User Ratings: 313,393

For the same movie in IMDB I'm trying to get:
Country: USA | Bulgaria
Language: English
Release Date: 17 August 2012 (USA)
Sound Mix: Dolby Digital | Datasat
Color: Color
Aspect Ratio: 2.35 : 1

Again I only need the values but everything is in

and I don't know if there's any way to get specific data based on for example

Sound Mix:

<itemprop='url'>Dolby Digital
<itemprop='url'>Datasat

Any ideas on how to get those .. I'm not sure what they are, child attributes?
UPDATE:
OK so the first worked with
Pattern pattern = Pattern.compile("[0-9]*\\.?,?[0-9]+");
I have a few more questions
I need to get "/title/tt1764651/?ref_=fn_tt_tt_1" or even better the whole http
from

   	  The Expendables 2 (2012)

I tried
Elements links = doc.select("table[class=findList");
String a= links.attr("abs:href");
but it doesn't work, any ideas?
Also I used
Document doc6= Jsoup.parse(new URL(url6).openStream(), "ISO-8859-1", url6);
to get the Also Known As but on the Bulgarian title for example I get
Bulgaria (Bulgarian title) ???µ?????±?µ???????????µ
@Spectre

A: jsoup only provides manipulation of HTML. It can get you slight further than your attempt but not much:
Element el = doc.select("p.critic_status").last();

Will get you the element containing:
"Rotten: 10 liked it Average Rating: 3.7/5 User Ratings: 313,393"
This is because there are no further sub-elements to be able to dig into. To extract the data you want will require using other text-processing tools. For example using regular expressions:
Pattern pattern = Pattern.compile("User Ratings: ([0-9,]+)");
Matcher = pattern.matcher(el.text());
if(matcher.matches()) {
    String userRating = matcher.group(1); // "313,393"
}

For your second question, you need to chain selectors:
doc.select("div.txt-block");                   // <div class=<txt-block">

doc.select("div.txt-block > h4.inline");       //

doc.select("div.txt-block > a[itemprop=url]"); //

jsoup selectors are documented in the Selector class. Also Jsoup is modelled after jQuery so that documentation is also useful:

*

*jsoup: org.jsoup.select.Selector

*jQuery: Selectors


text:
Q: Print div without opening extra popup I have a GridView with a print button in the last column
<asp:LinkButton ID="lnkPrint" runat="server" Text="Print" OnClientClick="OnPrintClick(this);" OnClick="lnkPrint_Click"></asp:LinkButton>

function OnPrintClick(lnk)
{
    var row = lnk.parentNode.parentNode;
    var userId = row.cells[0].innerHTML;
    $('[id$=hdnPrintUserId]').val(userId);

    $('#<%=lblPrintIdNumber.ClientID %>').val("");
    $('#<%=lblPrintName.ClientID %>').val("");
    $('#<%=lblPrintAge.ClientID %>').val("");

    $("#idPrint").show();
}

On click it opens a pop up which displays the user info :
<asp:Panel id="pnlPrintContents" runat = "server">

            <asp:Label ID="Label3" runat="server" Text="Profile Photo"></asp:Label>

            <asp:Image style="max-height:100px;max-width:100px;" ID="profileImage" runat="server" />

            <asp:Label ID="lblIdNumber" runat="server" Text="Identification Number"></asp:Label>

            <asp:Label ID="lblPrintIdNumber" runat="server"></asp:Label>

            <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>

<asp:Label ID="lblPrintName" runat="server"></asp:Label>

          <asp:Label ID="lblAge" runat="server" Text="Age"></asp:Label>

<asp:Label ID="lblPrintAge" runat="server"></asp:Label>

</asp:Panel>

In the code behind on button click, I fetch the data from the database and set the values in the respective controls.
To do:
I want to show the popup with the print dialog box i.e. it will show the pop up with the details and a print dialog box to print the popup content. I have checked the net and found that it too opens the pop up with the printable content like this:
function PrintPanel() {
    var panel = document.getElementById("<%=pnlPrintContents.ClientID %>");
    var printWindow = window.open('', '', 'height=400,width=800');
    printWindow.document.write('<title>DIV Contents</title>');
    printWindow.document.write('');
    printWindow.document.write(panel.innerHTML);
    printWindow.document.write('');
    printWindow.document.close();
    setTimeout(function () {
    printWindow.print();
    }, 500);
    return false;
}

I only want to show my pop up and do not want to write window.open(..).
Is this possible that on 'Print' button click it shows my div content as a popup with the print dialog box and prints only my div content?


text:
Q: Convergence of hankel transform for polynomials The hankel transform is related to fourier transforms that have some kind of spherical symmetry. The simplest is related to the 2D radially symmetric fourier transform. This transform $F(k)$ of $f(r)$ is defined below as
$$
F(k) = \int_0^\infty f(r) J_0(kr) r {\rm{d}}r, \qquad {\rm{(limit\:for\:upper\:bound\:implied)}}
$$
Since $J_0\sim 1\big/\sqrt{r}$ for large $r$, we can imagine that a convergence condition exists where we just replace the bessel function with the asymptotic limit.
$$
\int_0^\infty f(r) \sqrt{r} {\rm{d}}r < M
$$
And wikipedia lists this is so for invertibility. However, the statement doesn't appear to be bijective and there's an entry in the wiki article that lists hankel transform pairs where the function doesn't meet the condition. I'm interested in these polynomial conditions,
$$
r^3 \rightarrow 9k^{-5} \quad {\rm{and}} \quad r \rightarrow -k^{-3}
$$
I could attempt to crunch it out and see what happens for $r^3$, but I'm worried about convergence of other functions that are less than $r^3$ but greater than or equal to $r^{-1/2}$ or what if $f(r)$ isn't strictly real valued? Is it that the wiki isn't including that there are restrictions on $k$ where this converges?

I did try to do it to see if along the way it would become apparent why it works for $r$ and $r^3$ but not other functions that don't satisfy the invertibility condition.
I use some properties of bessel functions $\partial_z z^\nu J_\nu = z^\nu J_{\nu-1}$ and $\partial_z J_0 = -J_1$ and integration by parts, to obtain,
$$
\begin{align}
F(k; r^n) &= \int r^n J_0(kr) r {\rm{d}}r \\
&= \frac{r^n}{k} J_1(kr) r + \frac{nr^n}{k^2} J_0(kr)r - \frac{n^2}{k^2}\int r^{n-1} J_0(kr) r {\rm{d}}r \\
&= \frac{r^n}{k} J_1(kr) r + \frac{nr^n}{k^2} J_0(kr)r - \frac{n^2}{k^2}F(k; r^{n-2})
\end{align}
$$
From here I've gotten a way to go from $r^3$ to $r$ but I can't imagine the ``surface'' terms from $r^3$ cancelling the ones from $r$ because the additional factor of $k$. What am I missing?

A: It is not my personal answer but one that someone I know showed me, it is certainly not a rigorous answer but it shows that the behavior of oscillations are what causes the decay. We will use the integral form of the 0th bessel function,
$$
J_0(x) = \frac{1}{2\pi} \int_0^{2\pi} \exp(ix\cos\varphi) {\rm{d}}\varphi
$$
and the transform, $F_n(q)$ of $f(b)=b^n$ becomes,
$$
F_n(q) = \int_0^{\infty}b{\rm{d}}b \frac{1}{2\pi} \int_0^{2\pi}{\rm{d}}\varphi \exp(iqb\cos\varphi) b^n
$$
For a mathematician, this next part is an issue especially since it's so close to what I am trying to show, but I exchange the order of integration.
$$
F_n(q) = \frac{1}{2\pi} \int_0^{2\pi}{\rm{d}}\varphi \int_0^{\infty} b^{n+1}{\rm{d}}b \exp(iqb\cos\varphi)
$$
Let's look at the second integral, we will use $n+1=m-1$ to cite a different result for a later expression.

$$
G_m(z)=\int_0^\infty b^{m-1} \exp(izb) {\rm{d}}b, \quad z\equiv q\cos\varphi + i\eta
$$
where we introduce eta as a convergence parameter and we will take a limit of it vanishing later. Let $x=(\eta+iz)b$ and the previous expression becomes.
$$
G_m(z)=\int_0^\infty \left(\frac{x}{\eta+iz}\right)^{m-1} \exp(-x) \frac{{\rm{d}}x}{\eta+iz}
$$
extracting the terms independent of $x$ gives the integral form of the gamma function for integer argument, so that
$$
G_m(z) = \frac{(m-1)!}{(\eta+iz)^m} = \frac{(m-1)!}{i^m(z-i\eta)^m}
$$
coming back to where we were

We find that
$$
\begin{align}
F_n(q) &= \frac{1}{2\pi} \int_0^{2\pi} {\rm{d}}\varphi G_{n+2}(z, \eta \rightarrow 0) \\
 &= \frac{(n+1)!}{2\pi i^{n+2} q^{n+2}} \int_0^{2\pi}\frac{{\rm{d}}\varphi}{(\cos\varphi - i \eta/q)^{n+2}}, \quad \eta\rightarrow 0
\end{align}
$$
the integral can be done as a contour integral. Taking $z=\exp(i\varphi)$ and factoring the resulting polynomial in the denominator has roots at $z_0=i\eta\pm i\sqrt{1+\eta^2}$, redefining $\eta$ and assuming $q\neq0$, giving that the integral is now
$$
-i2^{n+2} \oint z^{n+1} \frac{\rm{d}}{(z-z_{0+})^{n+2}(z-z_{0-})^{n+2}}
$$
which can be evaluated with residue theorem as all of singularities are removable telling us that the integral is finite for integer $n\geq-1$.


text:
Q: Checking if an account is valid in Django I am attempting to create some validation logic to my views. In order to not repeat myself, I'd like to have the validation logic in a single function, which can then be called by other view functions. The validation function is called check_if_account_valid. However, it looks like the HttpResponseRedirects which are embedded in the validation function are not being called -- the subscription_status check works ('Subscription status is lapsed' is printed out), but the redirect does not happen.
How can I have a view that executes some validation logic when each view is called? Is there a reason you can't call a view from within another view? Is there a better way of doing this?
models.py
class Account(models.Model):

    SUBSCRIPTION_CHOICES = (
        ('Dev Account', 'Dev Account for Testing'),
        ('15 day trial', '15 day trial'),
        ('Paid', 'Paid account - payment up to date'),
        ('Lapsed', 'Paid account - payment lapsed'),
        ('Inactive', 'Inactive'),
        )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    subscription_status = models.CharField(choices=SUBSCRIPTION_CHOICES, default='15 day trial',
                                            max_length=100)
    date_created = models.DateTimeField(auto_now_add=True)

views.py
def check_if_account_valid(request):
    if request.user.is_authenticated():
        subscription_status = request.user.account.subscription_status
        date_created = request.user.account.date_created
        if subscription_status == '15 day trial':
            localtz = pytz.timezone('Europe/Lisbon')
            now_datetime = datetime.datetime.utcnow()
            now_datetime_loc = localtz.localize(now_datetime)
            # check if trial is up
            if (date_created - now_datetime_loc) < datetime.timedelta(days=15):
                pass
            # if it is up, do nothing
            else:
                return HttpResponseRedirect('/subscription/trial_ended/')
        elif subscription_status == 'Paid':
            pass
        elif subscription_status == 'Lapsed':
            print('Subscription status is lapsed')
            return HttpResponseRedirect('/subscription/lapsed/')
        elif subscription_status == 'Inactive':
            return HttpResponseRedirect('/subscription/inactive/')
    else:
        return HttpResponseRedirect('/login/')

def home(request):
    check_if_account_valid(request)
    context = {}
    return render(request, 'home.html', context)

Django==1.8.4

A: It is because you are returning HttpResponseRedirect from check_if_account_valid to home but then not doing anything with them.

A: The problem is that you don't return your response. To get your approach to work, you might want to change it to this:
def check_if_account_valid(request, next_view):
    if request.user.is_authenticated():
        subscription_status = request.user.account.subscription_status
        date_created = request.user.account.date_created
        if subscription_status == '15 day trial':
            localtz = pytz.timezone('Europe/Lisbon')
            now_datetime = datetime.datetime.utcnow()
            now_datetime_loc = localtz.localize(now_datetime)
            # check if trial is up
            if (date_created - now_datetime_loc) < datetime.timedelta(days=15):
                pass
            # if it is up, do nothing
            else:
                return HttpResponseRedirect('/subscription/trial_ended/')
        elif subscription_status == 'Paid':
            pass
        elif subscription_status == 'Lapsed':
            print('Subscription status is lapsed')
            return HttpResponseRedirect('/subscription/lapsed/')
        elif subscription_status == 'Inactive':
            return HttpResponseRedirect('/subscription/inactive/')
    else:
        return HttpResponseRedirect('/login/')

    return next_view

And then call your view like this:
def home(request):
    context = {}
    next_view = render(request, 'home.html', context)
    return check_if_account_valid(request, next_view)

A better (more django-like) approach might be to switch to ClassBased View, create a Mixin in which the check_if_account_valid is called in the dispatch methdod.

A: Your check_if_account_valid function returns an HTTPResponse but then your home view doesn't do anything with it.
For the code to work, you would have to return the response
def home(request):
    return check_if_account_valid(request)
    context = {}
    return render(request, 'home.html', context)

But that would always return, which you don't want for valid accounts. So you would need to add a check like the following:
def home(request):
    response = check_if_account_valid(request)
    if response is not None:
        return response
    context = {}
    return render(request, 'home.html', context)

This works, but isn't very tidy. A better approach would be to make check_if_account a decorator. Django uses this approach for decorators like login_required and user_passes_test. Then your view would simplify to:
@check_if_account_valid
def home(request):


text:
Q: generating maximum number using pig I was trying to find generate year , MAX(number) for the following data and it gives me error saying
ERROR 1045: Could not infer the matching function for org.apache.pig.builtin.MAX as multiple or none of them fit. Please use an explicit cast.
i used the commands
loadfirstoutput = load '/outt/part-r-00000' as (year:chararray, number:chararray);
foreach2 = foreach loadfirstoutput generate year, MAX(number);
dump foreach2;

 ERROR 1045: Could not infer the matching function for org.apache.pig.builtin.MAX as multiple or none of them fit. Please use an explicit cast.

"   8
A"  6
"0" 4004
Ng" 1
1)" 1
Co" 5
/i>"    12
#4)"    1
&amp    2
21)"    1
22)"    2
38)"    1
80)"    1
Now"    1
Son"    1
"Unk"   1
Budd"   1
Food"   1
Ginn"   1
Hate"   1
Jax)"   1
Lang"   1
More"   1
Ross"   1
Sans"   1
Sign"   2
Sons"   1
Stan"   1
"1378"  1
"1806"  1
"1900"  2
"1901"  5
"1902"  2
"1904"  1
"1906"  1
"1908"  1
"1909"  2
"1910"  1
"1911"  14
"1914"  1
"1917"  1
"1920"  29
"1921"  2
"1923"  10
"1924"  2

A: Its a bit hard to tell whats going on with your data.  But assuming it is as the pattern suggests you need to group first.
loadfirstoutput = load '/outt/part-r-00000' as (name:chararray, year:chararray, number:chararray);
A = GROUP  loadfirstoutput ALL;
B = FOREACH A GENERATE MAX(loadfirstoutput.number);
dump B;

This will give you the max "number"
If you want the max number per year
loadfirstoutput = load '/outt/part-r-00000' as (name:chararray, year:chararray, number:chararray);
    A = GROUP  loadfirstoutput BY year;
    B = FOREACH A GENERATE MAX(loadfirstoutput.number);
    dump B;

A: This does not answer the question, but the same error happened in another situation when different types were mixed in MAX like this:
FOREACH fltrd GENERATE ids, MAX(TOBAG(suu, 1)) AS uu;

where suu is a long field.
I had to cast the int 1 to long 1 by appending an L to 1 like this:
FOREACH fltrd GENERATE ids, MAX(TOBAG(suu, 1L)) AS uu;


text:
Q: Conditional probability doubt Assume
$$P(B|A) = 1/5,\ P(A) = 3/4,\ P(A \cap B) = 3/20,\ \textrm{and}\ P(¬B|¬A) = 4/7.$$
Find $P(B)$.
What I tried: $$P(B)=\dfrac{ P(A \cap B)}{P(B|A)}=(3/20)/(1/5) = 3/4.$$
Answer is $P(B)=9/35.$
Where have I made the mistake?

A: The probability of B can be split into the probability given A and given not A
$$P(B) = P(B|A) \cdot P(A) + P(B|\neg A) \cdot P(\neg A)$$
The negations can be replaced by one minus the actual and vice versa
$$P(B) = \frac{1}{5} \cdot \frac{3}{4} + (1-P(\neg B| \neg A)) \cdot (1-P(A))$$
$$P(B) = \frac{3}{20} + (1-\frac{4}{7})\cdot (1-\frac{3}{4})$$
$$P(B) = \frac{3}{20} + \frac{3}{7} \cdot \frac{1}{4}$$
$$p(B) = \frac{3}{20} + \frac{3}{28}$$
$$p(B) = \frac{21}{140} + \frac{15}{140}$$
$$P(B) = \frac{36}{140}$$
$$P(B) = \frac{9}{35}$$


text:
Q: Rest API Field Requirements I'm curious to see if there is a solution to send Field Requirements (type, length, required) together with the API, which I can use for Form Validation.
So... What I expect, is the following:

*

*Page loads

*Gets required fields and their requirements from API.

*Builds form based on requirements

A: Just add more properties to the response body to specify the requirements. For example:
{
    "fields": [{
        "field": "username",
        "type": "String",
        "minLength": 3,
        "maxLength": 20,
        "required": true
    }, {
        "field": "password",
        "type": "String",
        "minLength": 6,
        "maxLength": 15,
        "required": true
    }]
}


text:
Q: Error with VMware Player on Windows 7 - Virtual system won´t start my OS is Windows 7 64bit and I have installed VMware Workstation Player 12.1.1-3770994.
I never had problems with it, every time I started the virtual machine it worked without any problems.
But since yesterday the system just won´t start.
I always get the error message
"Error while powering on: VMware Player cannot connect to the virtual machine. Make sure you have rights to run the program, access all directories the program uses, and access all directories for temporary files.  The VMware Authorization Service is not running."
I already found several solutions for it through Google and even here on the website but nothing helped me to get it working again.
I tried to kill all VMware processes in Task Manager and start it again, killed all processes and reboot my PC before I started VMware again, unistalled VMware Player and rebootet my PC but had no success.
Then I uninstalled VMware Player again, clean my registry with CCleaner, rebooted my system, installed again, still no success.
I ran CMD with administrator rights, opened services.msc and restarted the VMware Authorization service.
I also tried the same steps as administrator but it also did not help.
The virtual system I used is Windows XP and I had a backup of the system on my HDD so I deleted the whole folder with the virtual system and copied the backup to the location.
That backup was always working until yesterday.
Now I am at a point where I don´t know what to do anymore and I would be really grateful if someone would have a working solution for it.

A: Install Virtualbox.  Create a new virtual machine.  When it asks to create a hard drive, find the "use existing" option and point it to your existing .vmdk file.  You'll have to do a little set-up for memory and the virtual network card, but you can be up and running in very little time.


text:
Q: Building a CMake library within a Bazel project I've written a module on top of a private fork off of TensorFlow that uses nanomsg.
For my local development server, I used cmake install to install nanomsg (to /usr/local) and accessed the header files from their installed location. The project runs fine locally.
However, I now need to package nanomsg within my TensorFlow workspace. I've tried the following two approaches, and find neither satisfactory:

*

*Similar to this answer for OpenCV, I precompiled nanomsg into a private repository, loaded it within my workspace (within tensorflow/workspace.bzl) using an http_archive directive then included the headers and libraries in the relevant build script. This runs fine, but is not a portable solution.

*A more portable solution, I created a genrule to run a specific sequence of cmake commands that can be used to build nanomsg. This approach is neater, but the genrule cannot be reused to cmake other projects. (I referred to this discussion).
Clearly cmake is not supported as a first-class citizen in Bazel builds. Is there anyone who has faced this problem in your own projects created a generic, portable way to include libraries within Bazel projects that are built using cmake? If so, how did you approach it?

A: As Ulf wrote, I think your suggested option 2 should work fine.
Regarding "can I identify if the cmake fails", yes: cmake should return with an error exit code (!= 0) when it fails. This in turn will cause Bazel to automatically recognize the genrule action as failed and thus fail the build. Because Bazel sets "set -e -o pipefail" before running your command (cf. https://docs.bazel.build/versions/master/be/general.html#genrule-environment), it should also work if you chain multiple cmake commands in your genrule "cmd".
If you call out to a shell script in your "cmd" attribute that then actually runs the cmake commands, make sure to put "set -e -o pipefail" in the first line of your script yourself. Otherwise the script will not fail when cmake fails.
If I misunderstood your question "Can I identify if the cmake fails", please let me know. :)

A: This new project: https://github.com/bazelbuild/rules_foreign_cc seems like a solution(it build rules for cmake to build your project inside bazel).


text:
Q: make content inside divs display in the same locations i have a page that displays products on my website inside boxes (https://s21.postimg.io/9nw7kqrfb/Screen_Shot_2016_09_12_at_22_27_46.png)
but the data inside the boxes is not displaying in the same locations in each box if the image is too small.
if i make each box a set height, how can i make the product title and price display at the bottom of the box under each other so each both is exactly the same?
HTML for one box:

Mikrotik RB2011 Advanced Wi-Fi Router

    £109.00 ex VAT

A: I suggest using jquery to equalize the height of spans with et_shop_image class name.
$(document).ready(function(){
  var maxHeight=0;
  $(".et_shop_image").each(function(){
  if ($(this).height()>maxHeight){maxHeight=$(this).height()}
  });

  $(".et_shop_image").height(maxHeight);
})

Also make sure the class et_shop_image has display:inline-block or block
If you can not use javaScript and you are using HTML 5 , check the flexbox. But you will need to revise the HTML codes too.


text:
Q: Кто-нибудь знает, как сделать аналог AppContext.SetSwitch на .net 4.5? Необходимо изменить значение конфигурации программы:
AppContext.SetSwitch("Switch.UseLegacyAccessibilityFeatures", false);

В .NET Framework 4.6 всё срабатывает замечательно, а в более старых версиях нужно редактировать, а потом носить с приложением app.config. Вопрос к профессионалам: кто-нибудь знает аналоги, либо способ переноса этого метода из 4.6?
Прошу не предлагать способы с изменением реестра, склейкой конфига с приложением и уж тем более с апгрейдом до 4.6.


text:
Q: Force Chrome to use subpixel rendering for floats I am trying to have 8 images floated by each other with
width: 25%;
float: left;

Here is a fiddle:
https://jsfiddle.net/y06z0em1/
If you resize the section that the images are in, you will see that there are times when it breaks because some of the images are off by a fraction of a pixel. Could I ever change make it so that every pixel always rounds up or down?
Thanks!

A: Browsers round fractional pixels automatically and this is browser specific, some round it up, some down; There is no way to force it to do one or the other with CSS.
A solution could be to work with LESS, there are functions for that (ceil, floor).
But if you need a solution with CSS I would just suggest define the width as calc(100% - 0.5px) / calc(100% -1px) or 99.9%. That's just not perfect, but a solution. You can adjust it as you like and as it works for you.
But I'm not sure your problem comes from that.
Take a look at the following fiddle and tell me if it solves your problem. Instead of floating I use a layout based on display:inline-block here, and it seems like there is not such a problem.
https://jsfiddle.net/a693yj52/

A: I'd recommend using Flexbox here.
It'd look something like this:
.container {
   display: flex;
   flex-wrap: wrap;
}

.container > * {
   flex-basis: 25%;
   height: auto;
}


text:
Q: Mac - Max Texture Size for compatibility? I have an OpenGL based game for the Mac.
Mac OS X 10.5 compatibility required, going back to pretty much any Mac that can reasonably handle Leopard, going back to G4 Powerbooks.
I'm building my sprite sheets/texture atlases, for feeding to OpenGL, and need to set a maximum texture size.
Q. What's the maximum texture size that a 5 year old Mac can reasonably accommodate?  Would I be safe making my sprite sheets 1024x1024?
Q2. Would all such hardware be able to handle non-power of two textures?
Cheers.
[edited]
I found the following (very useful!) resource:
http://homepage.mac.com/arekkusu/bugs/GLInfo_1058.html
From this list, supporting 10.5.8 as a minimum requirement, it would appear that everything I need the game to run on supports a maximum texture size of 2048x2048, which makes me very happy, as the use of larger sprite sheets negates the need for NPOT textures.


text:
Q: Matching Part of a String in MySQL I would like to make a query which matches a string, either completely or partially.
This is what I have:
SELECT code
FROM jos_rsticketspro_tickets
WHERE message LIKE '%1. Fuente Dorada%';

The solution would match message contents "fuente". "fuen". "orada". "1. Fuente Dorada", etc.
How can I do this?

A: maybe this will work. it will check row wich have message part of "1. Fuente Dorada"
SELECT code
FROM jos_rsticketspro_tickets
WHERE "1. Fuente Dorada" LIKE concat("%", message, "%");


text:
Q: Orthogonality of eigenfunctions of a linear operator. Suppose I have a linear operator
$$
\frac{\mathrm{d}^2}{\mathrm{d}r^2}+\frac{1}{r}\frac{\mathrm{d}}{\mathrm{d}r}
$$
and I want to find its eigenfunctions, that is, to solve the ODE
$$
\frac{\mathrm{d}^2R}{\mathrm{d}r^2}+\frac{1}{r}\frac{\mathrm{d}R}{\mathrm{d}r}=\lambda R.
$$
Suppose, further, that I have boundary conditions $R(0)\neq\pm\infty$ and $R(a)=0$, then the solutions are Bessel's functions of the first kind $R=J_0\left(\frac{j_n}{a}r\right)$, where $j_i$'s are the roots of $J_0$. I want to show directly that these functions are orthogonal with respect to a weight function. Notice that
$$ rR''+R'=\lambda rR =\frac{\mathrm{d}}{\mathrm{d}r}(rR')$$
and suppose that $R_m$ and $R_n$ are eigenfunctions with distinct corresponding eigenvalues $\lambda_m,\lambda_n$, so
$$
(rR'_m)'=\lambda_m rR_m \\
(rR'_n)'=\lambda_n rR_n
$$
Hence, multiplying by $R_n$ and $R_m$ and subtracting, one gets
$$
(\lambda_m-\lambda_n)rR_mR_n=((rR'_m)'R_n-(rR'_n)'R_m)
$$
At this stage, it seems that $r$ is the weight function and I need to integrate w.r.t. $r$ from $0$ to $a$
$$
(\lambda_m-\lambda_n)\int^a_0 rR_mR_n\:\mathrm{d}r=\int^a_0 ((rR'_m)'R_n-(rR'_n)'R_m)\:\mathrm{d}r
$$
It seems that the integral on the RHS should be equal to zero, but I do not see how.

A: I think you made a mistake in the next-to-last step.  You would be integrating
$$\begin{align}\int_0^a dr \, [R_n (r R_m')' - R_m (r R_n')'] &= [r R_m' R_n - r R_n' R_m]_0^a - \int_0^a dr \, r (R_m' R_n' - R_n' R_m') = 0- 0\end{align}$$
The second step is a result of applying the boundary conditions.


text:
Q: Variable assignment inside an 'if' condition in JavaScript How does the below code execute?
if(a=2 && (b=8))
{
    console.log(a)
}

OUTPUT
a=8

A: It is called operator precedence
(a=2 && (b=8))

In the above example. then results are evaluated against the main && sign.
(a=2 && (b=8)) evaluated to a = 2 && 8

So 2 && 8 return a = 8

A: You're setting (not comparing) a to 2 && (b=8). Since 2 is tru-ish the second half of the expression will be executed, i.e. a = true && (b = 8), i.e. a = (b = 8), i.e. a = 8.

A: Your statement is interpreted like
a = (2 && (b=8))

when you uses && statement, then last true statement value will be returned. Here (b=8) will becomes value 8 which is true and last statement.

A: It has nothing to do with the if statement, but:
if(a=2 && (b=8))

Here the last one, (b=8), actually returns 8 as assigning always returns the assigned value, so it's the same as writing
a = 2 && 8;

And 2 && 8 returns 8, as 2 is truthy, so it's the same as writing a = 8.

A: To understand what is going on, refer to the operator precedence and associativity chart. The expression a = 2 && (b = 8) is evaluated as follows:

*

*&& operator is evaluated before = since it has higher priority

*

*the left hand expression 2 is evaluated which is truthy

*the right hand expression b = 8 is evaluated (b becomes 8 and 8 is returned)

*8 is returned

*a = 8 is evaluated (a becomes 8 and 8 is returned)

Finally, the if clause is tested for 8.
Note that 2 does not play any role in this example. However, if we use some falsy value then the result will be entirely different. In that case a will contain that falsy value and b will remain untouched.

A: It's generally a bad idea to do variable assignment inside of an if statement like that. However, in this particular case you're essentially doing this:
if(a = (2 && (b = 8)));

The (b = 8) part returns 8, so we can rewrite it as:
if(a = (2 && 8))

The && operator returns the value of the right hand side if the left hand side is considered true, so 2 && 8 returns 8, so we can rewrite again as:
if(a = 8)


text:
Q: find Date Difference in Milliseconds I have two fields in hive : forwarddate & recieved date.
forwarddate has values like : 2018-07-18 01:51:30.655 +0200
recieved date has similar values.
I want to find the difference between forwarddate & recieved date in milliseconds


text:
Q: Parsing XML with DOM : Java I have an XML document that I've received from my server. I need to use this file (which is a WSDL, by the way) to print out a method signature for each of the methods in the WSDL. I've heard that I should be using DOM for this, but I'm not sure how it's used for accomplishing said task. Which parts of DOM should I be using to get the method information? (return type, method name, and parameters)

A: You don't have to use DOM, it's just one of the many possibilities. DOM is nice if you need random access to any part of the XML, like when using it to store and use structural data over an extended period of time.
Even then, these days you'll find JAXB to be a much more natural fit. It binds XML structure to Java classes, turning XML documents into instances of those classes for easy use in Java code. Since JAXB was created in the context of web service support you'll probably find good support there.
But I think for your purposes, you could even do with just an XSLT transformation. A stylesheet could be written that outputs simple text based on those elements that describe methods. XSLT in Java is simple to use, there's a default implementation in the Sun JRE and it's highly performant. I'd definitely look into XSLT as your first option.

A: There is a specialized library called WSDL4J that allows to parse WSDL files.

A: JAXB is much more powerful and much less code than manual DOM manipulation will be.


text:
Q: How do I connect a menuType to another viewcontroller? I want to make the below .merchant menu option link to another view controller I made the UI design for, non-modally. I have a feeling it has something to do with Subview and connecting my MerchantViewController. I do not want to add buttons and I want to use these "cases". Thanks so much, first post.
The possible childviewcontroller solution is mentioned in this video: https://youtu.be/vKh1b3ctCf4?t=556
func transitionToNew(_ menuType: MenuType) {
        topView?.removeFromSuperview()
        switch menuType {
        case .profile:
            let view = UIView()
            view.backgroundColor = .yellow
            view.frame = self.view.bounds
            self.view.addSubview(view)
            self.topView = view

        case .camera:
            let view = UIView()
            view.backgroundColor = .blue
            view.frame = self.view.bounds
            self.view.addSubview(view)
            self.topView = view

        //I want .merchant to link to a MerchantViewController
        case .merchant:
            let view = UIView()
            //view.backgroundColor = .blue
            view.frame = self.view.bounds
            self.view.addSubview(view)
            self.topView = view

        default:
            break

A: You could add the Merchant ViewController as a child of the current View Controller.
let merchantVC = MerchantViewController()  //setup MerchantViewController
let merchantView = merchantVC.view
self.view.addSubview(merchantView)
self.addChild(merchantVC)
merchantVC.didMove(toParent: self)
self.topView = merchantView


text:
Q: How to write some data to excel file(.xlsx) This is what I am trying to do:

*

*Create an Excel file (.xlsx) c://test/files/work1_4.13.14.xlsx with name + value (date).
example: work1_4.13.14.xlsx

*Set headers to the file.
example: [Name] [Age] [City].

*I have 3 List<string> objects containing names, ages, and cities that I need to fill into the Excel sheet.
This is the format I would like the data to be in:
Name   Age  City
Ben    20   xyz
Jack   25   xyz
Mike   45   zyx

How can I send the data to the Excel sheet in this format?

A: You can use ClosedXML for this.
Store your table in a DataTable and you can export the table to excel by this simple snippet:
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table );

You can read the documentation of ClosedXML to learn more. Hope this helps!

A: Recently, I tried npoi and it was very simple.
As requested, let's make code that output data to work1_4.13.14.xlsx file like:
Name   Age  City
Ben    20   xyz
Jack   25   xyz
Mike   45   zyx

Here's code
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;

namespace ExcelWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet1 = workbook.CreateSheet("Sheet1");

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("Name");
            row1.CreateCell(1).SetCellValue("Age");
            row1.CreateCell(2).SetCellValue("City");

            IRow row2 = sheet1.CreateRow(1);
            row2.CreateCell(0).SetCellValue("Ben");
            row2.CreateCell(1).SetCellValue("20");
            row2.CreateCell(2).SetCellValue("xyz");

            IRow row3 = sheet1.CreateRow(2);
            row3.CreateCell(0).SetCellValue("Jack");
            row3.CreateCell(1).SetCellValue("25");
            row3.CreateCell(2).SetCellValue("xyz");

            IRow row4 = sheet1.CreateRow(3);
            row4.CreateCell(0).SetCellValue("Mike");
            row4.CreateCell(1).SetCellValue("45");
            row4.CreateCell(2).SetCellValue("zyx");

            FileStream sw = File.Create("work1_4.13.14.xlsx");
            workbook.Write(sw);
            sw.Close();
        }
    }
}

I didn't used loop just to make it easy for beginner to understand.
.CreateRow(int index) creates new row at specified index.
row.CreateCell(int index) creates new cell at specified index in row.
cell.SetCellValue(string value) set value at row index.
Learn more:
Nuget: https://www.nuget.org/packages/NPOI
Code: https://github.com/nissl-lab/npoi
Examples: https://github.com/nissl-lab/npoi-examples

A: Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

A: It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb.  Using OleDb, it behaves as if you were writing to a table using sql.
Here is the code I used to create and write to an new excel file.  No extra references are needed
var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

A: Try this code
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

A: just follow below steps:
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();

oXL.Visible = false;


text:
Q: Incorrect timezone with NSCalendar I am attempting to grab a date using a specified timezone name, for example "America/New_York". For some reason, when I choose my correct timezone "America/Chicago", it shows the correct time (e.g. 9:41PM). However, when I choose New York, it should show an hour ahead (expecting 10:41PM), but I get an hour behind my current time (what I get: 8:41PM).
- (NSDate*)dateFromTimezone:(NSTimeZone*)timezone
{
    timezone = ( timezone == nil ? [NSTimeZone timeZoneWithName:CUSTOMTIMEZONE] : timezone );

    NSDate * date = [NSDate date];

    NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:timezone];
    [gregorian components:units fromDate:date];

    NSDateComponents* dateComponents = [[NSCalendar currentCalendar] components:units fromDate:date];
    [dateComponents setTimeZone:timezone];
    [dateComponents setCalendar:gregorian];

    return [gregorian dateFromComponents:dateComponents];
}


text:
Q: How to get value of particular cell at row command field of gridview I am using following expression.
int index = Convert.ToInt32(e.CommandArgument);

I want to get the row index, but the value of index is coming like 0x000000 something.

A: Try this:
int index = 0;
int.TryParse(e.CommandArgument as string, out index);

Not sure from your question in which context you're trying to obtain the index, but in the RowDataBound event handler, you would get the index as described here:
How to get index of the gridview row


text:
Q: The program unexpectedly exits when dragging the window and outputs 0xc000041d I am using webview2 as UI.
When I use JavaScript to call C# dragging the window, there is a probability that it will exit unexpectedly.
C# Code:
public const int WM_SYSCOMMAND = 0x0112;
public const int WM_LBUTTONUP = 0x0202;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;

[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll")]
public static extern bool ReleaseCapture();

public void DragMove()
{
    try
    {
        mainWindow.edge.IsEnabled = false;
        IntPtr hwnd = new WindowInteropHelper(mainWindow).Handle;
        Win32.SetCapture(hwnd);
        if (Win32.ReleaseCapture())
        {
            Win32.SendMessage(hwnd, Win32.WM_SYSCOMMAND, (IntPtr)(Win32.SC_MOVE + Win32.HTCAPTION), IntPtr.Zero);
        }
        mainWindow.edge.IsEnabled = true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

JavaScript Code:
window.chrome.webview.hostObjects.base.DragMove();

Is there any way to solve this problem?


text:
Q: Scan a directory in my webserver and list all of its images On my webserver under the directory path sites/default/files/app-images, I have the below images:

*

*image-1.png

*image-2.png

I am trying on Cron Run to:

*

*Scan this Directory.

*Check if directory is not empty.

*Loop through all available images and for each; get its filename.

*Delete that image.

So far, I did the below:
$Directory = new \RecursiveDirectoryIterator('sites/default/files/app-images');
$Iterator = new \RecursiveIteratorIterator($Directory);
$Regex = new \RegexIterator($Iterator, '/^.+\.png$/i', \RecursiveRegexIterator::GET_MATCH);
foreach ($Regex as $info) {
  $filename = $Regex->getFilename();
// Display a message
\Drupal::messenger()->addWarning(t("$filename"));
}

*

*Is it the best method to use in term of performance ?

*I am getting the filename of the images with file extension like image-1.png and image-2.png but how to get the filename without the file extension, Ex: image-1 and image-2 ?

*How to delete the image after getting its name ? I have tried unlink($filename); but with no avail, the image still exist in the directory !
Can anyone set me on the right track please ?
Thank you