text:
Q: Codeigniter - Reservation Function I've been trying to finish my reservation function, and some of you may even already know me since I've been trying to ask many questions here for consecutive days regarding this function. I've been trying to create a reservation function, wherein users can reserve for the basketball court any date they would like to. An admin will approve the reservation, because sometimes, the courts are used by the village administrators therefore it cannot be used. So in approving, there will be a validation to check whether that date has already been taken, and if it is taken, then it will not be approved. Here's my database table.

So the reservation_start and reservation_end numbers stand for their respective hours, 6 as 6:00 PM, 7 as 7:00 PM, and so on. What I did was create a model to check whether a slot was already taken, and I created an array which serves as switches whenever an hour was taken. I also used the "group_by" query in order to group my reservation dates into one, so that the switches will be reset whenever there is a different date. My problem is that the switches are carried over into the other dates. In the example above, 02/26/2017 has been reserved from 7:00 PM to 10:00 PM. This means that the switches will be "on" from 7 until 9(in order for 10:00 PM as the start time to be still reserved). Then, on March 3, the switches are being carried over, which means that I cannot reserve them since it reads that 7:00 has been taken, therefore I cannot reserve from 6:00 to 8:00 PM.
Here's the code.
function checkexisting_reserve_courtone()
{
    $checkresult = $this->db->select('*')->from('courtone_reservation')->where('reservation_status', 1)->group_by('reservation_date')->get();
    $resultreserve = $checkresult->result();

    $tdX = array(0,0,0,0,0,0,0,0,0,0,0);
    foreach($resultreserve as $result)
    {

        while($result->reservation_start < $result->reservation_end)
        {
            $tdX[$result->reservation_start] = 1;
            $result->reservation_start++;
        }
    }

    foreach($resultreserve as $result)
    {
        $reserveactualend = $result->reservation_end - 1;
        if($tdX[$result->reservation_start] == 1 || $tdX[$reserveactualend] == 1)
        {
            return FALSE;
            break;
        }
    }
    return TRUE;
}

Is there a get-around here? Any help would greatly be appreciated!


text:
Q: matlab oop "use data of hole class" for calculation First, sorry for the bad title - I'm new to OO programming - basically I'd like to understand how Matlab works with oop classes.
Before I ask my question, here is a basic example of what I want to do:
I have two houses and some data about them and I got the idea, to work with oop classes. Here is my .m file.
classdef building
  properties
  hohe = 0;
  lange = 0;
  breite = 0;
  xabstandsolar = 0;
  yabstandsolar = 0;
end

methods
  function obj = building(hohe, lange, breite, xabstandsolar, yabstandsolar)
    obj.hohe = hohe;
    obj.lange = lange;
    obj.breite = breite;
    obj.xabstandsolar = xabstandsolar;
    obj.yabstandsolar = yabstandsolar;
   end

   function hohenwinkel(h)
     h = h
     d = sqrt(obj.xabstandsolar^2 + yabstandsolar^2);
     gamma_v = atand((obj.hohe - h)/(d));
   end
  end
end

I filled it with some data - for example
>>H1 = building(10,8,6,14,8)
>>H2 = building(18,8,6,14,0)

And now I want to calculate "gamma_v" (as an 1x2 array) for each building. Any ideas, how I can archive this?
Edit:
 I want to create gamma_v (as an array) automatically for all objects in the class "building". There will be a lot more "houses" in the final script.

A: Your hohenwinkel method needs to accept two input arguments. The first argument for non-static methods is always the object itself (unlike C++, you'll have to explicitly list it as an input argument) and the second input will be your h variable. You'll also want to actually return the gamma_v value using an output argument for your method.
function gamma_v = hohenwinkel(obj, h)
    d = sqrt(obj.xabstandsolar^2 + obj.yabstandsolar^2);
    gamma_v = atand((obj.hohe - h)/(d));
end

Then you can invoke this method on each building to get the value
gamma_v1 = hohenwinkel(H1);
gamma_v2 = hohenwinkel(H2);

If you want to have an array of buildings, you can create that array
houses = [building(10,8,6,14,8), building(18,8,6,14,0)];
gamma_v = hohenwinkel(houses);

and then construct your hohenwinkel function to operate on each one and return the result
function gamma_v = hohenwinkel(obj, h)

    if numel(obj) > 1
        % Compute hohenwinkel for each one
        gamma_v = arrayfun(@(x)hohenwinkel(x, h), obj);
        return
    end

    d = sqrt(obj.xabstandsolar^2 + obj.yabstandsolar^2);
    gamma_v = atand((obj.hohe - h)/(d));
end

A: there is some tricky solution (and its not recommended)(@Suever solution is better)
 you should create a handle class
 classdef gvclass<handle
       properties
            gvarr=[];
       end
       methods
            function setgvarr(obj,value)
                  obj.gvarr=[obj.gvarr,value];
             end
       end
  end

then use this class in your building class
classdef building<handle
properties
  gv
  hohe = 0;
  lange = 0;
  breite = 0;
  xabstandsolar = 0;
  yabstandsolar = 0;
end

methods
  function obj = building(hohe, lange, breite, xabstandsolar, yabstandsolar,handle_of_your_gv_class,h)
    obj.hohe = hohe;
    obj.lange = lange;
    obj.breite = breite;
    obj.xabstandsolar = xabstandsolar;
    obj.yabstandsolar = yabstandsolar;
    obj.gv=handle_of_your_gv_class;
    obj.hohenwinkel(h);
   end

   function hohenwinkel(obj,h)

     d = sqrt(obj.xabstandsolar^2 + yabstandsolar^2);
     gamma_v = atand((obj.hohe - h)/(d));
     obj.gv.setgvarr(gamma_v);
   end
  end
end

finally before creating any building you should create an object of gv class and pass it to the building constructor,
Egv=gvclass();
H1 = building(10,8,6,14,8,Egv,2)
H2 = building(18,8,6,14,0,Egv,3)

and to access gv array:
 Egv.gvarr

you should do more effort on this issue to debug possible errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extending 64 bit support to existing iOS app I have read Apple's Guidelines for converting app to 64 bit binary and few other web pages.I am using Xcode 6 and I believe that if Architectures contain "Standard Architecture(armv7,arm64)" and Valid Architectures contain "armv7,armv7s" then it means my app supports 64 bit binaries.
Can someone please confirm if my understanding is correct?
The second issue is that my project contains a number of libraries.I believe that I will have to convert those libraries to 64 bit as well in case the library vendors don't.
In future, I am planning to use cocoa pods, but I believe cocoa pods is not supporting 64 bit binaries right now. Can someone please confirm if my belief is correct? Also what can be done in this case?
Has someone here converted their app to 64 bit using cocoa pods?

A: Your project as well as all the included libraries or frameworks should include arm64 as supported architecture like below:
Please note that you are missing arm64 in your Valid Architecture menu.
Valid Architectures : Specify the architectures you want to build:
amv7 and armv7s are for 32 bit devices.
arm64 is for 64 bit devices

You may also want to look at this link for more details:
About CocoaPods:
Cocoapods has no relation to 64Bit. As Cocoapods is just a dependency manager and does not gets included in you source code. It works with your build tool chain.
So what you should be worried about is that all the pods you are using should be 64Bit compatible.


text:
Q: Area 51 doesn't show how to propose a new site in FAQ It seems to me that Area 51 should tell how to propose a new site. However, this is what it says to do to create a site:

How do I start a new site?
If your area of expertise doesn't already have a Stack Exchange site,
  propose it! Stack Exchange sites are free to create and free to use.
  All we ask is that you have an enthusiastic, committed group of expert
  users who check in regularly, asking and answering questions.
The creation of Stack Exchange sites is a democratic, community-driven
  process. That does not mean the majority of Area 51 users have to love
  your site idea. It simply means you have to recruit a community of
  users large enough so that questions get good answers quickly. Reach
  out to other experts to build support for your site; bloggers,
  enthusiasts, and support groups can all benefit from a world-class,
  canonical collection of expert answers to the hardest questions.

Note that it mentions finding a group of experts (Which is important), but doesn't say anything about the mechanics of proposing something. It seems that this is a bit of a mis-hap. I do know that it says on the bottom of the main site, as listed below, but it still seems like that should be in the FAQ...

Can't find what you're looking for? Select a category listing to the
  left and propose your site there!


text:
Q: Swift: Function call from custom class throws exception I have a cusom class for NSButton. Pressing the button calls a function in the main AppDelegate.swift by AppDelegate().startTask(), which fires an NSTask and animates an NSProgressIndicator via IBOutlet in AppDelegate.swift.
@IBOutlet weak var mySpinner: NSProgressIndicator!

func startTask() -> Void
{
    mySpinner.startAnimation(true)
    ...
}

It throws an error at mySpinner.startAnimation(true):

fatal error: unexpectedly found nil while unwrapping an Optional value
  (lldb)

What am I missing? Does AppDelegate not have access to this IBOutlet when called from a custom class? Calling this function from within AppDelegate works fine.

A: Problem
With this line
AppDelegate().startTask()

you are creating a new AppDelegate. In this new instance mySpinner is not populated and this line does crash
mySpinner.startAnimation(true)

because mySpinnder is nil.
Solution
You should instead retrieve the instance of AppDelegate already created
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
appDelegate.startTask()


text:
Q: How can I count alphabet characters efficiently? I initialized an array of characters, to put all uppercase and lowercase alphabets.
#include <iostream>
using namespace std;

int main () {
    char c;
    int cnt = 0;
    cout << "Enter 0 to view the results " << endl;
    char arr[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    while (1) {
        for (int i = 0; i < 100000000; i++)
        {
            cin >> c;
            if (c == arr[i]){
                cnt++;
            }
            else if (c == '0'){
                break;
            }
            else{
                cout << "Please enter only characters!" << endl;
            }
        }
        if (c == '0')
            break;
    }
    cout << cnt << endl;
    return 0;
}

I know that this code is inefficient.

*

*How to write this code without break;?

*If there's a better way to do that without using array, please mention it.

A: OP's question is very unclear but what I have understood from the comments is OP trying to find a simpler/similar way of counting someone's input for lowercase/upperCase alphabets and keep doing so until the user enters in a 0, I looked online and i found a better way and did some adjustments, it is pretty straight forward, here it is below.
#include <algorithm>
#include <iostream>
#include <cctype>
#include <string>

using namespace std;

int main()
 {
    string s = "TEST";
    while(s != "0"){
        cout << " Enter text: ";
        getline(cin, s);
        size_t count_alpha = count_if(s.begin(), s.end(),
            [](unsigned char ch) { return isalpha(ch); });
        cout << "Alphabets: " << (  count_alpha)<<endl ;
    }
}


text: Q: How to apply marquee effect on the Collapsing Toolbar title of an android app In my android application,in which I am designing using design support library, I need to make the collapsing toolbar, title and give marquee effect as the text coming from my server can sometimes be long. This is currently giving me a dot dot dot after fitting text. I was able to use marquee in list item of RecyclerView but same when done on collapsing toolbar title fails for me.


text:
Q: Solving exponential equations from 2 points I have been working on this code for a while now, and since I am only in 9th grade, I don't have much algebra experience. I have tried many things, and this is where my scripts are now.(Note, this is just the JavaScript, the id's being called for are the boxes with the info and the output).

That only works with "b" in the form y = a(b)x from the points (0,4) and (1,8). A is always -3 when I plug those points into the boxes. The equation is completely different when I use points from the same line. Any got solutions?

A: you can't use bx in the equation for a before you have assigned it a value. those two lines are out of order. EQX and EQY don't get assigned to anything if EX1 = EX2 or EY1 = EY2. eval is a taboo word in javascript and should be used with extreme caution. Other people will harass you about using it. Read up about why it's bad and decide for yourself.


text:
Q: Use xbindkeys & xdotool to bind mouse buttons I am very new on Ubuntu desktop and just like it so much. Now i get a problem. My OS is Ubuntu 20.04 LTS.
I am a designer. I use a lot of middle click when i do 3d drawings. (A lot of my mouse's middle licks have been dead already). I want to bind button 8 & 9 to middle click.
By the way, I found another function can exchange button:
xmodmap -e "pointer = 1 9 3 4 5 6 7 8 2
But I still want more button 2. So I tried xbindkeys & xdotool
I try to follow the webside:
https://www.linuxuprising.com/2019/11/how-to-bind-mouse-buttons-to-keyboard.html
what I add in ".xbindkeysrc" file is:
"xdotool key 'z'"
    b:8

"xdotool click '2'"
    b:9

Or
"xdotool click 2"
    b:9

Now my problem is Button 8 works well. (can use as z) My button 9 doesn't work.
And I have try command in terminal:
xdotool click 2
xdotool mousedown 2

it works well.
Anybody can help me on this? Thanks a lot. But my English is poor, use simple English please.


text:
Q: Calculate time difference over the first and the last table row Within postgresql, I'm trying to write a query that calculates the time difference between a time stamp of the first row and a time stamp of the last row:
(select public."ImportLogs"."DateTimeStamp" as migration_start from public."ImportLogs" order by public."ImportLogs"."DateTimeStamp" asc limit 1)
union
(select public."ImportLogs"."DateTimeStamp" as migration_end from public."ImportLogs" order by public."ImportLogs"."DateTimeStamp" desc limit 1);

I tried to get the time difference between migration_start and migration_end, but I couldn't get it to work. How can I achieve this?

A: We can substract min(DateTimeStamp) from the max(DateTimeStamp)` and cast the difference as time.

select
  cast(
     max(DateTimeStamp)
   - min(DateTimeStamp)
     as time) TimeDiffernce
from ImportLogs

| timediffernce |
| :------------ |
| 00:00:10      |

db<>fiddle here


text:
Q: How does global variable work in Angular, Ionic Perhaps this is a dumb question to ask but I am new to front-end development and come from a backend background. Doing things as so in a java class is not threadsafe if the object created is a singleton that is shared across all threads
class{
  String username;
}

In Angular what happens if we have
export class RegistrationPage implements OnInit {

  firstname: string = "";

}

Are components in Angular singletons?

A: Generally components are not singleton. And if you declare a public variable in a component, it can only be accessed from the files of the same module(for example html file).
But services are singleton. You can access public variables declared in the services globally.
Is that the answer you are looking for?


text:
Q: Defining second derivative boundary condition using DEigensystem I tried to solve a fourth-order eigenvalue problem with boundary conditions on high order derivative.
For example, the following equation,
$$\frac{\partial d}{\partial t}+\frac{\partial^4 d}{\partial x^4}=0$$
with a homogeneous Dirichlet condition at the edges and a homogeneous second derivative condition, also at the edges of the domain.
The problem, I think, is with the second derivative condition. All the example I found was for Dirichlet and/or Neumann condition, and then it works.
I tried to define the problem like that,
 eqn = D[u[t, x], {t, 1}] + D[u[t, x], {x, 4}] == 0;
 bc1 = {u[t, 0] == 0, u[t, 1] == 0};
 bc2 = {Derivative[0, 2][u][t, 0] == 0, Derivative[0, 2][u][t, 1] == 0};
 {vals1, fans1} =
 DEigensystem[{eqn + bc2, bc1}, u[t, x], {x, 0, 1}, 1];`

Or like that,
 {vals, fans} =
 DEigensystem[{D[u[t, x], {t, 1}] + D[u[t, x], {x, 4}] == 0,
 DirichletCondition[u[x] == 0,
 True], (D[u[t, x], {x, 2}] /. x -> 0) ==
 0, (D[u[t, x], {x, 2}] /. x -> 1) == 0}, u[t, x], {x, 0, 1}, 4];`

both ways I get the following error,
Lists {vals,fans} and DEigensystem[{(u^(0,4))[t,x]+(u^(1,0))
[t,x]==0,DirichletCondition[u[x]==0,True],(u^(0,2))[t,0]==0,(u^(0,2))
[t,1]==0},u[t,x],{x,0,1},4] are not the same shape.

Thanks,
Israel.


text:
Q: How to renew the lock after the lock duration has expired? Using Azure Service Bus Session Queue Currently I am using Azure Service Bus Session Queue by configuring the 30 seconds as a lock duration.
For example, I have one session with 3 messages

*

*While processing the first message to took more time, after that I am calling CompleteAsync() for deleting the message from the queue. But whenever I execute CompleteAsync(),  I am getting SessionLockLostException.
await session.CompleteAsync(message.SystemProperties.LockToken);

I want to renew the lock whenever lock has expired.
I followed this documentation, but I am not getting any sample for renew lock token.

A:
I want to renew the lock whenever lock has expired.

Not possible. Once lock token has expired, the broker will consider it unlocked and serve to other consumers. Instead, you should review your configuration and design approach. If you receive messages that can take longer to process, don't use MaxLockDuration of 30 seconds, up it up. If 5 minutes is not sufficient, look at either extending the lock time manually before it expires, or if using the built-in message pump, configure the maximum time to auto-renew the lock.


text:
Q: ImageMagick:: Throwing DLL error --> IM_MOD_RL_PNG_.dll': The specified module could not be found I am trying to run a simple comparison ROBOT FrameWork Script. Here is the script..
    *** Settings ***
Library   String
Library   OperatingSystem

*** Variables ***
${IMAGE_COMPARATOR_COMMAND}     D:\\"Program Files"\\ImageMagick-7.0.7-Q8\\convert __REFERENCE__ __TEST__ -metric RMSE -compare -format  "%[distortion]" info:

*** Test Cases ***
Image Comparison Ok
  Compare Images    D:/Project/Lg/imageCompare/CollectorCreation_IE.png    D:/Project/Lg/imageCompare/CollectorCreation_Chrome.png #  0.1

#Image Comparison NOk
#  Compare Images    D:/Project/Lg/imageCompare/CollectorCreation_IE.png    D:/Project/Lg/imageCompare/CollectorCreation_Chrome.png   0.1

*** Keywords ***
Compare Images
   [Arguments]      ${Reference_Image_Path}    ${Test_Image_Path}    ${Allowed_Threshold}
   ${TEMP}=         Replace String     ${IMAGE_COMPARATOR_COMMAND}    __REFERENCE__     ${Reference_Image_Path}
   log  ${TEMP}
   ${COMMAND}=      Replace String     ${TEMP}    __TEST__     ${Test_Image_Path}
   log  ${COMMAND}
   Log              Executing: ${COMMAND}
   ${RC}            ${OUTPUT}=     Run And Return Rc And Output     ${COMMAND}
   Log              Return Code: ${RC}
   Log              Return Output: ${OUTPUT}
   ${RESULT}        Evaluate    ${OUTPUT} < ${Allowed_Threshold}
   Should be True   ${RESULT}

but I ran into issue with dll's. Not sure what is the issue.
Return Output: convert: unable to load module 'd:\Program Files\ImageMagick-7.0.7-Q8\modules\coders\IM_MOD_RL_PNG_.dll': The specified module could not be found.
 @ error/module.c/OpenModule/1275.
convert: no decode delegate for this image format `PNG' @ error/constitute.c/ReadImage/509.
convert: unable to load module 'd:\Program Files\ImageMagick-7.0.7-Q8\modules\coders\IM_MOD_RL_PNG_.dll': The specified module could not be found.
 @ error/module.c/OpenModule/1275.
convert: no decode delegate for this image format `PNG' @ error/constitute.c/ReadImage/509.
convert: unable to open image '#': No such file or directory @ error/blob.c/OpenBlob/3323.
convert: unable to open image '#': No such file or directory @ error/blob.c/OpenBlob/3323.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/509.
convert: no images defined `info:' @ error/convert.c/ConvertImageCommand/3275.

I could see this dll in the given location bt program is not able to pick.
I am using Windows 7 64 bit machine and i installed "ImageMagick-7.0.7-14-Q16-x64-dll.exe" and got above issue and tried with "ImageMagick-7.0.7-14-Q8-x64-dll.exe" (i am picking from here) same result.
Can some one help me out with issue. I am guessing it would be issue with the installed version.
C:\Users\bbanduch>magick -version
Version: ImageMagick 7.0.7-14 Q8 x64 2017-12-06 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Visual C++: 180040629
Features: Cipher DPC Modules OpenMP
Delegates (built-in): bzlib cairo flif freetype gslib jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib


text:
Q: Universal Analytics, will this work: Remarketing + Anonymise IP? So I need to have this feature in Analytics code to anonymize IP from the visitors:
ga('set', 'anonymizeIp', true);

But I also need remarketing for AdWords campaigns:
ga('require', 'displayfeatures');

So my question is: will remarketing work with anonymize IP?

A: Yes, this will work. Remarketing does not depend on the IP address, it uses the (3rd party) cookie from the Google display network.


text:
Q: Not Able to Add Migrations in .NET 6 I keep getting this message every time I try to add a migration. I'm using N-Layer architecture and it always points at my API and not my context class library as i set it in my package manager console

Your startup project 'API' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

Note that I'm using EF Core Design package in my context class library and I referenced it in my API project.


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError: main
Possible Duplicate:
Exception in thread "main" java.lang.NoSuchMethodError: main

I got the above message. The code is as follows:
class Test
{
 public static void main(String ar[])
 {
  printf("hai");
 }
}

How is this problem caused and how can I fix it?

A: The class which you're trying to execute doesn't have a main method.
Since your main method looks syntactically fine, this can have two causes:

*

*You're executing the wrong class.

*The actual class file doesn't contain this code.

The solution is obvious:

*

*Make sure that your command is pointing the correct class file, you might have multiple class files with the same name and be sitting in the wrong directory.

*Make sure that you've compiled the correct source file into the correct class file before, you might have edited one and other and forgot to recompile.

A: In addition to the problem that's causing the current exception (see BalusC's answer), the proper "Hello World" in Java is:
class Test
{
    public static void main(String[] args) {
        System.out.println("hai");
    }
}

See: java.lang.System

A: I see your problem, the signature is not correct.
It should be public static void main(String[] args)

A: It could also be a class path issue which causes Eclipse to get confused and not able to find your class when it tries to run it.  I would look at the Java Build Path in the Project Properties to make sure there are no errors.


text:
Q: PrimeFaces tags not working with new design using jquery and other jquery libs I am using PrimeFaces some tags in my jsf pages .its working fine in my old design but when i promoted my application to new design in which is extensively use of jquery and other jquery liberaries like bootstrap,morris and slimscroll etc.
my header page liberaries are as below which i tried .
      <script src="resources/js/jQuery-2.1.3.min.js"/>
    <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js" type="text/javascript"></script>
    <script>
        $.widget.bridge('uibutton', $.ui.button);
    </script>
    <script src="resources/js/bootstrap.min.js"/>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="resources/js/morris.min.js"/>
    <script src="resources/js/jquery.sparkline.min.js"/>
    <script src="resources/js/jquery-jvectormap-1.2.2.min.js"/>
    <script src="resources/js/jquery-jvectormap-world-mill-en.js"/>
    <script src="resources/js/jquery.knob.js"/>
    <script src="resources/js/daterangepicker.js"/>
    <script src="resources/js/bootstrap-datepicker.js"/>
    <script src="resources/js/bootstrap3-wysihtml5.all.min.js"/>
    <script src="resources/js/icheck.min.js"/>
    <script src="resources/js/jquery.slimscroll.min.js"/>
    <script src="resources/js/fastclick.min.js"/>
    <script src="resources/js/dashboard2.js"/>
    <script src="resources/js/app.min.js"/>
    <script src="resources/js/dashboard.js"/>
     <script type="text/javascript">
        $.noConflict();
        jQuery.noConflict();
        $ = jQuery;
    </script>
/// and in page where i use primefaces tag is below
    <script src="resources/js/jquery-latest.js"/>
    <h:outputScript library="primefaces" name="jquery/jquery.js"        target="head" />
   $.noConflict();
    jQuery.noConflict();
        $ = jQuery;
     </script>

     <p:autoComplete value="#{orderBean.customerBean}"
                        id="customer"
                        completeMethod="#{orderBean.autoCompleteCustomer}"
                        var="c"
                        itemLabel="#{c.customerName}"
                        itemValue="#{c}"
                        converter="customerc"
                        forceSelection="true"
                        required="#{orderBean.isRequired()}"
                        requiredMessage="customer:Please enter Customer!!">
            <f:facet    name="itemtip">
                <h:panelGrid  columns="2"
                              border="1"
                              styleClass="itemTip"
                              cellspacing="1"  cellpadding="10" >
                    <f:facet name="header">
                        <h:outputText
                            value="#{c.customerName}"
                            style="alignment-adjust: central;" />
                    </f:facet>
                    <h:outputText value="Customer Type" />
                    <h:outputText value="#{c.customerType}" />

                    <h:outputText value="Contact Person" />
                    <h:outputText value="#{c.contactPerson}" />
                    <h:outputText value="Email" />
                    <h:outputText value="#{c.customerEmail}" />
                    <h:outputText value="Phone No" />
                    <h:outputText value="#{c.customerPhoneNo}" />
                    <h:outputText value="GST No" />
                    <h:outputText value="#{c.customerGstNo}" />
                </h:panelGrid>
            </f:facet>
            <p:ajax event="blur" process="customer"
                    listener="#{orderBean.handleCustomerBlur}"
                    update="customer, productName, quantity, packingName, packs,orderTable, addToListButton ,addPackingButton" >
            </p:ajax>

        </p:autoComplete>

but primefaces tag is not working  due new jquery files included in my design .please any one help me to overcome this situtation so that i can work with new design futhur.


text:
Q: How to add a keybind from controller javafx I am (still) working on my todo application. While I'm thinking about where to place the save button, I figured I would add a keybind to save too.
I added the key bind in my main class like this:
final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.S,
        KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent event) {
        if (keyComb1.match(event)) {

        }
    }
});

However, the stuff I need to do on the CRL + S is in the controller class. How can I bridge this or make it so the controller can get this information?
Edit: I do not want to pass any info. Just the fact that the event happened.
Edit 2.0:
I have solved the issue. The solution was to get the controller instance at the start, save it and when the event was called, use the said method.


text:
Q: Trigger to SELECT schema rows based on WHERE condition I am learning about triggers.
Generally it seems triggers are employed on the backend to perform some action on a schema. I was interested if it was possible for a trigger to return data on a SELECT statement to the main application.
In the table I'm working with we have several string columns followed with a geom (geometry::polygon) column which would contain the WKBT LAT/LONG values.
I'd like to return the rows which meet some WHERE clause AND also return the geom [LAT/LON] in WKBT format. By return I am interested in returning data to the main application.
I seek any examples.
Currently I build a list of all our column names {colA, colB, colC, colD} and then append the following as the last entry: public.ST_ASText(geom).
So I obtain a SELECT as follows....
SELECT colA, colB, colC colD, public.ST_AsText(geom) FROM schemaA WHERE .
So the crux of the problem here I cannot use SELECT * since I must convert the geom (LAT/LON pairs) to WKBT and this must be in the select along with every other column name defined, whether I use that column data or not.  I definitely require the geom column in WKBT format.
This is passed via our DEVART interface.
I was wondering if there is a better way to do this,

A: No, there is no "select" trigger in Postgres.
What you can do is to implement a view that transform the data for you.
CREATE OR REPLACE VIEW myView AS
    SELECT
      mycol1,
      mycol2,
      geom,
      st_astext(geom) WKT
    FROM myTable;

If you need to be able to update the data, you would then put an insert/update/delete trigger on the view, that will manipulate the base table.


text:
Q: SQL - Insert Into Aes_Encrypt Statement Error MySQL is rejecting a certain part of my query. It's giving me the error 'A comma or closing bracket was expected (near ()' on line 18.
According to what I've found so far about the AES_ENCRYPT function, is that the statement itself is correct, but for some reason it keeps rejecting the query.
When I've used the query several months ago, it was working fine but for some reason now that I've been more actively working on the site itself, it stopped working for some reason and can't completely re-create the database.
The query:
    /* Adding data to the User entity */
INSERT
INTO
  Users(
    FirstName,
    LastName,
    EmailAddress,
    Password2,
    City,
    Street,
    PostalCode,
    PhoneNumber
  )
VALUES(
  'Test',
  'Administrator',
  'administrator@thisisatest.com',
  AES_ENCRYPT('123456', 'administrator'),
  '',
  '',
  '',
  ''
);


text:
Q: Login into stackoverflow and stackoverflow careers simultaneously It seems that you cannot be logged into stackoverflow and stackoverflow careers simultaneously. If you are already logged on to stackoverflow and try to log on to careers, it will bring you back to the careers homepage and not give you any kind of indication that the login has failed. Is this intended? Is there some reason that you can't be logged into both at the same time?

A: Do you have the same sign-in on both sites?  Due to the new central authentication feature, if you have different sign-ins you may experience weirdness, and in fact may be unable to sign in to both at the same time.

A: In this case, we had duplicate accounts. We combined them.


text:
Q: How can I tell whether/where python a virtualenv has been set up? (aka installing lxml on bitnami's djangostack) I'm working on a django application on the bitnami djangostack.  I want to use the lxml library, but I haven't been able to install it.  Or rather, I haven't been able to install it where django can find it.
I've already used apt-get to install the libxml2, libxslt, and python-dev dependencies. Both of these commands report success*:
sudo pip install lxml
sudo apt-get install python-lxml

easy_install fails with a super-long error message that makes me think it can't find the dependencies. (I've run into this problem before.)
When I open up python or call python manage.py shell and try "import lxml", I get
"ImportError: No module named lxml"

As best I can tell, bitnami has set up a virtual environment for django, and pip and aptitude are installing lxml perfectly -- to the wrong python. Assuming that's all correct, how do I get lxml installed to the right one?

A: When you use apt-get install you are installing system libraries. BitNami DjangoStack is self-contained and independent. You could upgrade or remove your system libraries with apt-get and it would not be affected. Unfortunately lxml is not included in the stack nor libxslt which is a depency. We will include it in a future version however please find below the steps for manualing installing lxml on top of the python version included in BitNami DjangoStack.
You will need to use the system libraries for libxslt and libxml2. Be sure that you have them installed:
sudo apt-get install libxml2 libxml2-dev libxslt1.1 libxslt1-dev

Download lxml and uncompress it:
wget http://lxml.de/files/lxml-2.3.2.tgz
tar zxvf lxml-2.3.2.tgz
cd lxml-2.3.3

Load the BitNami environment:
. path_to_your_djangostack_installation/scripts/setenv.sh <-- notice the space between the dot and the path to the script.
which python <-- the output should be the python version from BitNami.
Install lxml specifying the path to your system libraries (notice that you should execute this command in the lxml directory):
python setup.py install --with-xslt-config=/usr/bin/xslt-config --with-xml2-config=/usr/bin/xml2-config

Now executing import lxml in the python console should work.
(This was already replied here)

A: There have been a couple of blog postings on installing this library on shared hosting. http://rhodesmill.org/brandon/2009/installing-lxml-on-webfaction/
How to install lxml for python without administative rights on linux?


text:
Q: Adding space char to each item appending to string - have to erase last item. How to improve This function, vec2string takes a vector of char's and converts to a hex string representation but with a blank space between each byte value.  Just a formatting requirement in my app.  Can anyone think of a way to remove the need for that.
std::string& vec2string(const std::vector<char>& vec, std::string& s) {
   static const char hex_lookup[] = "0123456789ABCDEF";
   for(std::vector<char>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
      s.append(1, hex_lookup[(*it >> 4) & 0xf]);
      s.append(1, hex_lookup[*it & 0xf]);
      s.append(1, ' ');
   }
   //remove very last space - I would ideally like to remove this***
   if(!s.empty())
      s.erase(s.size()-1);

   return s;
}

A: You could add a check in the loop, before appending the characters, if the string is not empty and then add a space. Like:
for (...)
{
    if (!s.empty())
        s += ' ';
    ...
}

A: std::string& vec2string(const std::vector<char>& vec, std::string& s) {
   static const char hex_lookup[] = "0123456789ABCDEF";
   if (vec.empty())
      return s;
   s.reserve(s.size() + vec.size() * 3 - 1);
   std::vector<char>::const_iterator it = vec.begin();
   s.append(1, hex_lookup[(*it >> 4) & 0xf]);
   s.append(1, hex_lookup[*it & 0xf]);
   for(++it; it != vec.end(); ++it) {
      s.append(1, ' ');
      s.append(1, hex_lookup[(*it >> 4) & 0xf]);
      s.append(1, hex_lookup[*it & 0xf]);
   }
   return s;
}

A: I'd start by separating the hex conversion into its own little function:
std::string to_hex(char in) {
    static const char hex_lookup[] = "0123456789ABCDEF";
    std::string s;
    s.push_back(hex_lookup[(in>>4) & 0xf];
    s.push_back(hex_lookup[in & 0xf];
    return s;
}

Then I'd use std::transform to apply that to the whole vector, with my infix_ostream_iterator and a std::stringstream to put the pieces together.
#include <sstream>
#include <algorithm>
#include "infix_iterator"

std::string vec2string(const std::vector<char>& vec) {
    std::stringstream s;

    std::transform(vec.begin(), vec.end(),
                   infix_ostream_iterator<std::string>(s, " "),
                   to_hex);
    return s.str();
}

Also note that rather than modifying an existing string, this creates and returns a new string. At least in my opinion, modifying an existing string is a poor idea -- simply producing a string is much cleaner and more modular. If the caller wants to combine the results into a longer string, that's fine, but it's better for the lower-level function to just do one thing cleanly, and let the higher level function decide what to do with the result.

A: If you have Boost, use algorithm/string/join.hpp.  Otherwise, you could try the Duff's Device approach:
string hex_str(const vector<char>& bytes)
{
    string result;
    if (!bytes.empty())
    {
        const char hex_lookup[] = "0123456789ABCDEF";
        vector<char>::const_iterator it = bytes.begin();
        goto skip;
        do {
            result += ' ';
        skip:
            result += hex_lookup[(*it >> 4) & 0xf];
            result += hex_lookup[*it & 0xf];
        } while (++it != bytes.end());
    }
    return result;
}

A: Use boost::trim documentation
boost::trim(your_string);


text:
Q: Centrar tabla html Buenas tengo estas tablas generadas en pdf mediante php en html, y me gustaría centrarlas, pero no lo consigo. Adjunto el código:
 $content .= '

Jornada 1

'.$user['Fecha_Inicio'].'

        LOCAL

        VISITANTE

  ';
  $content .= '

      '.$user['Nombre_E7'].'
      VS
      '.$user['Nombre_E8'].'

      '.$user['Nombre_E9'].'
      VS
      '.$user['Nombre_E4'].'

      '.$user['Nombre_E5'].'
      VS
      '.$user['Nombre_E2'].'

      '.$user['Nombre_E1'].'
      VS
      '.$user['Nombre_E6'].'

      '.$user['Nombre_E3'].'
      VS
      '.$user['Nombre_E10'].'

';
 $content .= '
';

Gracias,
Saludos

A: Yo, donde pone
 añadiría una nueva clase, por ejemplo algo como esto:

Y luego definiría la clase tableCenter con text-align='center' o, según si tienes o vas a poner más clases o elementos, con un margin='0 auto'

A: Puedes centrar la tabla a su contenedor creando una clase, por ejemplo .table-center e indicar los margenes y ancho de la misma.
Demo:

.table.table-center {
  width: auto;
  margin: 0 auto;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Jornada 1

'.$user['Fecha_Inicio'].'

          LOCAL

          VISITANTE

        '.$user['Nombre_E7'].'
        VS
        '.$user['Nombre_E8'].'

        '.$user['Nombre_E9'].'
        VS
        '.$user['Nombre_E4'].'

        '.$user['Nombre_E5'].'
        VS
        '.$user['Nombre_E2'].'

        '.$user['Nombre_E1'].'
        VS
        '.$user['Nombre_E6'].'

        '.$user['Nombre_E3'].'
        VS
        '.$user['Nombre_E10'].'


text:
Q: Best strategy for finding tasks with unobserved exceptions Suppose I have the following code:
private static void Run()
{
    TaskScheduler.UnobservedTaskException += delegate { Console.WriteLine("Unobserved task exception!"); };

    try
    {
        RunAsync().Wait();
    }
    catch (Exception)
    {
    }

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    Thread.Sleep(Timeout.InfiniteTimeSpan);
}

private static async Task RunAsync()
{
    var task1 = ThrowAsync();
    var task2 = ThrowAsync();

    await task1;
    await task2;
}

private static async Task ThrowAsync()
{
    throw new Exception("Test exception");
}

This code outputs Unobserved task exception! because the exception in task2 is not observed.
My question is the following: is there any way to programmatically determine which task had an unobserved exception? For example, I want to get a stack trace for a method which invoked a task or something like this:
Unobserved exception: task2 in RunAsync()

Sadly, exception stack trace is not enough. The code above is just a demonstration, in a real-world application I sometimes have unobserved task exceptions with a stack trace like this:
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.HttpApplication.get_CurrentModuleContainer()
   at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)

A: One would be able to tell which Task instance had its exception unobserved. That would be task2 under the second await
await task1;
await task2;

because the first await "observes" the result of task1.
Then if the event handler is modified to presenting the actual Task exception that TaskScheduler.UnobservedTaskException provides
    TaskScheduler.UnobservedTaskException += delegate(object o, UnobservedTaskExceptionEventArgs ea)
    {
        Console.WriteLine($"Unobserved task exception! {ea.Exception.ToString()}");
    };

then the failing region of the Task code can be tracked down by observing the exception's stack trace:
Unobserved task exception!
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. (Test exception)
---> System.Exception: Test exception
   at ConsoleApp1.Program.ThrowAsync() in C:\Users\sergepavlov\Desktop\ConsoleApp1\ConsoleApp1\Program.cs:line 42
   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.Exception: Test exception
   at ConsoleApp1.Program.ThrowAsync() in C:\Users\sergepavlov\Desktop\ConsoleApp1\ConsoleApp1\Program.cs:line 42
<---

Hope that makes sense.


text:
Q: Order of initialization for multiple declarators in a single declaration Just looked through C99 and C11 trying to figure out whether they guarantee that multiple declarators in a single declaration are executed in order, from left to right. They do say that each full declarator ends in a sequence point

6.7.5C99 Declarators
6.7.6C11 Declarators
3 A full declarator is a declarator that is not part of another declarator. The end of a full declarator is a sequence point.[...]

but there seems to be nothing that would say that individual initializations are carried out in left-to-right order. Is it really unspecified or am I missing something simple?
int main() {
  int i = 0;
  int a = i++, b = i++;
  // Are values of `a` and `b` specified here?
}

If the order is unspecified, it outlaws the following implementation pattern
int array[N];
for (int *element = array, *element_end = element + N;
     element != element_end;
     ++element)
  *element = 0;

which strikes me as rather surprising. (I do realize that I can initialize element_end with array + N instead.)
P.S. C++ specification is not exactly explicit in that regard either. It has a footnote that says that T d1, d2; is equivalent to T d1; T d2;, but these are non-normative. Hence apparently the DR#1342

A: I don't know how I missed it, considering that I actually searched the entire document for the word "order", but it is really there

6.8C99 Statements and blocks
3 A block allows a set of declarations and statements to be grouped into one syntactic unit.
The initializers of objects that have automatic storage duration, and the variable length
array declarators of ordinary identifiers with block scope, are evaluated and the values are
stored in the objects (including storing an indeterminate value in objects without an
initializer) each time the declaration is reached in the order of execution, as if it were a
statement, and within each declaration in the order that declarators appear.

A:
Is it really unspecified or am I missing something simple?

The order is unspecified. This is because , in
 int a = i++, b = i++;

act as separator, not as an operator. The order of initialization is not guaranteed here.

A: So here it is. if the initial value is supposedly 0, then a will be assigned the value: 1.
B will be also assigned 1 because the value of i hasn't changed. At this stage the values of a and b are assigned.
You may check by printf statement.
the a= i++ means that the value of a is i+1.
Just like that b is also given i+1.


text:
Q: php class pass in undefined variables I am trying to make a class that can process strings with un defined variables. Is this possible? or is there a better way?
For instance, if I have the following and would like this class Looper to take $str_1 and output it with the variables $fname and $lname filled out ... then somewhere else i can reuse Looper class and process $str_2 since they both need $fname and $lname.
class Looper {
    public function processLoop($str){
        $s='';
        $i=0;
        while ($i < 4){
            $fname = 'f' . $i;
            $lname = 'l' . $i;

            $s .= $str . '
';
            $i++;
        }
        return $s;
    }
}

$str_1 = "First Name: $fname, Last Name: $lname";
$rl = new Looper;
print $rl->processLoop($str_1);

$str_2 = "Lorem Ipsum $fname $lname is simply dummy text of the printing and typesetting industry";
print $rl->processLoop($str_2);

A: Why not just use strtr:
$str_1 = "First Name: %fname%, Last Name: %lname%";
echo strtr($str_1, array('%fname%' => $fname, '%lname%' => $lname));

So in the context if your class:
public function processLoop($str){
    $s='';
    $i=0;
    while ($i < 4){
        $tokens = array('%fname%' => 'f' . $i, '%lname%' => 'l' . $i);
        $s .= strtr($str, $tokens) . '
';
        $i++;
    }
    return $s;
}

Likewise if you dont want to be dependent on named placeholders you could use positional placeholders via sprintf:
public function processLoop($str){
    $s='';
    $i=0;
    while ($i < 4){
        $s .= sprintf($str, 'f' . $i, l' . $i) . '
';
        $i++;
    }
    return $s;
}

In that case your $str argument would look like "First Name: %s, Last Name: %s"
So over all usage:
// with strtr

$str_1 = "First Name: %fname%, Last Name: %lname%";
$rl = new Looper;
print $rl->processLoop($str_1);

// with sprintf

$str_1 = "First Name: %s, Last Name: %s";
$rl = new Looper;
print $rl->processLoop($str_1);


text:
Q: Mongoose schema method is "not a function" My model looks like this, but when I try use verifyPassword, it says TypeError: user.verifyPassword is not a function
const User = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: String,
  token: String,
  role: String,
  permissions: Array,
  email: {
    type: String,
    unique: true,
    required: true
  },
  joined: {
    type: Number,
    default: ( new Date() * 1 )
  }
})

User.methods.verifyPassword = function (password) {
  return bcrypt.compare(password, this.password)
}

I use it like this.
yield User.find({
  email: this.request.body.email
}).exec()
.then( user => {
  if ( user.verifyPassword(self.request.body.password) ) {
    self.status = 200
    self.body = {
      token: user.token
    }
  } else {
    self.status = 500
    self.body = "Problem signing in."
  }
}, error => {
  self.status = 500
  self.body = "Problem signing in."
})

A: Mongo's "find" returns an iterable cursor of results (potentially there are none). If you expect to get one result only, try "findOne" instead. This will return one document.


text:
Q: Duplicating in multiple click I have here an add record. I unbind the save button to prevent duplicating record. But the problem is when i try to add new record, the save button still disable. I try to use bind again but it doesn't work.
Help please

$(document).ready(function(){

    $("#save").click(function(){
    $('#save').unbind( "click" );
        ajax("save");
    });
    //$(document).on('click', '#save', function() {
    //ajax("save");
    //});

    $("#add_new").click(function(){
        $(".entry-form").fadeIn("fast");
    });

    $("#close").click(function(){
        $(".entry-form").fadeOut("fast");
    });

    $("#cancel").click(function(){
        $(".entry-form").fadeOut("fast");
    });

    $(".del").live("click",function(){
        if(confirm("Do you really want to delete this record ?")){
            ajax("delete",$(this).attr("id"));
        }
    });

    function ajax(action,id){
        if(action =="save")
            data = $("#userinfo").serialize()+"&action="+action;
        else if(action == "delete"){
            data = "action="+action+"&item_id="+id;
        }
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data : data,
            dataType: "json",
            success: function(response){
            console.log(JSON.stringify(response))
                if(response.success == "1"){
                    if(action == "save"){
                        $(".entry-form").fadeOut("fast",function(){
                            $(".table-list").append("
"+response.cat_name+"	"+response.cat_code+"	"+response.letter+"	Delete
");
                            $(".table-list tr:last").effect("highlight", {
                                color: '#4BADF5'
                            }, 0000);
                        });
                        $(".entry-form input[type='text']").each(function(){
                            $(this).val("");
                        });

                    }else if(action == "delete"){
                        var row_id = response.item_id;
                        $("a[id='"+row_id+"']").closest("tr").effect("highlight", {
                            color: '#4BADF5'
                        }, 0000);
                        $("a[id='"+row_id+"']").closest("tr").fadeOut();
                    }
                }else{
                    alert("unexpected error occured, Please check your database connection");
                }
            },
            error: function(res){
                alert("Unexpected error! Try again.");
            }
        });
    }
});


text:
Q: Unable to instantiate class...because it's looking for the wrong one I'm using IBM RAD with a WAS 7.0 application server. I'm developing a JSF project using RichFaces components and I'm having some trouble with one of the classes. Whenever I start my server, I'm getting this error in the console:
[9/23/10 15:38:13:182 EDT] 00000016 annotation    W com.ibm.ws.webcontainer.annotation.WASAnnotationHelper collectClasses unable to instantiate class
                             java.lang.ClassNotFoundException: org.richfaces.taglib.HtmlToolTipTag

I believe the problem to be that HtmlToolTipTag doesn't actually exist.  In the RichFaces package, it's named HtmlToolTipTagHandler.  I'm new to development, and I'm not sure how to fix this.  Any help would be appreciated.
Thanks!

A: The HtmlToolTipTag was introduced in RichFaces 3.1, but since RichFaces 3.2 it's apparently replaced by HtmlToolTipTagHandler. I am not sure about the reasoning (I don't follow RichFaces that close), but fact is that the HtmlToolTipTag is indeed not available anywhere in RichFaces 3.2 and newer according to the docs.
This exception indicates that you've multiple RichFaces JAR files of different versions in your classpath. I'd scan and cleanup the classpath to get rid of the older ones.

A: Another possibility would be that you have a rich.tld for an older version of richfaces.


text:
Q: How can I get a variable from a method in java without invoking said method? I'm coding a small audio player and need help here; the method fopen() is called by a button press in another class (not the issue here); the problem is that I cannot get the file's path as a string without calling the method.
The playsound() method needs the filepath variable from fopen(), and if I use the String 'path' (initialized after fopen()) it calls the method again.
I ONLY need the 'filepath' variable, but I cannot access it outside of fopen(), or at least not that I know of. Assistance on how I can access filepath without invoking fopen()?
EDIT: Fixed fopen() being set up to return a 'File' instead of a string. Also made some changes to the code; the issue of having fopen() called when it's not supposed to be is fixed, but now it gives me a java.io.FileNotFoundException: when I call playsound() (which, from what I understand, means that the file's path and/or name wasn't even recorded). What else is going on here?
Edit 2: I'm just going to ask another question, seeing as the problem at hand seems to have been answered, and I have an entirely different one on my hands.
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;

public class audio {
private String lastfilepath = "";
public String fopen(){
    JFileChooser fc= new JFileChooser();
    FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
    Audio Layer III", "mp3");
    fc.setFileFilter(filtermp3);
    int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION)
    {
        File file = fc.getSelectedFile();
        String filepath = file.getAbsolutePath();
        this.lastfilepath = filepath;
        return filepath;
    }
else
    return null;
}

String path = fopen();

void playsound(){

    System.out.println("You pressed play.");
    try{
    FileInputStream fis = new FileInputStream(this.lastfilepath);
    Player playMP3 = new Player(fis);
    playMP3.play();
    }
    catch(Exception e){
    System.out.println("Error: '" + e +"'");
    }
}
//  IGNORE WHAT'S BELOW HERE    //
void rewsound(){
    System.out.println("You pressed rewind.");
    }

void pausesound(){
    System.out.println("You pressed pause.");
    }

/*    void forwardsound(){
    System.out.println("You pressed fast forward.");
}
*/
}

A: Create a String instance variable in audio, and then when you call fopen() store the currently selected file's path in that string.
See code below. Untested, but the idea is here. Also, the formatting of this code is pretty bad, it's hard to read. This is what it should look like (ish).
Edit: Added some comments in the code on general improvements/coding style
Edit: For more info on the try I updated in the code, see: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;

public class audio {
    private String filePath = "";

    public File fopen() {
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
            Audio Layer III ", "
            mp3 ");
        fc.setFileFilter(filtermp3); int ret = fc.showOpenDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            this.filePath = file.getAbsolutePath()
            return filepath; // should be file
        } else // give me braces please!
            return null;
    }

    // try to stick to camelCase, it is the 'Java' way
    void playsound() {
        System.out.println("You pressed play.");
        // streams implement AutoCloseable, use it
        // also, you were not closing fis as it was
        try (FileInputStream fis = new FileInputStream(this.filePath)) {
            Player playMP3 = new Player(fis);
            playMP3.play();
        } catch (Exception e) {
            System.out.println("Error: '" + e + "'");
        }
    }
}

A: Your fopen() method is declared to return a File, yet in the method you return a String. If you returned the file that the user selected, and then stored this reference somewhere, you could ask that file for its path any time you wanted.

A: Create another method that returns the last filepath determined in fopen(), eg:
private String lastFilepath;

public String fopen() {
    // logic for determining filepath
    lastFilepath = filepath;
    return filepath;
}

public String getLastFilepath() {
    return lastFilepath;
}

A: First of all you should read about scopes in java programming.
What you currently have is a local scope for your variable "filepath". To make it accessible outside its method block you can either return it as the method result or asign it to a instance variable.
In addition please note that your fopen() method currently won't compile cause it is declared to return a File but inside tries to return a String type.
I would recommend the following:
public class foo {
    private String filePath;

    private void readFile() {
        filePath = doReadingHere();
    }

    private void useFilePath() {
        System.out.println(filePath);
        // do what ever you like to do with the instance variable filePath
    }
}


text:
Q: Unable to import database in Vertica Management Console I have problem with importing database in Vertica Management console 7.2.3.
Whenever I try to connect to database it complains about password:
{"message":"Could not connect to the database. Invalid Password","status":"invalidPwd"}

That is the same password and user dbadmin which I use to connect to the same database via admintools. It works in admintools.
In the agent.log I could only find following:
INFO:wsgi:10.14.44.102 - - [26/Apr/2017:14:04:09 +0000] "POST /databases/dwh_vertica/users/null HTTP/1.1" 401 167 "-" "Apache-HttpClient/4.5 (Java/1.7.0_80)"
INFO:wsgi:10.14.44.102 - - [26/Apr/2017:14:06:16 +0000] "POST /databases/dwh_vertica/users/null HTTP/1.1" 401 167 "-" "Apache-HttpClient/4.5 (Java/1.7.0_80)"

Could you please do let me know why I can't connect?


text:
Q: spring security - remember-me with ajax I'm using spring (security) for a REST webservice and remember-me to keep my users logged in without the need to relogin too often.
The problem is, if the jsession expires, remember-me seems to need a dedicated single synchronous request to get a new jsession-cookie for future requests.
Is there a good alternative or modification to remember-me that handles parallel requests well?
Alternatively, I had the idea to send a custom error code "on cookietheft". Whenever the client receives this code, it could wait some seconds to let the first request finish. Then issue the other requests again with the new cookie. But the problem on this workaround is, that only the first failed request is raising the "cookietheft". All other ajax calls return with 401. Is there a way to detect those calls also in relation to the "cookietheft" so I can return the same special statuscode?


text:
Q: d3 v4 function gives TypeError: d3.timeParse is not a function I loaded d3 v4 but it gives error at line below:
var parseTime = d3.timeParse("%Y");
TypeError: d3.timeParse is not a function
Not sure if this happens because I loaded also v3  which is used for another component. But it shouldn't since the message is about not finding the function.

A: In d3 you can use:
v3:
var timeParse = d3.time.format("%Y-%m-%d").parse;
var date = timeParse(_date);

v4:
var timeParse = d3.timeParse("%Y-%m-%d");
var date = timeParse(_date);


text:
Q: Storing table references in text field (for Agile Toolkit) I have been experimenting with RDB design lately, and I was wondering about storing items in a field that can have more than one value:
    CARS        Color_avail
  1  corvette    1, 2, 3        <<<<<<<
  2  ferrari      2
  3  civic        1

    COLORS
  1  red
  2  White
  3  black

so  on CRUD I would like to add more than one item via a drop down / checkboxes or something that would hold multiple values.

A: Storing relations in the coma-separated list makes sense in some senses. You don't need commas though. There are 2 existing controls which can help you with that.
Displaying list of values with checkboxes in a form:
$form->addField('CheckboxList','corvette')->setValueList($array);

(you can populate array through $model->getRows() although I think it needs to be associative. You can probably join them with var_dump and foreach).
Your other options is to use a hidden field with selectable grid.
$field = $form->addField('line','selection');
$grid = $form->add('MVCGrid');
$grid->setModel('Colors',array('name'));
$grid->addSelectable($field);

$form->addSubmit();

To hide the actual field, you can either use "hidden" instead of "line" or use JavaScript to hide it:
$field->js(true)->hide();

or
$field->js(true)->closest('dl')->hide();

if you need to hide markup around the field too.

A: I can see the benefit of displaying the output like this in a form, but do you really want to store it like this in the database ?
For example with a datamodel that holds a comma separated list as in your example, what SQL would you use to identify all the cars available in white ?
The traditional way to hold a many to many relationship like this is to use an additional table e.g. you have a separate table that holds CAR_COLOUR with the following contents
 CAR      COLOUR
 1        1
 1        2
 1        3
 2        2
 3        1

So now you can easily query things like, get a list of all cars and colours
SELECT CAR, COLOUR
  FROM CARS CA,
       COLOUR COL,
       CAR_COLOUR CACOL
 WHERE CA.CAR=CACOL.CAR
   AND CACOL.COL=COL.COLOUR

OR if you just want the white cars, add the following to the WHERE clause
   AND COL.COLOUR='White'

an index on the id fields and on both fields in CAR_COLOUR will mean you get great performance even if you have thousands of rows whereas putting them all in a comma separated list in a single field will mean you have to use substr or like which would prevent the use of indexes and mean as the amount of data grows, the performance will degrade rapidly.


text:
Q: Determine hbm2ddl value programmatically without triggering schema update I would like to know the value of the hbm2ddl feature during the runtime of my application. I succeeded to determine that value with the following code:
@Autowired
private ApplicationContext applicationContext;

private getHbm2DdlValue() {
    LocalSessionFactoryBean sessionFactoryBean = (LocalSessionFactoryBean)
            applicationContext.getBean("&sessionFactory");
    Configuration conf = sessionFactoryBean.getConfiguration();
    String hbm2ddlValue = conf.getProperty("hibernate.hbm2ddl.auto");
    return hbm2ddlValue;
}

Now, I want to know that value before the automatic update is triggered. The problem with the solution above is, that retrieving the LocalSessionFactoryBean immediately triggers the automatic update.
I could read the configuration file from disk and interpret it - but I would rather like to let the configuration build by hibernate and then read the property from there.
Is there any other way to create or access the hibernate configuration without triggering the automatic schema update?

A: As far as I know, it is not possible to disable factory-initialization during ApplicationContext loading. The LocalSessionFactoryBean is a FactoryBean. Spring will call that object's getObject() method during initialization of the context and that will force the schema to be updated.
Note that the Configuration instance of the LocalSessionFactoryBean is configured and used directly in the afterPropertiesSet() method. You won't be able to intercept it either.
You'll need to create your own Configuration instance (or parse the file yourself) before the ApplicationContext is created. You can look at the source code of LocalSessionFactoryBean to see how that is done.


text:
Q: Why i get <__main__.Node object at 0x000001EF886AB2E0> when i output Node's name? class Node():
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def search1(root, value):
    if root is None or root.val == value:
        return root

    if root.val > value:
        return search1(root.left, value)

    if root.val < value:
        return search1(root.right, value)

def search2(root, value):
    while root != None and root.val != value:
        if root.val > value:
            root = root.left
        elif root.val < value:
            root = root.right
            return root

if __name__ == '__main__':
    a = Node(15)
    b = Node(6)
    c = Node(18)
    d = Node(4)
    e = Node(8)
    f = Node(17)
    g = Node(20)
    h = Node(13)
    i = Node(9)
    a.left = b
    a.right = c
    b.left = d
    b.right = e
    c.left = f
    c.right = g
    e.right = h
    h.left = i

    print(search1(a, 13))
    print(search2(a, 13))

output: <__main__.Node object at 0x000001EF886AB2E0>
How can I convert the address of this Node() to the name of Node()?

A: Either simply by
a) Accessing the attribute on print
print(search1(a, 13).val)
print(search2(a, 13).val)

or b) by overwriting the __str__ or __repr__ method within your Node class. The former is used for more human readable output  (e.g., in a GUI) while the latter is more for a technical/development related output.
class Node():
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
    def __str__(self):
        return str(self.val)
    def __repr__(self):
        return 'Node: ' + str(self.val)

__str__ is used by the builtin print function or str function. If it is not defined, they fall back to __repr__. __repr__ is also used by the python command line and used by the builtin repr function.
Output of print:
15

Output in Python CLI:
$ python3
from <your-module-name-here> import Node
a = Node(15)
>>> print(a)
15
>>> a
Node: 15


text:
Q: Limit Selectable DOM Checkboxes I am trying to limit the number of checkboxes a user can select.  These checkboxes are DOM input objects generated for each item in an array.  I'm having no luck with this currently, so any help is much appreciated.  Thanks!
Fiddle Here: http://jsfiddle.net/vVxM2/222/
names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
var numberOf = names.length;
var text = "
";
for (i = 0; i < numberOf; i++) {
    text += "
<input type='checkbox' class='playerCheckbox'>" + names[i] + "
";
    }
text += "
";
document.getElementById("recentPlayersContainer").innerHTML = text;

var limit = 3;
$('input.playerCheckbox').on('change', function(event) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});

A: Your problem is in the change event.
Instead of doing:
if($(this).siblings(':checked').length >= limit)

You should do this:
if($('.playerCheckbox:checked').length >= limit)

Also, if your limit is maximum 3 checked, then you should do:
$('.playerCheckbox:checked').length > limit

Because when the event change is raised, the current checkbox is already checked.

A: Your problem was found here: if($(this).parent().siblings().children(":checkbox:checked").length >= limit).  You actually have two parents, so you should have added another parent() and children() function.  It should look like if($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit)

names = ["Donny", "Danny", "Ricky", "Eric", "Jamie", "Bobby", "Booby"];
var numberOf = names.length;
var text = "
";
for (i = 0; i < numberOf; i++) {
  text += "
<input type='checkbox' class='playerCheckbox'>" + names[i] + "
";
}
text += "
";
document.getElementById("recentPlayersContainer").innerHTML = text;

var limit = 3;
$('input.playerCheckbox').on('change', function() {
  if ($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit) {
    $(this).attr('checked', false);
    alert('You can only select 3 checkboxes.');
  }
});

A: DEMO
 names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
        var numberOf = names.length;
        var text = "
";
        for (i = 0; i < numberOf; i++) {
            text += "
<input type='checkbox' class='playerCheckbox'>" + names[i] + "
";
            }
        text += "
";
        document.getElementById("recentPlayersContainer").innerHTML = text;

    var limit = 3;
    $('input.playerCheckbox').on('change', function(event) {
            if($('input.playerCheckbox:checked').length >= limit + 1) {
              alert('enough');
            }
    });


text:
Q: Why is power specified in watts rather than amperes? This probably has an obvious answer I'm missing, but searching the web only gave me information on how watts are defined, not why we use them.
Many electric appliances (from things used to build circuits to appliances we use every day) give their power draw in watts. Many other appliances, however, give their draw in amps.
From what I've seen online, watts is calculated by multiplying voltage by current. However, Ohm's law states that \$I = \frac{V}{R}\$, which implies that current already varies linearly with voltage (given constant resistance.) Isn't multiplying current by voltage again redundant?
Similarly to electrical appliances, I've also seen battery capacities defined in both watt-hours and amp-hours, even with batteries that have variable voltages (depending on the charge.)
This doesn't seem to really make sense: if the battery has varying voltages and if amperes don't truly represent power (as I've seen several sources online state as a reason for the usage of watts), why are they used to measure the capacity of batteries that have varying voltages?

A: Power is specified in watts because a watt is a unit of power. Current is specified in amperes because an ampere is a unit of current. Appliances made for use in homes are designed to run on the AC mains supplied by utilities. In general mains power is generated at a fixed voltage (120 volts in the United States, 240 volts in some other countries). Therefore you can specify the power used by such appliances either directly in watts or in amperes since it is assumed that the latter is for the fixed utility supplied voltage (thus the power can be calculated by multiplying the current by the AC mains voltage). Also most appliances do not appear to the AC mains as fixed resistances so your use of Ohm's law is not relevant.

A: Because 1-amp looks the same whether it is...
A) pushed through a 1000-ohm resistor by a 1000V potential, or,
B) pushed through a 1-ohm resistor by a 1V potential.
Option A requires 1000 watts and will soon vaporize the resistor.
Option B will still get warm but only requires 1 watt.

A: Because amps are a unit of current, and watts are a unit of power. They're not the same thing.

A: An outlet is often just called a power outlet. But if nothing is plugged in, it's not delivering any power. And some I've spoken with were confused by that because they wanted to know what happens to the power if nothing is plugged in. "Does it get recovered or captured and 'put back somehow' if nothing is plugged in?" they asked. "Or does it just spill out and get wasted?"
However, these power outlets do deliver a voltage to each and every outlet. So, to be technical, perhaps the outlet should be called a voltage outlet and not a power outlet, as it always provides a consistent voltage even if there's no power involved as there is no device connected up.
But you have to pick a word and go with it. And in any case, that's what people require (power) when they do plug in a device for use. So "power" it is.
Besides, voltages tend to come in standard lengths. So they don't need to be stated, much of the time. It's either there or it isn't. The value when it is there is just assumed to be known.
I'll switch over to an analogy of sorts.
Voltage is like the distance from a floor to a ceiling in a home. There is a standard height that most folks can just assume. So you don't need to mention a quantity, at all. It's "enough" and that's all you need to know. If you need to look up a specific value, that is easily had.
Current tends to be more like "floor space." It can be anything at all that is appropriate for a use.
You don't need to talk about the height of a room. But people are interested in the area, if you want to tell them. So it would seem odd to hear someone ask, "Could you also tell me how high your ceiling is?" just after having being told that the house is 1300 sq. ft. (or 120 sq. m.).
Sure, the actual living space really is a volume and without the ceiling height you don't know the volume. But you don't care, either. The floor space tells you what you need to know for most uses.
So it may be easier to see why voltage may not be mentioned, at all. (It's assumed to be some standard value.) And why it's enough to mention the current (analogous to floor area.)
In this analogy, power is like the home's volume. That's the actual 3D space required for a decent life, as you can't live glued down flat to a floor (we aren't flounders.) But just saying the area gets across all that's needed for most non-technical discussions.
Floor-space is what you think in, when you are considering some function: kitchen, pantry, bedroom, etc. Yet you really mean volume when thinking that way, because there is an implied working height that you also expect. And there are standards for that. Separately, the functions might be: door and cabinet carpentry, auto repair shop, and so on. And each of these would likely imply a different standard height needed. You need and will pay for the required working volume and the required time it is needed, but you think in terms of the working area and just assume the standards for the height that everyone shares as an assumption for the function. (And you pay for the time you use it.)
Likewise, the voltage for a home is standardized. So there's no need to refer to it. It's a given. The current matters because of the safety breakers and the power matters because of the cost (when considered with time) to operate the device. So while current is a concern ("Will my circuit breaker support this?") and while power is a concern ("Is this freezer more expensive to operate than another freezer?"), the voltage is not a concern. It just exists in the background, so to speak.
That said, like renting space for some function, you will pay for the floor space and the ceiling heights needed (the total volume -- similar to power, here) and also the rental period (time.) In total, the voltage times the current times the time is the energy consumed. And that is what you pay for. So voltage matters in that computation. (If you need 240 VAC instead of 120 VAC and use the same current for the same time, you will pay twice as much for the 240 VAC power usage.) But voltage is just a matter of determining compatibility ("Will this device function properly with this voltage?") What you mostly care about is the current (circuit handling) and the power (cost to operate per unit time of use.)
So it's reasonable for some devices to talk about current. In this way, you can make sure that your circuit, together with other devices that may share the same circuit, will function properly with your breaker. It's also reasonable to talk about power. In this way, you can think about functional efficiency or cost-to-operate. The only use of voltage is for compatibility (a yes-no question of whether or not you can plug device X into socket A.)
But everything, voltage, current, and time goes into computing the dollars spent for some job or task performed.

A: Power is formally defined as the amount of work done over a period of time. Work is a fundamental concept in physics,  and is quantified in units of joules. And the derived quantity of power is canonically expressed in units of joules per second; a watt is by definition 1 joules per second (it is simply defined as such by humans).
Electrical current describes the rate of change of charge over a period of time. Charge is a fundamental quantity in physics and is expressed in coulombs. And the derived quantity of electrical current is expressed in coulombs per second; an amp is by definition 1 coulomb per second (it is simply defined as such by humans).
If you understand and/or accept the fundamental nature of what a joule represents and what a coulomb represents, it is self evident that the derived quantities of power and electrical current are fundamentally different. They are relatable things, but a third concept links them.
That concept is voltage (electromotive force), which is another derived quantity, and which is expressed in terms of joules per coulomb; and again by human definition 1 joule per coulomb is called a volt.

A: Watts are a unit of power, they should be preferably be used. However, for certain appliances such as batteries, amps can make more sense because of the loses inside the battery.
The difference between power, current, voltage has been explained in other aswers, I will only focus on why amp-hours can make sense even if it's not properly a unit of energy.
Let's take an example with a battery that is 12V, 12Wh (1Ah), with an internal resistance of 1Ω
here is a simplified diagram: a perfect source (always 12V) in series with a 1Ω resistor

Let's assume Rload is 11Ω. The output current is
$$I = U/(Rg+Rload) = 12V / (1+11)\Omega = 1A$$
the internal perfect source delivers
$$ P = U*I = 12V * 1A = 12W $$
the battery will be empty after 1h (12Wh delivered) but the load only received
$$ P = Rload*I^2 =  11\Omega * (1A)^2 = 11W $$
$$ E = P*dt = 11W*1h = 11Wh $$
In Ah, the load "received"
$$ 1A * 1h = 1Ah $$
So, should the battery be branded as 11Wh ? Not so fast, it depends of the load, let's see with a 1Ω load. This is the maximum power output and can happen when a car starts for example, where a huge amount of power is needed.
now, the current is
$$ I = U/(Rg+Rload) = 12V/(1+1)Ω = 6A $$
so the internal source delivers
$$ P = I*U = 6A*12V = 72W$$
so it will last 1/6 h or 10 minutes
during these 10 minutes, the internal source delivered 12Wh, but the load only received
$$ P = Rload*I^2 = 1\Omega * (6A)^2 = 36W $$
$$ E = P*dt = 36W * (1/6)h = 6Wh $$
Only half! If counting in Ah however, it is still
$$ 6A * (1/6)h = 1Ah $$
Now, the battery delivered only 6Wh, but the 1Ah is still "correct"
In practice, it's even worse than that because the internal resistance isn't constant or even linear, it can vary depending on many factors (current, state of charge, temperature, aging, etc)
TLDR: for a battery, measuring the current output is more accurate than the power because it is depends less of what happens inside the battery, even if it's not a true measure of the available power

A: it generally changes to what you model the load as, each unit has sort of an implied meaning to it, with a model I mean that you assume something about the load to simplify. Remember that  V= I/R is not always true there a lot of conditions that need to be met so you can do that.
I will give you some examples:
Constant impedance :  you can think of it as resistance to simplify but it is not exactly the same, the square root of the voltage magnitude controls the power mainly.  example Headphones and audio equipment usually mention ohms
Constant current : the voltage will control the power, but we assume the load draws a constant current so from there we can know the power. Transducers and arc lamps behave like this.
Constant power : here you assume the load only has constant power. Some electronic devices behave like this but I got no examples from the top of my head
so each definition implies how it should be modelled as when you work with it, or what conditions are considered constant.
there is nothing wrong with using ohm's law but don't forget the formal definition of electric power

A: Imagine two rubber balloons, A and B, where B's rubber wall is twice as thick as balloon A.
They are both inflated by injecting air into them, but balloon B's thicker wall will resist inflation more. To inflate them both with 1 litre of air would take much more physical effort for B than A would require, and yet it's the same amount of air in both cases.
In other words, you expend more Joules of energy inflating balloon B than for A, to the same volume, to move the same amount of air from outside the balloons to inside.
To extend this analogy to power, remember that power is the rate of doing work, the number of Joules of "exertion" made each second. The unit is Watts, which means Joules per second. If you intend to inflate both balloons to the same volume of 1L in the same amount of time, obviously you will have to work harder blowing into balloon B than A. In this scenario you are doing more Joules of work per second (power, in Watts) for ballon B than for A.
Conversely, if you don't care how long it takes, then you can make the same effort to inflate both balloons, but for balloon B you will have to make that effort for longer. In this scenario you are delivering the same power to both balloons, but for far longer in the case of balloon B.
The rate of air flow here is analagous to electric current, which is charge flow. Balloon volume would be analogous to total electric charge moved. I hope it's clear by this point that you can't measure power, or work done by knowing only how much air/charge moved, since in all cases it has been 1 litre.
Current tells you how much charged moved, in the same way volume tells you how much air you moved, but it doesn't tell you anything about how much effort the battery or lungs made in order to do the moving. To know that, you also need to know how hard you blew into the balloon, or how hard the battery/mains pushed charge through some device.
For the air analogy, clearly the measure of "how hard" is pressure, and for electricity, that measure is voltage.
If you have to blow twice as hard (twice the pressure) to inflate ballon B to 1L in 10s, as you do to inflate balloon A to 1L in the same time, then you've done twice the amount of work over the same duration, and therefore delivered twice the power. That's why fluid power is proportional to pressure, and electrical power is proportional to voltage.
Now understand that to inflate any balloon to 1L, you can control the flow of air into it, and that rate of flow will determine how long it takes to deliver each Joule of energy. In other words, doubling the air-flow/current will also double the the number of Joule's of work done each second. That's why electrical power is also a function of electric current.
If you double electric current, you double the power, the number of Joules of energy delivered each second to whatever that current is flowing through. If you double the voltage across something, then you also double the power delivered to that thing.
Crucially, what happens if you double both? You quadruple the power. For a fixed electrical resistance, something interesting happens. Let's say you double the voltage across a resistor. Ohm's law tells us what happens to the current:
$$
\begin{aligned}
\frac{V}{R} &= I \\ \\
\frac{2V}{R} &= 2I
\end{aligned}
$$
Doubling the voltage across the resistor will also double the current through it, and the combined effect on power is a quadrupling. Similarly, if you double the current through a resistor, you also consequently double the voltage across it. Either case therefore results in a quadrupling of power, a relationship which can be clearly seen in the "square" terms of the two other famous power equations:
$$
\begin{aligned}
P = \frac{V^2}{R} \\ \\
P = I^2 \times R
\end{aligned}
$$
TLDR; To get to your question, current on its own cannot tell you about energy delivered per second. Voltage alone cannot tell you this either. Only together can you know the power:
$$ P = I \times V $$
Few household appliances have constant electrcal resistance, though an electric kettle comes close. For a kettle, doubling the voltage supply from its usual 110V to 220V would (if the kettle survived) cause the kettle to boil the same amount of water in a quarter of the time, because four times as many Joules of heat energy are delivered to the water each second.
Most electrical appliances are not so simple, and may not be treated as constant resistances. As an example, if you had a multi-voltage TV, rated at 100W, doubling the supply voltage would halve the current, to maintain 100W. That requires some complex switch-mode power supply magic, but it is possible.
Most appliances would just die if you doubled the voltage. Unless they are designed to cope with the sudden doubling or quadrupling of power delivery (which entails some kind of dynamic control of their "apparent resistance"), they usually deal with it by not doing anything any more. Like when you put your back out trying to deliver too many Joules of gravitational potential energy to something in too short a time.

A: Assuming you know the difference between current and power...

why are they used to measure the capacity of batteries that have varying voltages?

Simple: if the stuff you want to power from the battery draws current that doesn't depend on battery voltage, you'll be interested in battery capacity expressed in Amphours. However if your load uses constant power, then its current will depend on battery voltage, and then battery capacity expressed in Watthours will be more useful. It's not obvious how to convert between the two because battery voltage isn't constant.
An example of a load that current independent of battery voltage would be anything powered by a linear regulator.
An example of a load that draws constant power would be a LED flashlight driven by a switching DC-DC converter. This will regulate a constant output current into the LED, so it has constant output power, and it will draw constant power from the battery (equal to output power + losses) so input current is in inverse proportion to battery voltage.

Many electric appliances (from things used to build circuits to appliances we use every day) give their power draw in watts. Many other appliances, however, give their draw in amps.

If your appliance is a resistor, or if it behaves as a resistor, it makes no difference.
If it doesn't behave as a resistor, for example a switching power supply without power factor correction, then its power factor will be far from 1, and it will draw current in pulses or other weird shapes.
So if you want to use a switch on your wall to control a bunch of LED "transformers" (which are really switching power supplies) you'll be interested in the maximum peak input current of these, so that it doesn't exceed the rating of the switch. In this case, power will be very low, so the switch won't care, but peak current could be a problem.


text:
Q: Export Makefile parameter How can I change exported value to one passed by parameter?
Makefile:
default_value=Default-Value
export ENV_VALUE=default_value

build:
      python3 script.py

execution:
$ make build
python3 script.py
ENV_VALUE: default_value
script executed.!
$ make build default_value=modified_value
python3 script.py
ENV_VALUE: default_value
script executed.!

A: export ENV_VALUE="$(default_value)"


text:
Q: How authorize in Spring OAuth2 by client_id and secret only? Now I am using the next configuration:
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(mAppConfig.dataSource())
                .withClient("virto")
                .secret("secret")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token");
    }
}

It requires to send client_id, client_secret, username, password... But I need to provide access_token for my trusted servers that has client_id and client_secret only... How can I make it? Is it possible?

A: What you need is to configure a client with client_credentials grant
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(mAppConfig.dataSource())
                .withClient("virto")
                .secret("secret")
                .authorizedGrantTypes("client_credentials");
    }
}

To get a token you send a post request, with credentials as base 64 encoded.
POST http://localhost:8080/paymentiq/oauth/token?grant_type=client_credentials -h 'Authorization: [clientId:secret]'


text:
Q: The word underlying What meaning does the word "underlying" add in this sentence?

Behaviorism is based on a number
  of underlying assumptions regarding methodology and behavioral
  analysis: Psychology should be seen as a science.

"Underlying" means "true causes" but assumptions are the things which are not proved.
So it doesn't make a sense for me. Is it like true lies?
Thank you

A: Underlying may mean 'true cause', but it does not have to mean that. What it means here is simply that the assumptions in some sense 'lie under' the discourse of behaviorists: probably that the assumptions are not made explicit but lie deep 'beneath' the surface discourse, perhaps so deep that they are not even recognized as assumptions by the behaviorists themselves.


text:
Q: Getting value from an array I have an array I call with an api connection.
["data"]=>
  object(stdClass)#212 (3) {
    ["status_code"]=>
    int(200)
    ["data"]=>
    object(stdClass)#211 (3) {
      ["days"]=>
      int(30)
      ["total_clicks"]=>
      int(6)
      ["clicks"]=>
      array(30) {
        [0]=>
        object(stdClass)#215 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466395200)
        }
        [1]=>
        object(stdClass)#216 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466308800)
        }

I try to get the first
["data"]=>
  object(stdClass)#212 (3) {
    ["status_code"]=>
    int(200)
    ["data"]=>
    object(stdClass)#211 (3) {
      ["days"]=>
      int(30)
      ["total_clicks"]=>
      int(6)
      ["clicks"]=>
      array(30) {
        [0]=>
        object(stdClass)#215 (2) {
          ["clicks"]=>
          int(0)

I try to do so with the following function (the array itself is stored in the "$data" variable):
function currentClicks($data)
        {
            $path = $data->data->data->clicks;
            foreach ($path as $key => $item) {
                $array[] = [$item->clicks[0]];
            }
            return json_encode($array);
        }

And I echo it in a
 tag:
<?php echo currentClicks($data); ?>

The problem is that instead of displaying the value (which is the number 0) I get an error in console displaying
[[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null],[null]]

A: Clicks is still an object, you still haven't reached the "bottom" of the object to display a primitive.
So for example it should be:
 $array[] = [$item->clicks[0]['clicks']];


text:
Q: jsp:setproperty what does property="*" mean? <jsp:setproperty name="Test" property="*">

What does this mean?
I know the definition is, "Sets a property in the specified JavaBean instance". So what is it setting a property in the javaBean test too ?

A: an asterisk (*) is used as the property attribute value of the  action. This means that all bean properties with names that match request parameters sent to the page are set automatically

A: Here is a complete example:
Form.html
<form method="POST" action="processForm.jsp">
    <input name="name"/>
    <input name="username"/>
    <input name="jobTitle"/>
    <input name="city"/>
<input type="submit">

The form collects input from the user and posts it to the processForm.jsp page.
processForm.jsp
<%@ page import = "com.Employee"%>

...

<jsp:useBean id="employee" type="com.Person" class="com.Employee">
    <jsp:setProperty name="employee" property="*"/>
</jsp:useBean>

The <jsp:useBean> action creates an object of type com.Person referred to by a com.Employee reference.
The <jsp:setProperty> action matches the name of each of the input elements with the name of the getter method in the Employee object.
For example: name matches with getName and jobTitle matches to getJobTitle. Below is the Employee class. I have not included the Person interface.
Employee.java
public class Employee implements Person{

    private String name;
    private String username;
    private String jobTitle;
    private String city;

    public String getJobTitle() {
           return jobTitle;
   }
    public void setJobTitle(String jobTitle) {
           this.jobTitle = jobTitle;
   }
    public String getName() {
           return name;
   }
    public void setName(String name) {
           this.name = name;
   }
    public String getCity() {
           return city;
   }
    public void setCity(String city) {
           this.city = city;
   }
    public String getUsername() {
           return username ;
   }
    public void setUsername(String username) {
           this.username = username;
   }
}

Things to note about this standard action.

*

*the name of the input element MUST be matchable with a getter method of the target object. name --> getName etc.

*Becareful with types. You cannot match to a Map or an Array

*The same is true if the property is an object. It will need to be treated separately.

*If the type of the property in Employee is int and the value entered in the form is not convertable to an int then a java.lang.NumberFormatException will be thrown.


text:
Q: Right Hand Rule on the magnetic field not working?

*

*Background: The magnetic field is going into the page and the velocity of the particle is going towards the right.

What is the sign of the particle?
I keep getting this wrong. The magnetic field is going inwards so my middle finger is pointed inwards. Then the velocity is towards the right so my index finger is pointed to the right. This makes my thumb go downwards [which is the magnetic force].
But the book says the magnetic force is upwards and not downwards?

A:
You are probably not using the hand rule correctly i've posted a picture.

A:
Then the velocity is towards the right so my index finger is pointed to the right.

To apply the right-hand rule, you need to know the charge of the particle.  If the charge is -1, like an electron, then the current, $qV$, is in the opposite direction as the velocity and that changes the force from up to down.

A: You use Flemings Left Hand rule to calculate the direction of a force on a charge moving in a magnetic field (see https://en.wikipedia.org/wiki/Fleming%27s_left-hand_rule_for_motors
and Motion of an electron in a magnetic and electric field)


text:
Q: Handling desktop position, font and other win32 console parameters Is it possible to programmatically set such windows console parameters as its left-top desktop position, console font, fast insert and selection by mouse options, etc.?
Unfortunately we can set some console parameters by invoking undocumented Windows API. For example: SetConsoleFont, GetConsoleFontInfo, GetNumberOfConsoleFonts from KERNEL32.DLL.

A: In order to reposition the console you need to update the underlying HWND.  You can use the GetConsoleWindow() function to get a handle to the HWND.  From there you can call GetWindowInfo, SetWindowINfo and the like to update it's postition and size
http://msdn.microsoft.com/en-us/library/ms683175(VS.85).aspx
EDIT The below is actually for updating the buffer.
I believe you are looking for the SetConsoleWindowInfo function.  This will allow you to control positioning of the Console Window.
http://msdn.microsoft.com/en-us/library/ms686125(VS.85).aspx


text:
Q: How to use Elastic Search to get alerts when document's datetime field value is 2 days percolate can be run when there is any updates on the document and we can identify any rules matching the document.
But how can we use this to find documents where a datetime field value is 2 days away,
like, find open tickets and 2 days before their expected closed date.

A: you can do this with Alerting, which is probably better suited
without knowing your mappings, https://github.com/elastic/examples/tree/master/Alerting/Sample%20Watches/lateral_movement_in_user_comm has an example of a Watch that compares two different timestamps that you should be able to adopt


text:
Q: lighttpd, php, fastcgi - individual virtual host settings for notices warnings and error showing I am looking for a way to configure the virtual hosts on a lighttpd individually to show or not Errors and Warnings.
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

I like to make it from the virtual hots configuration. Not from the php.ini.
$HTTP["host"] =~ "domain1\.com" {
            server.document-root = "/home/lighttpd/domain1.com/http"
            accesslog.filename   = "/home/lighttpd/domain1.com/logs/access.log"

            php_flag display_errors On ....???

}

If you try the Code above you get the following Errors
root@web:~/lighttpd# /etc/init.d/lighttpd restart
2014-02-05 11:23:54: (configfile.c.932) source: /usr/share/lighttpd/mysql_vhost.py line: 8 pos: 24 parser failed somehow near here: display_errors
2014-02-05 11:23:54: (configfile.c.932) source: /etc/lighttpd/lighttpd.conf line: 32 pos: 1 parser failed somehow near here: (EOL)

is there any other way to talk to PHP from inside lighttpd ?
PHP is loaded as a module.
It should be one.

A: Not sure, are looking for something like this
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/domains/example.com/html
    ErrorLog /var/www/domains/example.com/apache.error.log
    CustomLog /var/www/domains/example.com/apache.access.log common
    php_flag log_errors on
    php_flag display_errors on
    php_value error_reporting 30719
    php_value error_log /var/www/domains/example.com/php.error.log
</VirtualHost>

The reason 30719 is used is below
All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.   32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously .
Read here for this.
You can use
php_value error_reporting 2147483647

The above number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run
Or see below
php_value error_reporting 6143 # for all errors notice, warnings, etc
php_value error_reporting 6135 #show warnings less strict

A: If PHP is running as module under lighttpd than you can put below code inside virtualhost configuration :-
  php_flag display_errors off