Q:

How to iterate through JSON array from n1ql query?

so I'm using couchbase queue to Enqueue my beacon information. I'm trying to use n1ql query for my get method and I'm having trouble getting all the information. I realized I'm only getting the first beacon entry because result.Rows returns one element, an array of BeaconInfoN1ql. I wanted to iterate through that array and add each to a list.
try {
     var cluster = new Cluster(new ClientConfiguration());
     using (var bucket = cluster.OpenBucket("BeaconInfoN1ql"))
     {
         string query = "SELECT * FROM `BeaconInfoN1ql`";
         var queryRequest = new QueryRequest(query);
         var result = bucket.Query<dynamic>(queryRequest);
     foreach (var row in result.Rows)
      {

          int i = 0;
          var beacon = new Beacon()
          {
              SerialNumber = row.BeaconInfoN1ql[i].serialNumber,
              ReceivedDate = Convert.ToDateTime(row.BeaconInfoN1ql[i].receivedDate),
              ReceiverId = row.BeaconInfoN1ql[i].receiverId,
              Distance = Convert.ToDouble(row.BeaconInfoN1ql[i].distance),
              Rssi = Convert.ToInt32(row.BeaconInfoN1ql[i].rssi),
              NewDistance = Convert.ToDouble(row.BeaconInfoN1ql[i].newDistance),
              DistanceTesting = Convert.ToDouble(row.BeaconInfoN1ql[i].distanceTesting),
          };
          i++;
          _beaconsList.Add(beacon);
      }
 }
 return _beaconsList;

my result.Rows looks like this
result.Rows=
{{
"BeaconInfoN1ql": [
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
{
"distance": 2.2705747109792007,
"distanceTesting": 22,
"newDistance": 22,
"receivedDate": "0001-01-01T00:00:00",
"receiverId": "42008780c4b9b329",
"rssi": -73,
"serialNumber": "888"
},
]
}}

I'm not sure about how to make the second foreach/for loop to iterate through all the keys.

A:

For iterating JSON, I like to use dynamics. Here's an example:
var result = new Result()
{
    Rows = @"{
        'BeaconInfoN1ql': [
            {
                 'distance': 2.2705747109792007,
                 'distanceTesting': 22,
                 'newDistance': 22,
                 'receivedDate': '0001-01-01T00:00:00',
                 'receiverId': '42008780c4b9b329',
                 'rssi': -73,
                 'serialNumber': '888'
            }
        ]
    }" //other entries omitted for brevity
};

dynamic parsedRows = JsonConvert.DeserializeObject(result.Rows);
foreach (var entry in parsedRows.BeaconInfoN1ql)
    Debug.Write(entry.distance);

NOTE: I got rid of the double curly braces from your output in my example.


Q:

Click Event Not Working After Class Change

I have the following script:
// dashboard maximize
$('#dashboard-actions .btn-maximize').click(function() {

    // max / restore buttons
    $(this).removeClass('btn-maximize').addClass('btn-restore');
    $(this).find('span').removeClass('icon-maximize').addClass('icon-restore');

    // swap tables
    $('#table-dashboard-actions-mini').hide();
    $('#table-dashboard-actions').show();

    // show form
    $('#form-dashboard-actions-btm').show();

    // restyle panel
    $(this).parents('.panel-dashboard').addClass('panel-dashboard-max');

    // animate panel
    $(this).parents('.panel-dashboard').animate({
            width: "100%",
        }, 250, function() {
        // Animation complete.
    });
    $(this).parents('.panel-primary').animate({
            height: "725px"
        }, 250, function() {
        // Animation complete.
    });

});

As you can see, at one point the script changes the class of the clicked button to .btn-restore
However this means that I cannot seem to bind an event to .btn-restore
I originally had this:
// dashboard restore
$('#dashboard-actions .btn-restore').click(function() {

    alert('asdf');
});

And the alert statement didn't work, so I changed it to this:
$('#dashboard-actions .btn-restore').on('click', function() {

But still no joy. Can anyone see what I'm doing wrong?

A:

Try this:
$(document).on('click','#dashboard-actions .btn-restore', function() {

instead of:
$('#dashboard-actions .btn-restore').on('click', function() {

Delegated events must be bind to something that exist in the dom and in the second part will define the element ('#dashboard-actions .btn-restore') you want to trigger click on.

A:

You need to use event delegation as the class changes dynamically.
$('#dashboard-actions').on('click','.btn-restore', function() {

When you bind the event handler initially, there exists no element with class btn-restore, so the click event after class change does not fire.
Also, I see btn-maximize being altered, of this is later added/toggled I woould suggest using a single common class like 'btn-toggle' and then add/remove  btn-maximize/btn-restore. This would prevent adding two separate event handlers.

A:

As a couple of people have mentioned, event delegation is the key to binding to selectors that don't match yet. The alternative suggestion of binding to the generic selector .button that will always exist and then maintaining the state (maximised or restored) in a variable is also valid.
Your issue  with the panel opening and then immediately closing seems to be that you add the .btn-restore class inside the event handler immediately. It shouldn't happen, but it seems like the click event is firing again on the new selector (perhaps something to do with mouseup and mousedown components of the click event?). I'd suggest wrapping your addClass calls within a setTimeout() like so to ensure the classes are changed after any events fire, essentially "pushing" the change to the end of the current execution:
var $btn = $(this);
setTimeout(function () {
    $btn.removeClass('btn-maximize').addClass('btn-restore');
    $btn.find('span').removeClass('icon-maximize').addClass('icon-restore');
});

You'll notice the new variable $btn. This is required because this inside your setTimeout function will no longer refer to the clicked element (a quick search for "javascript scope and this" or similar will explain this further if required). It also doesn't hurt to cache the $(this) result in any case.
Hope that works for you - let me know if I can be of further help.


Q:

Starting Asp.Net Website Automatically on windows startup

I want to start my asp.net application when my windows 7 x64 starts.
I have manually start IIS to start my asp.net website.
Please suggest me to way to do this task.

A:

Follow the path..

Start>Control Panel>Administrative Tools>Services>World Wide Web Publishing Service>Right click on that service>Properties> Set startup type =Automatic >OK

Done!! you will get your localhost site in start up!!


Q:

@font-face not work in Firefox

Have a some trouble whit @font-face in Firefox.
@font-face{
font-family:'PopularScript';
src:url('http://static.dubrovka.dn.ua/eot/PopularScript.eot');
src:url('http://static.dubrovka.dn.ua/eot/PopularScript.eot?#iefix') format('embedded-opentype'),
    url('http://static.dubrovka.dn.ua/wof/PopularScript.woff') format('woff'),
    url('http://static.dubrovka.dn.ua/ttf/PopularScript.ttf') format('truetype'),
    url('http://static.dubrovka.dn.ua/otf/PopularScript.otf') format('opentype'),
    url('http://static.dubrovka.dn.ua/svg/PopularScript.svg#PopularScript') format('svg');
font-weight:normal;
font-style:normal;
}

It work's in any browser except Firefox.

A:

Firefox doesn't allow cross-domain font loading for security. Here are some solutions: http://www.red-team-design.com/firefox-doesnt-allow-cross-domain-fonts-by-default


Q:

How to distinguish Pretzel links with the same coefficients?

Let $P:=P(a_1,\dots,a_n)$ be a Pretzel link ( http://en.wikipedia.org/wiki/Pretzel_link ).
For every permutation $\sigma\in S_n$ we can consider the link $$\sigma P:=P(a_{\sigma(1)},\dots,a_{\sigma(n)})$$. If $\sigma=(12\dots n)^k$ for some k then $P$ and $\sigma P$ are equivalent.
My questions are:

Are there any results related to the general case?
Which invariants can be used to distinguish pretzel links which differ only by a permutation of their coefficients?

Note that $\sigma P$ is a mutant of $P$ for every $\sigma\in S_n$. So this problem is related to a more general problem i.e. how to distinguish mutant knots (or links).

A:

Richard Bedient has proved in 1984 that two Pretzel knots $P$ and $\sigma P$ are equivalent if and only if $\sigma$ is a cyclic permutation, an order reversing permutation, or a composition of both. He computes a particular group constructed from the fundamental group of the complement to distinguish every non-equivalent pair of knots.
Finding invariants is non-obvious since mutant knots have the same Jones (and HOMFLY) polynomial and hyperbolic volume. These particular mutant knots also have the same branched double covering (a Seifert manifold fibering over $S^2$ with singular fibers of order $a_1, \ldots, a_n$). In fact, Bedient was interested in finding families of non-equivalent knots sharing the same branched double covering.
Edit.  I missed some quite restricting hypothesis on the coefficients. The theorem holds if the $a_i$'s are distinct and all strictly greater than $1$. Moreover we must have $\sum_i 1/a_i <1$.
As noted by Ian, such a theorem cannot hold in general. For instance, a consecutive pair $(+1,-1)$ can be moved everywhere.


Q:

What are some specific applications of finite state automata?

There are several topics discussing finite state automata, but none that I've seen that go into detail about real world applications.  What are some concrete examples of finite state automata in action?

A:

Most popular application of FSMs are parsers of various kind.
As for real life example is my markup (HTML/XML) parser (tokenizer to be precise):
HTML_XML_Scanner


Q:

Merging two PNG images with PHP imagecopy does not work

Here a simple example that I cannot make it work.
I create 2 simple images of 2x2px with a dot in different coordinates and I try to merge it using imagecopy. The second image ($stamp) is created properly with a transparent background.
As result, I expect to see two white dots in the resulting image (result.png) but it is not the case.
I have try several combination of functions with no result.
What am I missing here?
<?php

// create source image
$src = imagecreatetruecolor(2, 2);
$white = imagecolorallocate($src, 255, 255, 255);
$black = imagecolorallocate($src, 0, 0, 0);

imagesetpixel($src, 0, 0, $white);
imagepng($src, 'src.png');

// create stamp image
$stamp = imagecreatetruecolor(2, 2);
imagecolortransparent($stamp, $black);
imagesetpixel($stamp, 1, 1, $white);
imagepng($stamp, 'stamp.png');

imagedestroy($src);
imagedestroy($stamp);

// merging images
$src = imagecreatefrompng('src.png');
$stamp = imagecreatefrompng('stamp.png');

imagealphablending($src, true);
imagesavealpha($src, true);

imagecopy($src, $stamp, 0, 0, 0, 0, 2, 2);
imagepng($src, 'result.png');

imagedestroy($src);

A:

Try something like this.
// create stamp image
$stamp = imagecreatetruecolor(2, 2);
imagesavealpha($stamp, true);
$transparent_colour = imagecolorallocatealpha($stamp, 0, 0, 0, 127);
imagefill($stamp, 0, 0, $transparent_colour);

$white = imagecolorallocate($stamp, 255, 255, 255);

imagesetpixel($stamp, 1, 1, $white);
imagepng($stamp, 'stamp.png');

The only difference is that you use imagesavealpha to allow transparency when creating the stamp and src images, then fill with transparent color using imagecolorallocatealpha.
After that, add your white pixel to one and your black pixel to the other as before. Then combine them.


Q:

Z-ORA-01745: invalid host/bind variable name (PLSQL)

I kind of new on dynamic variables in plsql.
I am getting an error "invalid host/bind variable name" on EXECUTE IMMEDIATE
statement. Thanks in advance.
CREATE OR REPLACE PROCEDURE MY_CLASS_CONFIG_DML (pBuCode     VARCHAR2,
                                                 pMyPKId     VARCHAR2,
                                                 pMyName     VARCHAR2,
                                                 pMyId       VARCHAR2,
                                                 pRemarks    VARCHAR2,
                                                 pUserId     VARCHAR2)
AS
    v_table      VARCHAR2 (50);
    v_lastdate   DATE;
    --bindable var.
    v_pkey       VARCHAR2 (12) := pMyPKId;
    v_myname     VARCHAR2 (30) := pMyName;
    v_bucode     VARCHAR2 (4) := pBuCode;
    v_myid       VARCHAR2 (12) := pMyId;
    v_remarks    VARCHAR2 (50) := pRemarks;
    v_lastid     VARCHAR2 (8) := pUserId;
BEGIN
    v_lastdate := SYSDATE;
    v_table := v_bucode || '_WORKSHEET_CONFIG';

    --Error happens on this part
    EXECUTE IMMEDIATE
           'insert into '
        || v_table
        || '(pk_id,my_name,my_id,remarks,last_user,last_date)
      values(:pkey,:myname,:myid,:remarks,:user,:lastdate)'
        USING v_pkey,
              v_myname,
              v_myid,
              v_remarks,
              v_lastid,
              v_lastdate;

    --end comment
    COMMIT;
    RETURN;
EXCEPTION
    WHEN OTHERS
    THEN
        ROLLBACK;
END MY_CLASS_CONFIG_DML;

A:

Replace :user by another keyword: :myuser or :lastid. The colon should make it possible to use the reserved keyword "user", but this is the only problem i see.


Q:

iOS - Globally change MBProgressHUD design

I use MBProgressHUD for loading screens in my app. I have 26 occurrences where I use a different HUD.
Now, I've decided to use a customised UIView (an animated UIImageView) for the HUD. I want to apply this to all the HUD's I use in my app, but the code to customise the HUD is about 15 lines long, and it's definitely not the right method to add this code to every single occurrence of a MBProgressHUD in my app.
What's the right way to go from here? This is not the first time I've run into an issue like this where I'm not sure how to keep my code cleaner and simpler.

A:

One way is to declare the spinner in the AppDelegate, and write the methods showSpinner and hideSpinner, and also define a macro to call these spinner methods.
And you can just use this macro globally in your project.It is also easy to change the spinner code in the app delegate and you don't have to change anything.


Q:

How to avoid duplicate database connection in java?

I have 2 classes. C_DB and C_Test.
In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.
Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.
C_DB
public class C_DB {
    Connection con;

    public C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public Connection getConnection() {
        return con;
    }
}

C_Test
public class C_Test {

    public static void main(String[] args) throws Exception {
        Connection con1 = new C_DB().getConnection(); // new connection
        Connection con2 = new C_DB().getConnection(); // new duplicate connection
        Connection con3 = new C_DB().getConnection(); // new duplicate connection
    }

}

A:

You can use Connection Pool and set it max pool size to 1 as @Elliott pointed out in the comment or you can implement something like this.
public class C_DB {

    private static C_DB instance;

    private Connection con;

    private C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";
        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public static Connection getConnection(){
        if(instance == null){
           instance = new C_DB();
        }
        return instance.con;
    }

}


Q:

HTML Input on change of value

I have an input tag. This tag does not have the autocomplete feature turned off, thus, one does not necessarily need to release a key to change the value of this field and focus another one. My question is: how can I detect ANY value changes of this particular field, like e. g.
<input onvaluechange="//do following..." />

The JavaScript attribute onchange does not fire on change of value, only on changes like blur, focus, etc...
EDIT: It also doesn't necessarily be a key press. Due to the autocompletion, the user can simply mouse-click the autocompletion result to change the value. This would not fire an onkeydown event.

A:

It also doesn't necessarily be a key press. Due to the autocompletion

...and many other non-key-based operations, such as right-click-cut/paste, drag and drop, undo/redo, spellchecker adjustments and so on.
HTML5 defines an oninput event to catch all direct changes.
Unfortunately browser support today isn't there (no support in IE, and there are some bugs in others), so all you can do if you really need to detect all changes to an input value earlier than onchange is to use setInterval to add a poller that constantly compares against the previous value.

A:

Detecting "value" of input text field after a keydown event in the text field?


Q:

TinyMCE - load whole html content without altering meta head JavaScript tags

When I load file.html to TinyMCE, just content in body tag is available. I would like to be able to edit whole html site content with TinyMCE without striping html, head, meta, script tags, or other tags. How is this possible please?

A:

There is a plugin called fullpage that will allow you to do what you want:
https://www.tiny.cloud/docs/plugins/fullpage/


Q:

Locus of the mid point of a line segment

Problem:

A rod of length $2$ units moves so that its ends are on the positive $x$-axis and on the line $x+y=0$ which lies in the second quadrant. Find the locus of the midpoint of the rod.

My approach:
Let the midpoint be $P(h,k).$ Let the end on the $x$-axis have coordinates $(x_2,0$). The end on $x+y=0$ has coordinates $(x_1,y_1)$.
$$\Rightarrow 2h=x_1+x_2$$
$$\Rightarrow 2k=y_1$$
$$\Longrightarrow 2h+2k=x_2$$
I cannot eliminate $x_2$ from the equation.

A:

You have not used the information of the length of the rod yet. That gives you
$$(x_2-x_1)^2+(0-y_1)^2=4$$
If you plug $x_2=2h+2k, x_1=-2k , y_1=2k$ into this, you will find an equation about $h,k$.


Q:

I have no idea how to calculate volume of stack of paper since its thickness not given

a stack of pages is growing at a rate of 1 mm per day (that’s 20 pages). How fast is the volume of paper growing when the stack is 50 pages high? (Assume standard A4 page: 210 by 297 mm)
i am confused here by the input given: (lets assume paper =p and time =t)
we have rate of increase per day or dp/dt=1mm or 20 pages
This is what i have come up with:
By the given info 1mm=20 pages
At 50 pages rate of change of height will be 50/20=2.5mm
Length L and Breadth B are constant
Volume =LBH or V=LBH
dV/dt=dH/dt
2.5mm

A:

You don't need the thickness. Let $h, l,$ and $w$ be the height, length, and width, respectively. Since $V = hlw$, by the product rule, $\frac{dV}{dt} = lw\frac{dh}{dt} + hw\frac{dl}{dt} + lh\frac{dw}{dt}$. However, A4 paper itself isn't changing size, so this becomes $\frac{dV}{dt} = lw\frac{dh}{dt}$. All three values on the right are known, so you just need to calculate.


Q:

escape single quote from last name in jquery

I have ajax call in my JQuery code with which I am doing lookup with c# web method.
The call works normally most of the time, the user needs to enter last name and it will get all the results for that last name.
The problem happens when user will enter last name with single quote included such as O'leary.
This is the jquery line I am using:
   data: "{selectedAgent: '" + $('#<%=txtAgentNameText.ClientID %>').val() + "',
   companyID: '" + $('#<%=ddlCompany.ClientID %>').val() + "'}",

The problem happens with the txtAgentNameText.ClientID value.

A:

It looks like you are passing a JSON string to your jQuery ajax method. Why not just pass a javascript object?
var data = {
            selectedAgent:$('#<%=txtAgentNameText.ClientID %>').val(),
            companyID: $('#<%=ddlCompany.ClientID %>').val()
           };

$.ajax({...data:data...})


Q:

How to create a variable from CSS class attribute?

I'm trying to create a variable to is defined by a single attribute of a CSS class.  Here's what I have now, which doesn't work.
var dist = $('.nav').css(width());

What I am trying to do:  my script slides the .nav class upon click.  The problem is, I'm using @media queries that change the width of .nav, which is the same value I need to slide.  What I'm trying to do here is define the variable "dist" by the width attribute of .nav - then I could just input "dist" as the slide distance in the function.
This is probably a pretty simple thing that I'm just doing horribly wrong.  Or perhaps there is a far simpler way to do it?

A:

You're calling width as though it were a function and then (if that worked) passing its return value into css. But unless your page defines one, there's no free-standing width() function (there is one on jQuery instances).
You either want to pass the string "width" into css, or call the jQuery width function:
var dist = $('.nav').css("width");
// or
var dist = $('.nav').width();


Q:

SEVERE Error in deploying WAR in Tomcat .ContainerBase addChildInternal error

I am not able to deploy my application war file in Tomcat Server version 7.0.54. Here is the error log.

WEB.XML
<context-param>
    <param-name>branding</param-name>
    <param-value>default</param-value>
</context-param>
<context-param>
    <param-name>brandingTitle</param-name>
    <param-value>Webchat: Fastpath</param-value>
</context-param>

<!-- Uncomment to specify your own logging
<context-param>
    <param-name>logging</param-name>
    <param-value>file://c:/log_file.log</param-value>
</context-param>
-->

<!-- Uncomment to specify your own location for the settings file
<context-param>
    <param-name>settings</param-name>
    <param-value>file://c:/my_settings.xml</param-value>
</context-param>
-->

<filter>
    <filter-name>SetupFilter</filter-name>
    <filter-class>org.jivesoftware.webchat.SetupFilter</filter-class>
    <init-param>
        <param-name>errorPage</param-name>
        <param-value>fatal.jsp</param-value>
    </init-param>
</filter>
 <filter>
    <filter-name>CharacterEncoder</filter-name>
    <filter-class>org.jivesoftware.webchat.SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SetupFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
 <filter-mapping>
    <filter-name>CharacterEncoder</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Servlets -->
<servlet>
    <servlet-name>FastpathServlet</servlet-name>
    <servlet-class>org.jivesoftware.webchat.FastpathServlet</servlet-class>
    <!-- Uncomment to have console debugger enabled
    <init-param>
       <param-name>smackDebugger</param-name>
       <param-value>org.jivesoftware.smackx.debugger.ConsoleDebugger</param-value>
    </init-param>
    -->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>org.jivesoftware.webchat.servlets.ImageServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>DynamicImageServlet</servlet-name>
    <servlet-class>org.jivesoftware.webchat.servlets.DynamicImageServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>SoundServlet</servlet-name>
    <servlet-class>org.jivesoftware.webchat.sounds.SoundServlet</servlet-class>
</servlet>

<!-- Adding Direct Web Remoting Servlet -->
<servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <display-name>DWR Servlet</display-name>
    <description>Direct Web Remoter Servlet</description>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
        <param-name>crossDomainSessionSecurity</param-name>
        <param-value>false</param-value>
    </init-param>
    <!--
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
        <description>Do we startup in debug/test mode?</description>
    </init-param>
    -->
    <load-on-startup>-1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

<!-- Servlet mappings -->
<servlet-mapping>
    <servlet-name>FastpathServlet</servlet-name>
    <url-pattern>/live/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/getimage</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DynamicImageServlet</servlet-name>
    <url-pattern>/dynoimages/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>SoundServlet</servlet-name>
    <url-pattern>/sounds/*</url-pattern>
</servlet-mapping>

<!-- Session config -->
<session-config>
    <session-timeout>1</session-timeout>
</session-config>
<mime-mapping>
    <extension>jnlp</extension>
    <mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>

<!-- Welcome file list -->
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Please help me get rid of this error!
Thanks
I am using JDK version 1.7. I have seen various solutions, but none have worked so far. It's frustrating.

A:

Resolved the Issue . It seems I had duplicate smack Jars which i had overlooked .
Silly on my part .:/


Q:

Update by iterating table in batches faster than whole table in PostgreSQL

I have a table with approximately one million rows.
It is being used in production and I ran an UPDATE which covers ~95% of those rows.
After five hours I cancelled the request because it was taking so long.

The table has an auto-incrementing ID column, so I tried extending the WHERE condition of my query to include id BETWEEN 1 AND 500.
This update completed in approximately two seconds. I then manually iterated up through the id in batches of 500, e.g. BETWEEN 500 AND 1000, then BETWEEN 1000 AND 1500.
At this rate it will require 2000 batches of 500 to update the whole table.
Updating 2000 batches at 2 seconds each is just over an hour.

My questions are:

What reasons are there for this difference?
I don't care about transaction isolation, so is there a way to simulate this 'update in batches', without having to script the 2000 updates to run separately.

A:

I'll try my best to answer your question in brief, but since I'm not really aware of your level of comfort with PostgreSQL, and I don't have a lot of time to go into an in-depth explanation anyways, I'll keep the answers simple, and you can ask for clarification if you'd like more info.
1) Why is it faster in batches?
Due to the structure of PostgreSQL's write ahead log, the amount of shared buffer space in RAM, and the attempt to perform the entire UPDATE in a single transaction, my guess is that you simply don't have enough computing resources to efficiently handle the update to nearly a million records in a single transaction.
PostgreSQL has a well-built concurrency control system, essentially meaning that it has to keep the old copies of your pre-UPDATE rows available during your UPDATE operation.  This is so that, in case another client tries to access these rows while you're updating, in case the update fails, or in case you cancel the update, you don't lose the old information.
If you perform a large enough UPDATE, PostgreSQL will load pages into memory and modify them, but will eventually run out of memory to work with, so it is forced to immediately copy these pages temporarily to disk if it wants to be able to load further pages and continue the transaction.
Rather than being able to amortize the disk writes over a period of time, you've just forced your database into a bottleneck.
2) Scripting the updates
You absolutely can script the updates, by creating a function in PL/pgSQL.  There's a lot to learn about PL/pgSQL, including a lot I probably don't know, but generally speaking, you could do something like this
CREATE OR REPLACE FUNCTION mini_batch_update()
  RETURNS void AS
$BODY$
DECLARE

id_val integer;

BEGIN

  FOR id_val IN 0..2000
  LOOP

  **UPDATE GOES HERE**
  WHERE id > (500 * id_val) AND id <= 500 * (id_val + 1);

  END LOOP;

END
$BODY$
LANGUAGE plpgsql;

I didn't take a lot of time to make this batch function in tip-top form; what I mean is that I simply hard-coded several of the numerical values for simplicity's sake.  In your case, you may want to get more detailed and include: 1) Something that checks for the maximum id value so that you set your bounds appropriately, and 2) even though I  hard-coded batches of 500, you could easily make this a function input parameter.
Sorry I don't have time to test this or make sure it really works well.  Good luck!


Q:

Pronunciation of じょ and よ

Spanish is my mother tongue and I almost can't differentiate じょ and よ sounds.
Maybe the same thing happens to English native speakers. How do you solve that problem in English... is there a common English word that uses the sound じょ and another that uses the sound よ?

A:

For equivalent English sounds, you can find the Japanese じょ sound in certain names and words:

Joe
Joad
joke

You can also find the Japanese よ sound in certain words:

yo-yo
yo (slang)

Here is an example of a phrase in Japanese that uses longer forms for each of the sounds じょ and よ on this website: JOUYOU KANJI
On that page is an audio recording of someone named "akitomo" speaking a phrase that includes both the じょ and the よ sounds: "JOUYOU KANJI".  (In that recorded phrase, can you hear the difference between the first part "JOU" and the second part "YOU"?)
As your native language is Spanish, you could almost think of Brazilian Portuguese pronunciation for (at least some cases of) the letter "j" when it comes to pronouncing the じょ sound, as well.  Do keep in mind, however, that the Brazilian Portuguese pronunciation might be slightly different (i.e. more of a softer "j" sound) than the Japanese pronunciation of じょ.


Q:

How can I catch dialog tab change in CKEditor 4?

I've been searching all day for this, but it seems there's no event triggered on dialog tab change. Is there any way to trigger some function when dialog tab is shown/changed/clicked? And I mean the moment it's clicked or shown, but NOT just getting active tab on some dialog element change or onOk.
Using latest CKEditor 4.4.5
Thanks

A:

There is a dialog event "selectPage" (http://docs.ckeditor.com/#!/api/CKEDITOR.dialog-event-selectPage)
for example:
 return {
         title : editor.lang.googlemaps.title,
         minWidth : 500,
         minHeight : 460,
         onLoad : function()
         {
            this.on('selectPage', function (e) {
               // your code
            });
         }
}

source:
http://ckeditor.com/forums/Support/How-add-selectPage-listener


Q:

How to discover web servers on a local network?

Suppose I'm running several servers serving basic requests on my local network (say a home network, where all machines generally have an IP in the form K.K.K.x, where x is variable). Is there an easy way to discover all such servers? I would need to find each IP on the network running a particular java server application.

A:

Are you looking for a solution within your Java application?  If you are simply looking for a one-time solution, nmap should work.
If your local network is of the form 192.*.*.* try this (I added sudo because it must be run as root):
sudo nmap -vv -sS -O -n "192.168.1.1/24"

A:

So you have a class C network... just attempt to open the particular server applications port on each IP address between 1 and 254.  If you want to get fancy, you can do some checks to verify that if the port actually opens, it does what you expect for that application.


Q:

Is it Possible to Return to a Neutral Vote State?

If I've down-voted something, and then later I come back and see an improved answer that

I wouldn't have down-voted
but still doesn't rise to an answer I feel is worth an upvote

is there a way to return my vote to a neutral state?
I'm not advocating for or against the behavior, I'm just wondering if its possible.

A:

Yes - just click on the down-vote arrow again. As long as you're inside the vote window or the post has been edited your down-vote will be removed. You'll even get your 1 point of rep back.
The same applies to up-votes as well of course (apart from the bit about the rep).
It actually says this on the tooltip you get when you hover over the voting arrows (which I forgot and should have added sooner).


Q:

CSS horizontal line in the middle of a td

The idea is, in a table, inside a td put a line in the middle of such, like this:

That you can write in it and the line stays there, like a "line background", but inside the td
Any ideas?

A:

There are many ways
1)  Add HTML <strike> or <del>.
2) use css property, text-decoration: line-through;
3) Using CSS:
td{
    border: 1px solid black;
    position: relative;
}

td:after{
    content: "";
    display: block;
    width: 100%;
    height: 1px;
    background-color: black;
    position: absolute;
    top: 50%;
}

Working Fiddle
EDIT: Since there is a bug in firefox related to position: relative and td element, wrap the text in a div of each td and use the same above css.
Working Fiddle
EDIT 2: In the comments below, @NicoO showed that the firefox bug can be resolved by giving line-height: 0 to the tr element.
Working Fiddle


Q:

Cannot add children to tree node

I retrieve data from my db put it inside a custom class DataClass and then I format mydata to an ArrayList of Nodes and until here every thing is fine. Then, I would like to make a loop over my data and add the children to each Node. But I'm having a NullPointerException error ...
So My class looks like :
@Entity
public class DataClass {
    @Id
    private Integer id;
    private String structureDescription;
    private String structId;
    private String structureTag;
    private Integer elementId;
    private String elementDescription;
    private Integer elementsSuite;
    private String elementTag;
    private Integer parent;
    private Integer elementTypeId;

Then I have a Node class :
public class Node {
    private String id = "-1";
    private List<Node> children = null;
    private String parent = "#";
    private String text = "";

    public Node(){}

    public Node(String id, String parent, String text) {
        this.id = id;
        this.parent = parent;
        this.text = text;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Node> getChildren() {
        return children;
    }

    public void setChildren(List<Node> children) {
        this.children = children;
    }

    public void addChild(Node child)
    {
        children.add(child);
    }

    public String getParent() {
        return parent;
    }

    public void setParent(String parent) {
        this.parent = parent;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean equals(Node node)
    {
        return node.getText().equals(getText());
    }
}

So I have a method that format a List of DataClass objects into anArrayList of Nodes :
public ArrayList<Node> formatData(List<DataClass> dbData)
{
    ArrayList<Node> result = new ArrayList<>();

    for(DataClass dbDataElement : dbData)
    {
        Node node = new Node();
        node.setId(String.valueOf(dbDataElement.getId()) == null ? "" : String.valueOf(dbDataElement.getId()));
        node.setParent(String.valueOf(dbDataElement.getParent()));
        node.setText((dbDataElement.getElementTag() == null)  ? dbDataElement.getStructId() : dbDataElement.getElementTag());
        result.add(node);
    }
    return result;
}

And then I have a method that is supposed to find all the children for each node :
public ArrayList<Node> addNodeChildren(ArrayList<Node> formattedNodes)
{
    ArrayList<Node> result = new ArrayList<>();

    for(Node parent: formattedNodes)
    {
        for(Node possibleChild: formattedNodes)
        {
            if(String.valueOf(parent.getId()).equals(possibleChild.getParent()))
            {
                parent.addChild(possibleChild);
            }
        }
    }

    return result;
}

But when I call return mainService.addNodeChildren(mainService.formatData(dbData)); from the controller i'm having this error :

09-May-2017 11:06:18.498 SEVERE [http-nio-8080-exec-211] null.null An
  exception was not mapped due to exception mapper failure. The HTTP 500
  response will be re turned.
  java.lang.NullPointerException
    at be.groups.observatory.domainmodel.Node.addChild(Node.java:38)

    at be.groups.observatory.be.groups.observatory.services.MainService.addNodeChildren(MainService.java:37)

    at be.groups.ui.resource.StructureResource.getAllChildren(StructureResource.java:130)

A:

you never initiated your children instance,
There are many fixes one of which is that you can change your method addChild to this:
   public void addChild(Node child)
    {
        if(children==null){
           children=new ArrayList<Node>();
        }

        children.add(child);
    }


Q:

How to correctly handle event with dynamically added elements?

I am developing a ToDo app with HTML and JS, while got stuck with removing dynamically added elements. Is there any way to remove the selected element?
I have tried to delete an element via selecting its parent and then reaching to the child and removing it. Could not arrange to remove the selected element though. el.removeChild(el.childNodes[0]) removes the element from the beginning. Is there any way to remove the selected-active element?
document.addEventListener('click',function(e){
  if(e.target && e.target.id== 'rem'){
    let el = document.getElementById('uList');
    el.removeChild(el.childNodes[0]); // How to remove the clicked el?
   }
});

I expect the code to remove the clicked element, rather deleting the nodes starting from the 0 element.
Many thanks!

A:

document.addEventListener('click', function(e) {
    if (!e.target || e.target.id !== 'rem') {
        return;
    }
    let parent = e.target.parentElement;
    if (!!parent) {
        parent.removeChild(e.target);
    }
});

for the parent of parent:
document.addEventListener('click', function(e) {
    if (!e.target || e.target.id !== 'rem') {
        return;
    }
    const parent = e.target.parentElement;
    if (!parent) {
        return;
    }
    const parentOfParent = parent.parentElement;
    parent.removeChild(e.target);
    if (!!parentOfParent) {
        parentOfParent.removeChild(parent);
    }
});


Q:

rails attr_accessible rspec check

When I want to test if attribute is / is not accessible with RSpec I'm doing it like this
class Foo
  attr_accesible :something_else
end

describe Foo do
  it('author should not be accessible')    {lambda{described_class.new(:author=>true)}.should raise_error ActiveModel::MassAssignmentSecurity::Error}
  it('something_else should be accessible'){lambda{described_class.new(:something_else=>true)}.should_not raise_error ActiveModel::MassAssignmentSecurity::Error}
end

is there better way doing that ?
...thx

A:

This is the way attribute accessibility tests are done in the Rails Tutorial, which I think are pretty good.  So, in your case, the test code could be modified slightly to read like:
describe Foo do
  describe "accessible attributes" do
    it "should not allow access to author" do
      expect do
        Foo.new(author: true)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end

    it "should allow access to something_else" do
      expect do
        Foo.new(something_else: true)
      end.to_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end
end

If this isn't what you were looking for, can you give us a better idea of what kind of solution you're after when you ask if there is a "better way"?
Edit
You may be interested in the Shoulda ActiveModel matchers, which would clean up the code to just one line per test.  Something like:
it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }


Q:

Create popup boxes for each row in mySQL

So I have the following code:
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";
$result=mysql_query($sql);

while($rows=mysql_fetch_array($result)){
  $links = $rows['links'];
  $linksArray = explode(',', $links);
  if ($links == ""){
    unset($linksArray);
  }
?>
//LINK TO ACTIVATE POPUP BOX

<?php echo $rows['title'] ?>

Posted @ <?php echo $rows['date'] ?>

      <?php
      if (!empty($linksArray)){
        ?>
      Links associated with this post:
      <? } ?>
      <?php
      foreach($linksArray as $link) {
        ?><a href="<? echo $link ?>">Here
        <?
    }
    ?>

Here i am

        ×

        <?php echo $rows['news'] ?>

<?php
}
mysql_close();
?>

For each row identified by my query, it links it to a popup box. However all the rows being outputted activate the same popup box. My question is how to create my popup box such that each row being outputted is linked to different popup boxes, if that makes sense. Such as the first row, when linked opens a popup box with that row's info. The next row after, when linked opens a popup box with that row's info, and so on. (I guess maybe like a dynamic popup box?)

A:

Add a counter in your loop and where you have your  and
 add in the counter variable like <a href="#popup<?php echo $x ?>"> and <div id="popup<?php echo $x ?>" class="overlay">
This would make your popup id unique.


Q:

How to exclude bank holidays from working days calculation?

I have been able to show working days excluding weekdays.
But now i need to know how to also exclude bank holiday. Please help?
This is my current code:
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2016/01/01'
SET @EndDate = '2017/01/01'

SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
   DECLARE @TotalDays INT,@WorkDays INT
   SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
  print @TotalDays

A:

Try this out, i think it should work
SELECT COUNT(1)
    FROM  bankholidays
    WHERE (@Region = 1 and Column1 BETWEEN @StartDate AND @EndDate)
    or (@Region = 2 and Column2 BETWEEN @StartDate AND @EndDate
    or (@Region not in (1,2) and Column3 BETWEEN @StartDate AND @EndDate


Q:

SQL Profiler displaying stored procedure that doesn't exist

I have an automated service that runs 3 stored procedure namely sp_1, sp_2, sp_3. When I was running SQL Trace, it displayed the following results
EXEC sp_1
EXEC sp_1
EXEC sp_2
EXEC sp_2
EXEC sp_4
EXEC sp_4
EXEC sp_2
EXEC sp_2

I don't know where the sp_4 came from. It doesn't exist in my automated service nor database.

A:

I know it sounds snippy, but who cares what is in the dababase?
The profiler shows what SQL gets executed. I can call in "EXEC funnybunny" and SQL Server will throw an error - AND the profiler will show that as being called.
So, in your case - stop looking at the database. Rather go to the application and look there why you call a SP that does not exist in the database. Look at the applicaiton layer (and the trace in more detail should tell you the call fails).


Q:

Question about Class in python Need to pass the whole class by using method from another class

I was building several classes, and those class and its method need to be passed by method from another class.
class SimplePlotGenerator:

    def __init__(self):
        self.phrase = 'Something happens'
    def generate(self):
        return self.phrase

and here another class should do.
pv = PlotViewer()
pv.register(SimplePlotGenerator())

pv.generate()
'Something happens'

I have two more class for the PlotGenerator.
My question is how to build that register method. I think it might be some sort of multiple inheritances but I kind of stuck there.

A:

It's not 100% clear but I think you probably just want to make this a constructor parameter:
class PlotViewer:
    def __init__(self, generator):
        self.generator = generator

    def generate(self):
        self.generator.generate()

# To use
pv = PlotViewer(SimplePlotGenerator())
pv.generate()

I'm assuming you want a parameter rather than inheritance as the names "generator" and "viewer" sort of imply that it is not true that a SimplePlotGenerator "is a" PlotViewer. However, if a plot generator is a kind of plot viewer then yes, you might want to have SimplePlotGenerator inherit from SimplePlotViewer.


Q:

Recommendations for a google finance-like interactive chart control

I need some sort of interactive chart control for my .NET-based web app.  I have some wide XY charts, and the user should be able to interactively scroll and zoom into a specific window on the x axis.  Something that acts similar to the google finance control would be nice, but without the need for the date labels or the news event annotations.  Also, I'd prefer to avoid Flash, if that's even possible.  Can someone please give some recommendations of something that might come close?
EDIT:  the "real" google timeline visualization is for date-based data.  I just have numeric data.  I tried to use that control for non-date data, but it seems to always want to show a date and demands that the first data column actually be a date.

A:

How about using the "real" google finance tool from the Google visualizations project?
http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html

A:

This is the one you are looking for. An almost exact match for the Google Flash graph.
http://www.humblesoftware.com/finance/index

A:

Have a look at the the Google vizualisation API, I guess this is what Google uses on Google Finance. I had a look at a few other chart API's, but this one is free and beautiful.


Q:

Jenkins email notification is successfully sent but not received

When I run test emails from the Jenkins configuration page they are reported as "successfully sent" but only sporadically arrive (sometimes after a long delay) to internal company email.  When I change the test email to send to an external (gmail) account it is immediately received.
I am using the company smtp mail server.  I am able to telnet to it from Jenkins master and successfully send internal emails that way.
Jobs notification emails never arrive even though Jenkins reports it as:
Email was triggered for: Success
Sending email for trigger: Success
Sending email to: <MY EMAIL>

I couldn't find anything in the jenkins.log (but maybe I need to look at a different log?).  Any help with troubleshooting the root cause would be great.

A:

Answering my own question: I overlooked the SMTP settings in manage Jenkins page for the Extended E-Mail Notification plugin.  It was only set for E-Mail Notification


Q:

C# NotFiniteNumberException Doesn't work

I want my program to throw an exception when some floating point variable reaches infinity or is Nan NotFiniteNumberException which looks like a solution but there is a problem.
This
try
{
    Single x = 5;
    x = x / 0;
    x = x + 1;
}
catch (NotFiniteNumberException ex)
{
    //bla bla bla
}

won't throw anything.
I'm aware of IsNan and IsInfinity methods but that's not what I'm looking for.

A:

That's because your division won't throw a NotFiniteNumberException. It will simply return infinity for x.
From the documentation of NotFiniteNumberException:

NotFiniteNumberException is available for programming languages that do not support the concepts of infinity and Not-a-Number in floating-point operations.

C# does support infinity and Not-a-Number for floating-point operations, so this exception does not apply here. You need to manually check the value of x after performing the division.


Q:

Prove that $R$ given by $L(a,b)\cap W =\varnothing$ is an equivalence relation.

Let $V$ be a real vector space and suppose $W$ is a subspace of $V$ with $\dim(W)=n-1$. Now define a relation $R$ on $V-W$ s.t. $$aRb\iff L(a,b)=\{ra+(1-r)b | 0\leq r \leq 1\}\text{ has the property that }L(a,b) \cap W = \varnothing$$ Prove that $R$ is an equivalence relation.
I am having problem to check transitivity. If $aRb$ and $bRc$ suppose $a$ is not related to $c$, then $\exists t \in (0,1)$ s.t $ta+(1-t)c \in W$. How do I get a contradiction?

A:

The intuition why this is an equivalence relation is, as explained by almagest, that the hyperplane $W$ seperates $V-W$ into two connected components. Two points $a,b\in V-W$ are in the same component if and only if the line segment $L(a,b)$ does not intersect the hyperplane $W$.
For a formal approach, describe $W$ as the kernel of some non-trivial linear-form $\omega\colon V\to\mathbb R$. Now let's translate $aRb$ using this description. Instead of $L(a,b)\cap W=\varnothing$ we can say

For all $x\in L(a,b)$ we have $\omega(x)\neq 0$.

and even more explicit

For all $0\le r\le 1$ we have $r \omega(a) + (1-r)\omega(b)\neq 0$.

Now this is a statement solely about the two real numbers $\omega(a)$ and $\omega(b)$. In fact, using the intermediate value theorem, you can check that this is equivalent to

The two non-zero real numbers $\omega(a)$ and $\omega(b)$ have the same sign.

From this the fact that this relation is an equivalent relation becomes obvious.

Let me elaborate on the equivalence claimed above.
Suppose $\omega(a)$ and $\omega(b)$ are non-zero real numbers with different signs. Consider the real function $f\colon [0,1]\to\mathbb R$ with $r\mapsto r\omega(a)+(1-r)\omega(b)$. This function is continuous with $f(0)=\omega(b)$ and $f(1)=\omega(a)$. Since $f(1)$ and $f(0)$ are non-zero of different signs, the intermediate value theorem says there exists $r\in(0,1)$ such that $f(r)=0$, hence $r\omega(a)+(1-r)\omega(b)=0$.
Now suppose that $\omega(a)$ and $\omega(b)$ are non-zero real numbers with the same sign. When $\omega(a),\omega(b)>0$, you can conclude that $r\omega(a)+(1-r)\omega(b)>0$ for all $r\in[0,1]$ since products and sums of positive numbers are positive. The same approach works for $\omega(a),\omega(b)<0$.


Q:

Populating listbox from another listbox selection

I am pretty much a newbie to using VBA in Access and I'm having trouble with something that seems like it should be quite simple.
I have two listboxes (called LB1_ID and LB2_ID) on my form (MainForm) that I want to list related IDs from their respective Row Sources. I need LB2 to be populated based on the selection in LB1. They both have Row Sources from the same Table (Table1) and it is a many to many relationship of Requirement IDs ("Req ID1" and "Req ID2"). My current form, which is not working, has the Row Source of LB1 as:
SELECT Table1.ID, Table1.[Req ID1] FROM Table1 ORDER BY Table1.ID;

and the Row Source of LB2 as:
SELECT Table1.ID, Table1.[Req ID2] FROM Table1 WHERE ([Forms]![MainForm]![LB1_ID]=Table1.[Req ID1]);

When I make a selection in LB1, nothing happens in LB2. The column widths are formatted correctly and I can get it to work if I use Me.[Forms]![MainForm]![LB1_ID] but I have to type out the LB1 selection manually in a popup box if I use that.
What am I missing?

A:

If your listbox is multi-select, you cannot use a simple form reference as query criteria. If it is not multi-select, keep in mind that its value may be a hidden column (usually an ID field), so there are two possible issues and solutions:
Possible Issues:

Single-Select listbox has an ID field that is hidden (column width = 0") and you are matching it to the wrong field in your table. To check the output of the listbox, open the VBE and type ?[Forms]![MainForm]![LB1_ID] into the immediate window and press enter when your form is open in form view and a row is selected in LB1_ID. If the returned line is what you expect, then the problem must be elsewhere.
Multi-Select listbox property is enabled. In this case, your query will not work, because the listbox will only return Null. You will need to write some VBA to loop through the rows and figure out which ones are selected, which is a bit of a pain. Ultimately you'll build some code that will alter your query with the specific criteria for each selected row. Instead of explaining here, take a look at this article for a tutorial.

The .Requery method is still important to put in the AfterUpdate event of your first listbox to refresh the second.


Q:

Drop down menu button isn't coloured fully and there are strange gaps in between

I'm trying to fix my drop down menu but I'm having problems with the highlighted colour and the background colour/size.
When I hover it, it is not covering the full button with orange like I want it to and, it has some grey left in it from the background where I don't want it to be.
One of the issues may be the fact I'm using 2 style sheets for mobile and computer.
HTML:

Home

About Revelstoke

Ticker Rates

Snow School

Kids Lessons

Adult Lessons

First Tracks

Weather

Gallery

Trail Maps

Contact Us

CSS (computer):
#nav {
    background-color:#eee;
    height: 33px;
    border-top: solid black 2px;
    border-bottom: solid black 2px;
    min-width: 1000px;
}

#nav #active a {
    font-weight: bold;
    color: #ffffff;
    background-color: #0160a2;
    padding: 5px 15px 8px 15px;
}

#nav ul {
    text-align: left;
    font-size: 18px;
    background-color: #eee;
}

#nav ul li {
    display: block;
    position: relative;
    float: left;
    line-height: 24px;
}

#nav ul li a {
    display:inline;
    padding:5px 10px 8px 10px;
    background-color: #eee;
}

#nav li ul {
    display: none;
}

#nav li:hover ul {
    display: block;
    position: absolute;
    margin-top: 6px;
    padding: 0;
    width: 97px;
    height: 82px;
}

#nav li:hover li {
    font-size: 14px;
}

#nav ul li a:hover {
    background-color: #ff8a00;
    color: #000000;
}

#nav ul li ul li a{
    padding:5px;
}

#nav ul li ul li a:hover{
    padding:5px;
    width: 97px;
    height: 82px;
}

CSS (mobile):
#nav {
    background-color:#eee;
}

#nav ul {
    text-align:center;
    font-size: 18px;
}

#nav ul li {
    list-style-type:none;
    border-top: 3px solid white;
}

#nav ul li a {
    color: #000000;
    display:block;
    padding:13px 0;
    text-decoration:none;
    font-weight: bold;
}

#nav ul li a:hover {
    background-color: #0096ff;
    font-weight: bold;
    color: white;
}

#nav #active a {
    background-color: #01385e;
    font-weight: bold;
    color: white;
}

A:

If I understood your question this should be a solution http://jsfiddle.net/GcDGv/2/ (I worked only for non-mobile CSS), this is how I fixed it:

I removed all height properties from classes related to the sub-menu. They can be auto-calculated.
Change the width of li elements in sub-menu to 100%, so now they will use whole area.
Make links in sub-menu as block elements, so margin/paddings from top and bottom will work as you want. And removed width and height properties from last style ul li ul li a:hover


Q:

Return value from function "outside"

I am beginner in Laravel and php.
I have this code:
$arrayToDelete = array();
$traverse = function ($categories) use (&$traverse) {
    foreach ($categories as $category) {
        //$this->model->delete($category->id);
        echo 'Delete'.$category->category_name.' i '.$category->id.'
';
        $traverse($category->children);
    }
};

dd($traverse($node));

This code return me:

Delete Mobile i 14 Delete Samsung i 15 Delete iPhone i 16 Delete Xiomi
  i 17

It's ok.
I need add id to $arrayToDelete. How can I make it?

A:

You can pass more than one parameter into the USE so pass your other array, also by reference of course
$arrayToDelete = array();
$traverse = function ($categories) use(&$traverse, &$arrayToDelete) {
    foreach ($categories as $category) {
        arrayToDelete[] = $category->id;
        echo 'Delete'.$category->category_name.' i '.$category->id.'
';
        $traverse($category->children);
    }
};

dd($traverse($node));


Q:

How to perform action on OK of JOptionPane.showMessageDialog

I am working on my first desktop based Java project. I have 2 questions actually
1) How to perform action on OK button of JOptionPane.showMessageDialog.I want to navigate to a new Jframe say x.java on clicking ok.
2) I have a table named as user. This table has 8 columns userid (Primary Key), name, password,emailid, dob, mobileno ,city, date. Four column entries has to be fetched from a Jframe x and remaining four from other Jframe y.
I wrote the following code
For Frame X
PreparedStatement stm = con.prepareStatement("insert into user

(userrid,name,password,emailid))values (?,?,?,?) ");

      stm.setString(1,id); // id is a public variable
      stm.setString(2,name);
      stm.setString(3,ps);
      stm.setString(4,email);
     stm.executeUpdate();

And for Frame Y. (userid is primary key)
public class Y extends javax.swing.JFrame
{
    X o = new X(); // to access id variable from frame X

}

PreparedStatement stm = con.prepareStatement(" update user set  dob ='? ', mobileno
='?' ,city='?', date='?'  where userid= 'o.id' ");

It keeps throwing exceptions for the above sql query
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

A:

1) How to perform action on OK button of JOptionPane.showMessageDialog.I want to navigate to a new Jframe say x.java on clicking ok.

int input = JOptionPane.showOptionDialog(null, "Hello World", "The title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);

if(input == JOptionPane.OK_OPTION)
{
    // do something
}


Q:

Photoshop CC2019 auto-update all linked smart objects including nested ones

I have Photoshop CC2019 PSD document containing several smart objects that contains other smart objects that contains other smart objects. Some of these have linked layers. Normally, such images are not updated automatically (which is extremely annoying, Adobe!) but you have to manually update each of them once the linked image content has changed.
There is a .jsx script file named "Update All Modified Content.jsx" which auto-updates linked layers (PNG image in my case) but only if the smart object is in the top most document - that is no nested smart objects with linked layers are updated automatically.
My question is: does anyone know how to update the content of the above mentioned .jsx file so that it would auto-update all linked images across all the smart objects in PSD document including nested ones?
For those who care or would be willing to help updating the code here it is:
// Update all modified content
var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO );

A:

So, after spending half a day with it I finally solved it myself. Here is the code:
#target photoshop

// SET INITIAL ACTIVE DOCUMENT
var mainDocument = app.activeDocument;

// SAVE THE DOCUMENT NAME FOR FUTURE USE
var mainDocName = mainDocument.name;

// RUN THE MAIN UPDATE FUNCTION
mainDocument.suspendHistory("processAllSmartObjects", "autoupdateAllSmartObjects(mainDocument, 0)");

// FINALLY SAVE THE MAIN DOCUMENT
mainDocument.save();

function autoupdateAllSmartObjects(theParent, prevVal) {

    // FUNCTION TO TEST IF SMARTOBJECT IS LINKED
    function isLinkedSO(obj) {

        var localFilePath = "";
        var ref = new ActionReference();
        ref.putIdentifier(charIDToTypeID('Lyr '), obj.id);
        var desc = executeActionGet(ref);
        var smObj = desc.getObjectValue(stringIDToTypeID('smartObject'));
        var isLinked = false;

        // TEST IF IT HAS LINKED FILE
        try {
            var localFilePath = smObj.getPath(stringIDToTypeID('link'));
            isLinked = true;

        } catch(e) {
            //
        }

        return isLinked;
    }

    // FUNCTION TO UPDATE LINKED SMART OBJECT
    function doTheUpdate(LYR, stackNr) {

        // SET ACTIVE LAYER TO ACTUALY ITERATED ONE
        app.activeDocument.activeLayer = LYR;

        // RUN IN "SILENT" MODE
        app.displayDialogs = DialogModes.NO;
        var layer = app.activeDocument.activeLayer;

        // IF ACTIVE LAYER IS SMARTOBJECT
        if (layer.kind == "LayerKind.SMARTOBJECT") {

            //alert(layer);

            // OPEN THE SMARTOBJECT
            app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));

            // DO THE ACTUAL FILE UPDATE
            var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
            executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO);

            // IF IT IS NOT THE "CORE/MAIN" DOCUMENT
            if(stackNr > 0) {

                // SAVE CHANGES (UPDATE) AND CLOSE IT
                app.activeDocument.close(SaveOptions.SAVECHANGES);
            }

            // CONTINUE INSIDE THIS ACTIVE SMARTOBJECT
            autoupdateAllSmartObjects(app.activeDocument, stackNr);
        }

        return;
    }

    // FUNCTION TO PARSE GROUPS
    function parseGroup(LYR) {

        var groupLayers = LYR.layers;

        // IF GROUP IS NOT EMPTY
        if(groupLayers.length > 0) {

            // PARSE ALL LAYERS IN THE GROUP
            for (var i = groupLayers.length - 1; i >= 0; i--) {

                var lyr = groupLayers[i];

                // IF NOT LOCKED = NOT EDITABL:E
                if(!lyr.allLocked) {

                    // YET ANOTHER GROUP?
                    if (lyr.typename == "LayerSet") {

                        // IF IT IS NOT EMPTY
                        if (lyr.layers.length > 0) {

                            // RE-RUN THE SCRIPT ANEW WITH THE SELECTED GROUP AS LAYERS SOURCE
                            autoupdateAllSmartObjects(lyr, 0);
                        }

                    // LAYERS
                    } else if (lyr.typename == "ArtLayer") {

                        // IF THE LAYER IS SMARTOBJECT
                        if (lyr.kind == LayerKind.SMARTOBJECT) {

                            // IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
                            if(lyr.visible){

                                // TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
                                if(!isLinkedSO(lyr)) {

                                    // RUN THE UPDATE SUB-FUNCTION
                                    doTheUpdate(lyr, i);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // PARSE ALL THE LAYERS
    for (var i = theParent.layers.length - 1 - prevVal; i >= 0; i--) {

        var theLayer = theParent.layers[i];

        // ONLY ArtLayers
        if (theLayer.typename == "ArtLayer") {

            // IF THE LAYER IS SMARTOBJECT
            if (theLayer.kind == LayerKind.SMARTOBJECT) {

                // IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
                if(theLayer.visible){

                    // TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
                    if(!isLinkedSO(theLayer)){

                        // RUN THE UPDATE SUB-FUNCTION
                        doTheUpdate(theLayer, i);

                        // IF WE ARE AT THE LAST LAYER IN THE STACK AND IT IS NOT OUR MAIN DOCUMENT
                        if(i == 0 && app.activeDocument.name !== mainDocName) {

                            // SAVE CHANGES (UPDATE) AND CLOSE IT
                            app.activeDocument.close(SaveOptions.SAVECHANGES);
                        }
                    }
                }
            }

        // ONLY Groups
        } else if (theLayer.typename == "LayerSet") {

            // RUN SUB-FUNCTION FOR GROUP PARSING
            parseGroup(theLayer);

        // ANYTHING ELSE
        } else {

            autoupdateAllSmartObjects(theLayer, m);
        }
    }

    return;
};


Q:

Unexpected Node.js program flow

I am new to node.js and working through the API.  In the stream module docs I came across this example of the "unpipe event" (actually a fusion of two examples in the docs).
const fs = require("fs);

const writable = fs.createWriteStream("write.txt");
const readable = fs.createReadStream("read.txt");

readable.pipe(writable);

setTimeout(function(){
    console.log("Stop writing to file.txt");
    readable.unpipe(writable);
    console.log("Manually close the file stream");
    writable.end();
}, 0);

writable.on("unpipe", function(src){
    console.log("Something has stopped piping into the writer");
});

I can't understand the following console.log order:
"Stop writing to file.txt"
"Something has stopped piping into the writer"
"Manually close the file stream"

Given the setTimeout callback is running - which is the first phase of the event loop as I understand - how on earth does the callback for the "unpipe" event start to run before the setTimeout callback has finished.
Originally I had the setTimeout firing after a time above zero seconds, however I was finding that the unpipe call back was always called first.  I reasoned that my computer was reading the file always first before the setTimeout was ready.  (Although I can't see any mention in the docs about the completion of the write to the file eliciting the "unpipe" event, but this makes sense I suppose).  However I can't for the life of me reason how the above program flow is occurring.  Thanks in advance for any help.

A:

As specified by the node.js documentation:

The EventEmitter calls all listeners synchronously in the order in which they were registered.

That is, when .emit is called, it synchronously runs through all listeners for the emitted event and calls them.
Note that if necessary you can wrap your callback code in process.nextTick to ensure that it will always run asynchronously, but in your case it's likely that's unnecessary.
Also the source of the call to .emit (the emission of the event) will often be asynchronous.


Q:

How do I determine the remaining ratio in this equation?

I'm developing an experience system for a game, where the experience is gained per hit.
Anyways, I need to calculate how much EXP a user should get each time they hit a monster.
So for example if a user hits 1000 on a monster with 1000 hp they get 100% of the EXP.
But if a user hits 500 on a monster with 1000 hp they get 50% of the EXP.
Now the problem is that if one user hits 300 on a monster with 1000 HP they will get 30% of the exp.
Then if another user hits 800 or higher on a monster they receive 100% of the EXP (which they shouldn't since the monster was already 30% dead they should only receive 70% of the EXP).
This is how I calculate it currently...
        damage_rate = damage / maxMonsterHealth;
        if (damage > maxMonsterHealth)
        {
            damage_rate = 1.0;
        }
        gained_exp = m_exp * damage_rate;

Any suggestions, I'm not the best at this kind of problem solving... Probably a super simple solution.
Solution...
    exp_damage = damage;
    if (exp_damage > original_CurrentHealth)
    {
        exp_damage = original_health;
    }
    damage_rate = exp_damage / m_maxHealth;
    gained_exp = m_exp * damage_rate;

A:

You could re-set the value of maxMonsterHealth each time somebody hits the monster. Alternatively, you could set up another variable, currentMonsterHealth, which starts off having the same value as maxMonsterHealth and updates its value each time somebody gains exp from hitting the monster, and use currentMonsterHealth in your calculation instead.
I'd probably go with the latter; seems less likely to interfere with the rest of the program then.
Something like
    currentMonsterHealth = maxMonsterHealth;
    damage_rate = damage / currentMonsterHealth;
    if (damage > currentMonsterHealth)
    {
        damage_rate = 1.0;
    }
    gained_exp = m_exp * damage_rate;
    currentMonsterHealth = currentMonsterHealth - damage;

As I'm not sure what you're programming in, I have no idea if the last line makes sense in the language, but hopefully you get what it means.


Q:

Log4j warnings on linux

its my first day with Titan Database, I just wanna ask if I should worry about those warnings ?!
the link provided to help me solving this issue is quite complicated
Linux Ubuntu 14.04, and I did installed JDK 8, Titan 1.0.0 with Hadoop 1
Jan 17, 2016 5:04:20 PM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.

         \,,,/
         (o o)
-----oOOo-(3)-oOOo-----
plugin activated: aurelius.titan
plugin activated: tinkerpop.server
plugin activated: tinkerpop.utilities
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/phoenix/Titan/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/phoenix/Titan/lib/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
log4j:WARN No appenders could be found for logger (org.apache.hadoop.security.Groups).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
plugin activated: tinkerpop.hadoop
plugin activated: tinkerpop.tinkergraph
gremlin>

A:

You can ignore the log4j warnings.


Q:

Apache rewrite rule with parameters?

I have the following URL:
http://domain.com/index.php?m=feedback&cSubject=My Subject

I want to have a rewrite rule so that the following:
http://domain.com/feedback?Subject=My Subject

maps to the previous url. Heres my rule at the moment:
RewriteRule ^feedback?Subject=(.*)$ index.php?m=feedback&cSubject=$1

Doesn't seem to be working tho! Any ideas?

A:

Query Strings are not parsed by Apache Mod_Rewrite, but there is a workaround. Try this
RewriteRule ^feedback/?$ index.php?m=feedback&c%{QUERY_STRING} [NC,L]

A:

You can use RewriteCond statement to do exactly what you want:
RewriteEngine On

RewriteCond %{QUERY_STRING} Subject=(.*)
RewriteRule ^feedback$ index.php?m=feedback&cSubject=%1 [L]


Q:

Why can't the earth discharge my DC batteries?

Electrical newbie here. After watching this video I noticed that in the event of a fault, the AC power in your house can discharge into the earth/ground (which thus causes the house breaker to trip).
If AC power can be discharged into the ground then why can't I drain a standard DC energizer battery by connecting a wire to the positive terminal and placing the wire in the earth/ground?

A:

If the battery negative was also connected to ground, then it would, as it's completing a circuit.
The neutral side of house AC power is connected to ground at some point, either the generation station, the sub station, or the inlet to your house, you just don't see the connection normally. It's there so that if there's a live to chassis fault in your equipment, which would be hazardous, enough current will flow to blow a fuse or trip a breaker.


Q:

How can I change the values in a particular column that are equal to a given value?

data_active is any dataset.
Ideally when the condition is satisfied, the values must be changed. But when I execute this code, it is changing the values in each of the specified columns to the values given in the if statement.
for (i in 1:nrow(data_active))
{
 if(data_active[i,1]==4866)
 {
  data_active$St="MH"
  data_active$Reg="South Central"
  data_active$REGION="South"
  data_active$Market="86"
 }
}

A:

You need to get used to a 'thinking with R' mentality. You don't need for loops or if statements. You can do this with just one line of code.
Try the following (replace id with your column name):
data_active[data_active$id == 4866,c("St","Reg","REGION","Market")] <- c("MH","South Central", "SOUTH", "86")

First, this statement is finding the rows where id matches 4866, and selecting from them the columns in the list created by c.
data_active[data_active$id == 4866,c("St","Reg","REGION","Market")]

Secondly, it is setting the values of these columnns to a new list, containing the values you desire.
<- c("MH","South Central", "SOUTH", "86")

A:

Inside your if statement, you have assigned a value to the entire column, not just to the row indicated by i. To assign to just a specific row, you need to assign to just that element of the vector.
for (i in 1:nrow(data_active))
{
 if(data_active[i,1]==4866)
 {
  data_active$St[i]="MH"
  data_active$Reg[i]="South Central"
  data_active$REGION[i]="South"
  data_active$Market[i]="86"
 }
}

That said, this is not the idiomatic way to do this in R. More natural would be to use logical indexing.
data_active$St[data_active[,1]==4866]="MH"
data_active$Reg[data_active[,1]==4866]="South Central"
data_active$REGION[data_active[,1]==4866]="South"
data_active$Market[data_active[,1]==4866]="86"


Q:

How to display images in modal bootstrap using AngularJS and ng-repeat derective?

i have simple AngularJS application, i'm trying display images in modal use bootstrap, all photos at page i'm displaying use ng-repeat directive:

and i have the code of modal:

     ×

Tell me please, how i can use it both ng-repeat and modal ?
Thanks for your answers !

A:

Just move your first code where you have ng-repeat in modal and you should be able to show your images there.

     ×


Q:

Stateful Bean using @PreDestroy to close database connection

I have a Stateful bean that is used to make a couple database queries. I open the connection in the first method I call, but I only really want to close the connection after the EJB Client is really done with the Stateful bean. I thought that I could put the logic that closes the database connection in the @PreDestroy method.
This seems to be working, but I'm curious as to the implications. When, specifically, does the EJB session complete? This is container managed transactions, so I would assume that when the EJB client method completes, so does the EJB transaction. When, specifically, does the PreDestroy method get called? Is the transaction still around? Or did it already commit and put itself back into the pool? Thanks!

A:

Below are the excerpt from specification, which might clarify the statefull session bean lifecycle.

At the end of the lifecycle, the client invokes a method annotated
@Remove, and the EJB container calls the method annotated @PreDestroy,
if any. The bean’s instance is then ready for garbage collection.
it would be wrong to perform database operations within a session
bean’s PostConstruct or PreDestroy lifecycle callback interceptor
methods and to assume that the operations are part of the client’s
transaction. The PostConstruct and PreDestroy methods are not
controlled by a transaction attribute because handling rollbacks in
these methods would greatly complicate the session instance’s state
diagram.
PreDestroy methods are invoked in an unspecified transaction and security context.
The PrePassivate callback notification signals the intent of the container to passivate the instance. The PostActivate notification signals the instance it has just been reactivated. Because containers automatically maintain the conversational state of a stateful session bean instance when it is passivated, these notifications are not needed for most session beans. Their purpose is to allow stateful session beans to maintain those open resources that need to be closed prior to an instance’s passivation and then reopened during an instance’s activation.


Q:

Tag badge styling issue

The styling for the tag badges does not fit with the rest of the design.

A:

The fix will be in the next deployment.


Q:

Can not open a text file just after creating it from webservice

I am unable to open the file just after creating the file in c# webservice code .
The directory is not present initially. So the program creates the directory and the file. Then tries to open the file to write a line. But it fails to open the file. The error is the file is open in another process.
I tried to open the file from windows explorer. the file opens but error message is still coming.
I tried to delete  the folder C:\Test, it says file is open is in WebDev.WebDevServer40.exe
Any help please.
[WebMethod]
    public string saveFileUploaderName(string name)
    {
        string path = "c:\\Test";
        string filename = "Test.txt";
        string completeFileName = Path.Combine(path,filename);
        if(!File.Exists(completeFileName))
        {
            Directory.CreateDirectory(path);
            File.Create(completeFileName);
        }
        StreamWriter writer = File.AppendText(completeFileName);
        writer.WriteLine(name);
        writer.Flush();
        writer.Close();
return "success";
}

A:

File.Create returns a stream, but you're discarding it.
So (I think!) you either need to use the returned stream, or explicitly close it before trying to open a new stream to the same file.


Q:

Jquery body click stops toggle

I have a div that needs to animate up/down on the click of a button, and, if it has been animated down (or opened) it must close if the body is clicked. This works fine however if I use the body to close it the toggle button doesn't work again on the first click. I'm hoping there is a simple fix to this, any help is greatly appreciated, thanks!
$('#button').toggle(function(event){
        event.preventDefault();
        $('#box').animate({top: '0'}, 300);
    },function(event){
        event.preventDefault();
        $('#box').animate({top: '-100px'}, 300);
    });

    $("body").click(function(event) {
        if ($(event.target).closest('#box').length === 0) {
            $('#box').animate({top: '-100px'}, 300);
        }
    });

http://jsfiddle.net/user1688604/ve7VA/1/

A:

toggle event method is deprecated, you can use click method instead. Using click and and a conditional statement can solve the issue.
$('#button').click(function (event) {
    event.preventDefault();
    var $box = $('#box'),
        val = $box.css('top') === '0px' ? '-100px' : '0px';
    $box.stop().animate({
        top: val
    }, 300);
});

http://jsfiddle.net/Wdjys/


Q:

IntelliJ cannot find find a symbol from a class in the same project

The Dice Class
package com.company;

import java.util.Random;

public class Die
{
     private int sides;
     private int result;
     public int roll()
{
    Random randint = new Random();
    return randint.nextInt(sides) + 1;

}
public int getSides()
{
    return sides;
}
public void setSides(int num_sides)
{
    sides = num_sides;

}
/**
 @param d Name of Dice
 */
public static void rollDie(Die d)
{
    System.out.println(d.roll());
}

}

The Game Class
package com.company;
import javax.swing.JOptionPane;

public class Game
{
public String dealerRoll()
{
  JOptionPane.showMessageDialog(null, "I will roll the dice now.");
  String choice = JOptionPane.showInputDialog("Even or odd?");
  return choice;
}
}

Main Class
package com.company;

public class Main {

public static void main(String[] args)
{
    Die Dice = new Die();
    dealerRoll();

}
}

IntelliJ is recognizing the Die in the main class, but not the dealerRoll. Can someone please tell me what I've done wrong? Im new to StackOverFlow sorry about the messed up formatting. I just learned classes in java but it works sometimes and sometimes it dosent. So please tell me whats wrong with the game class and the die class

A:

dealerRoll is inside Game, hence you need a reference to a game object like this:
Game game = new Game();
game.dealerRoll();

Also, please note that variable names starting with capital letters are bad practice (only classes start with capital letters), so please rename Die Dice to Die dice or to Die die


Q:

Permutations with limited repetition and various constraints

you have a string of 360 letters: 180 x 'A' and 180 x 'B'. I (hope I) understand that the number of ways this string can be permuted is $$\frac{360!}{180!180!} = \binom{360}{180}$$
What I have absolutely no clue about is how to calculate how this number changes if the following restrictions are both put into place.

The numbers of 'switches' ('AB' or 'BA') should be as close to equal as possible to the number of repetitions ('AA' or 'BB'). That would mean either 180 switches and 179 repetitions or vice versa.
The maximum number consecutive repetitions is 3 (thus AAAB would be valid, AAAAB not).

Thanks for any insights!

A:

Let's consider groups of one to three consecutive identical letters as building blocks and denote the numbers of such groups by $a_1$, $a_2$, $a_3$ for the As and by $b_1$, $b_2$, $b_3$ for the Bs, and let's first consider strings beginning with A and ending in B (and thus $179$ switches and $180$ repetitions). Then we have the following constraints:
\begin{align}
a_1+2a_2+3a_3&=180\;,\\
b_1+2b_2+3b_3&=180\;,\\
a_1+a_2+a_3&=90\;,\\
b_1+b_2+b_3&=90\;,\\
\end{align}
with solution
\begin{align}
a_2&=90-2a_1\;,\\
b_2&=90-2b_1\;,\\
a_3&=a_1\;,\\
b_3&=b_1\;.
\end{align}
Thus the number of admissible arrangements of this form is
$$
\left(\sum_{k=0}^{45}\binom{90}{k,k,90-2k}\right)^2=448581910545737950775083699792561795907509^2\;.
$$
The same number of arrangements begins with B and ends in A. You can carry out a similar analysis to find the number of admissible arrangements that begin and end with the same letter (and thus have $180$ switches and $179$ repetitions).


Q:

Why are keys hashed in Merkle Patricia Trie?

Account addresses are hashed before they are recorded in the Patricia Merkle Trie, as well as storage slot indexes. This makes it difficult to enumerate all accounts and storage slots by scanning the Patricia Merkle Trie.
Why not storing the addresses and indexes in clear?

A:

It's done for DoS Protection, as explained in the Design Rationale wiki:

Using sha3(k) as the key in the "secure tree" (used in the state and account storage tries): this makes it much more difficult to DoS the trie by setting up maximally unfavorable chains of diverge nodes 64 levels deep and repeatedly calling SLOAD and SSTORE on them. Note that this makes it more difficult to enumerate the tree; if you want to have enumeration capability in your client, the simplest approach is to maintain a database mapping sha3(k) -> k.


Q:

SDL_SetVideoMode Desired vs. Obtained

I'm writing programs in C that use SDL for graphics. I have my program optimized for writing video in a 32 bits per pixel mode. I just go along each scan line writing blue, green, red, skip, blue, green, red, skip, blue, green, red, skip (skipping those extra bytes in the 32 bpp format). Is there any chance this could fail? Could SDL deny me 32 bpp and give me something else instead? Could the byte offsets of different colors end up in a different order and screw up my program?

A:

The SDL_SetVideoMode by default ensures you get your required pixel depth. Even if the pixel depth is not available, it emulates it virtually (they call this "shadow surface"). Ofcourse, this can be disabled with the SDL_ANYFORMAT flag.
For more information, refer the following wiki
http://sdl.beuc.net/sdl.wiki/SDL_SetVideoMode
I am also suspecting that there might be a perfomance degradation if the depth is being emulated. Not sure on that.
Also with regards to your logic, I am not sure why you are doing such a native scan line manipulation. If your application really requires such control, then you are probably better off writing OpenGL or DirectX  specific code and interface them with SDL through library calls. You can google up for more on interfacing OpenGL or DirectX with SDL.


Q:

Vim: how to select a rect area and do copy/paste

e.g.
1.1.1.1  a.com
2.1.1.1  b.com
1.3.1.1  c.com
1.1.5.1  d.com
1.2.1.1  e.com

now I want to replace this ip from another text, not the same width, like 111.222.111.222, is also store in a rect text.
I know that Ctrl+v can do rect select, but how to do copy and paste?

A:

Ctrl-V, as you said, to select, then 'y' to "yank" (copy).  You can then paste it with 'p'.  You can select an area in which to paste by again using Ctrl-V and hitting 'p' instead of just hitting 'p'.  Vim will respect the rectangular area that you copied when you do the pasting, so you won't need to reformat.


Q:

The alignment of Java Layout is messed up

Trying to build a simple registration form in Java Swing and AWT, but couldn't accomplish what I really want.
Here is the result that I want

Here's the code
import java.awt.*;
import javax.swing.*;

public class MainFrame {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // Main Frame
    JFrame mainFrame = new JFrame("New Account Registration");

    JPanel borderPanel = new JPanel(new BorderLayout());
    JPanel gridPanel = new JPanel(new GridLayout(9,2));

    JPanel gridGenderPanel = new JPanel(new GridLayout(1,2));
    JPanel flowButton = new JPanel(new FlowLayout());

    //JLabels
    JLabel title = new JLabel("New Account Registration");
    JLabel name = new JLabel("Name");
    JLabel email = new JLabel("Email Address:");
    JLabel createPassword = new JLabel("Create Password:");
    JLabel confirmPassword = new JLabel("Confirm Password:");
    JLabel gender = new JLabel("Gender:");
    JLabel address = new JLabel("Address:");
    JLabel state = new JLabel("State:");
    JLabel country = new JLabel("Country:");
    JLabel phoneNo = new JLabel("Phone No:");

    String[] coutriesStrings = { "America", "Japan", "India", "Korea", "Sweden" };

    // JTextFields, JRadioButton, JComboBox
    JTextField nameField = new JTextField();
    JTextField emailField = new JTextField();
    JPasswordField passField = new JPasswordField();
    JPasswordField confirmPassField = new JPasswordField();
    JRadioButton male = new JRadioButton("Male");
    JRadioButton female = new JRadioButton("Female");
    ButtonGroup group = new ButtonGroup();
    group.add(male);
    group.add(female);
    JTextField addressField = new JTextField();
    JComboBox stateBox = new JComboBox(coutriesStrings);
    stateBox.setSelectedIndex(1);
    JTextField countryField = new JTextField();
    JTextField phoneField = new JTextField();

    JButton submitButton = new JButton("Submit");
    JButton clearButton = new JButton("Clear");

//      borderPanel.add(title, BorderLayout.NORTH);
//      gridPanel.add(title);

    // Name
    gridPanel.add(name);
    gridPanel.add(nameField);

    //Email
    gridPanel.add(email);
    gridPanel.add(emailField);

    // CreatePassword
    gridPanel.add(createPassword);
    gridPanel.add(passField);

    // Confirm Password
    gridPanel.add(confirmPassword);
    gridPanel.add(confirmPassField);

    // Gender
    gridGenderPanel.add(gender);
    gridGenderPanel.add(male);
    gridGenderPanel.add(female);
    gridPanel.add(gridGenderPanel);

    // Address
    gridPanel.add(address);
    gridPanel.add(addressField);

    // State
    gridPanel.add(state);
    gridPanel.add(stateBox);

    // Country
    gridPanel.add(country);
    gridPanel.add(countryField);

    //Button
    flowButton.add(submitButton);
    flowButton.add(clearButton);
    gridPanel.add(flowButton);

    mainFrame.add(gridPanel);

    mainFrame.setSize(600, 700);
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Here is the result of the codes

I don't know where did I do wrong, please guide me.

A:

You have to add gender label to gridPanel not to gridGenderPanel
    // Gender
    //gridGenderPanel.add(gender);//The mistake
    gridPanel.add(gender);//add to main panel
    gridGenderPanel.add(male);
    gridGenderPanel.add(female);
    gridPanel.add(gridGenderPanel);


Q:

Как убрать public из URL в проектах Laravel

У меня есть проект dev.ru.
Я залил в папку dev.ru/lara проект с laravel. Но проблема в том, что сам laravel будет доступен, только если зайти в dev.ru/lara/public.
Как сделать так, чтобы он был доступен по ссылке dev.ru/lara?
Пробовал класть htaccess в папку dev.ru/lara, который перенаправляет в public, но когда переходишь на dev.ru/lara laravel пишет not found. И laravel думает, что сейчас путь /lara. А должен /.
И получается надо всем роутам делать префикс /lara, но тогда ссылки на стили получаются неправильными. Стили подключаю через asset().
Пример: есть openserver в нем домен dev.ru, в нем разные проекты, в том числе laravel в папке lara, при такой структуре сайт будет доступен по адресу dev.ru/lara/public/
http://joxi.ru/52agj8XH4DPo9r
В общем можно ли установить Laravel в подпапку и при этом не было в ссылках public?

A:

Скопировать .htaccess из public и создать файл index.php который будет подключать index.php из папки public, но теперь стилям нужно добавлять префикс public/.
переписать функцию asset(), чтобы она сама добавляла public/ файлам.

У меня еще возникли проблемы с laravel-filemanager. Он подключает картинки через url() вместо asset(). И если заходить на dev.ru/lara4/laravel-filemanager, то превью картинок не загружалось, но сам filemanager работал. А если заходить на dev.ru/lara4/public/laravel-filemanager, то превью загружалось.
сделал define('PUBLIC_FIX',true); чтобы перенаправлять filemanager на public
index.php:
<?php
define('PUBLIC_FIX',true);

function asset($path, $secure = null)
{
    return app('url')->asset('public/'.trim($path,'/'), $secure);
}

require_once __DIR__ . '/public/index.php';

admin.blade.php
<script type="text/javascript">
    window.file_manager_url = '{{defined("PUBLIC_FIX") ? url('/public') : url('/')}}'
</script>

В итоге можно заходить как на dev.ru/lara как и на dev.ru/lara/public.
Если заходить на dev.ru/lara/public то файл сверху подключаться не будет.
2 Способ избавиться от public
Чтобы окончательно избавиться от public лучше всего настроить apache.
В openserver можно настроить так:
Alias /lara/ "%sprogdir%/domains/dev.ru/lara/public/"
<Directory "%sprogdir%/domains/dev.ru/lara/public/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
</Directory>

public/.htaccess после RewriteEngine On
RewriteBase /lara


Q:

Do you have to actively direct a Mage's Sword?

I was looking at Mage's Sword and noticed that in the spell description it states if you are not directing it the sword returns to you.  The spell description also states that the sword continues attacking its target if you do not use a standard action to direct it to a new target.  Below are the relevant sections of the spell description.

If the sword goes beyond the spell range from you, goes out of your sight, or you are not directing it, it returns to you and hovers.

and

Each round after the first, you can use a standard action to switch the sword to a new target. If you do not, the sword continues to attack the previous round's target.

Is there some unspecified action that needs to be taken to keep the sword attacking the target and not return to you?
Does this mean if you cast the spell twice, only the most recently directed sword attacks, with the other returning to you since you aren't directing it?

A:

Although the language is a little awkward, I believe the description is trying to say that the sword will attack whatever target is designated when cast, requiring no action to continue attacking that target each round. Designating a new target requires a standard action. The only time the 'return to caster' clause should trigger would be when the designated target is no longer available (dead, out of range or sight), and the caster has not designated a new target during his turn (either due to not having any valid targets, or not wanting to designate a new target, or not having any standard actions available).


Q:

Maximum area of a right-angled triangle with a fixed perimeter - can it be done without calculus?

The area, $A$, of a right-angled triangle with fixed perimeter $P$ will be maximised when the triangle is isosceles (i.e. is a multiple of the $1, 1, \sqrt{2}$ right-angled triangle). I know how to prove this using calculus, but I am interested to know whether there is an alternative proof that doesn't need advanced techniques. In particular, Simple proof that equilateral triangles have maximum area shows that a proof without calculus is possible in the general case (to show that the area of any triangle with fixed perimeter will be maximum when the triangle is equilateral), so I think a simple proof should also be possible in the right-angled case.

A:

Let a , b , c be the sides of the right angle triangle right angle at C.
$$ \therefore a^2+b^2=c^2 \,,where\,a+b+c=p\, ,\,perimeter\, of \,triangle$$
Using $AM\ge GM$ between $a^2,b^2$ we get
$$\frac{a^2+b^2}{2} \ge (ab)$$
$$\therefore ab\le \frac{c^2}{2}$$
Hence maximum area is $A=\frac{1}{2}ab=\frac{c^2}{4}$
$$ $$ AM = GM holds when $a=b$ ttherfore $c=\sqrt{2}a$
Hence sides are $a,a,\sqrt{2}a$ hence $a=(\frac{p}{2}(2-\sqrt{2}))$ where p is constant perimeter.


Q:

Powershell loop through two arrays and add content to file

I have to add text from one file to the end of another file, but the contents of one file is significantly shorter than the other, so I want to keep looping through the shorter file until the longer file is complete.  I generate the intial file (scopeout.txt) with the following code
$a = "NETSH Dhcp Server 192.168.10.1 Scope "
$b = " set optionvalue 6 IPADDRESS "
$Scopelist = Get-Content C:\ListOfScopes.txt

foreach ($i in $ListOfScopes)

{
$a + $i + $b >> C:\TestArea\scopeout.txt
}

I then have a file called newdns.txt that contains 4 entries (192.168.0.10, 192.168.0.11, 192.168.0.12, 192.168.0.13).  I want to read each line of scopeout.txt, add 1 entry from newdns.txt, then move onto the next line in each file.  I want to repeat this process until scopeout.txt is finished, so the final file will look similar to the following:
NETSH Dhcp Server 192.168.10.1 Scope 192.168.50.1 set optionvalue 6 IPADDRESS 192.168.0.10
NETSH Dhcp Server 192.168.10.1 Scope 192.168.51.0 set optionvalue 6 IPADDRESS 192.168.0.11
NETSH Dhcp Server 192.168.10.1 Scope 192.168.52.0 set optionvalue 6 IPADDRESS 192.168.0.12
NETSH Dhcp Server 192.168.10.1 Scope 192.168.53.0 set optionvalue 6 IPADDRESS 192.168.0.13
NETSH Dhcp Server 192.168.10.1 Scope 192.168.54.0 set optionvalue 6 IPADDRESS 192.168.0.10
NETSH Dhcp Server 192.168.10.1 Scope 192.168.55.0 set optionvalue 6 IPADDRESS 192.168.0.11
NETSH Dhcp Server 192.168.10.1 Scope 192.168.56.0 set optionvalue 6 IPADDRESS 192.168.0.12
NETSH Dhcp Server 192.168.10.1 Scope 192.168.57.0 set optionvalue 6 IPADDRESS 192.168.0.13
NETSH Dhcp Server 192.168.10.1 Scope 192.168.58.0 set optionvalue 6 IPADDRESS 192.168.0.10
NETSH Dhcp Server 192.168.10.1 scope 192.168.59.0 set optionvalue 6 IPADDRESS 192.168.0.11

I have experimented with using a foreach statement, but I am unsure how to combine 2 foreach statements and also how to keep looping through the newdns.txt until scopeout.txt is complete.

A:

Try this:
$c = 0
$ip = Get-Content C:\newdns.txt

Get-Content C:\ListOfScopes.txt | Foreach-Object{
    if ($c -gt 3) {$c=0}
    "NETSH Dhcp Server 192.168.10.1 Scope $_ set optionvalue 6 IPADDRESS $($ip[$c])"
    $c++
}


Q:

How to ensure that demesne holding are not lost on succession?

Basically when ruling, it always says titles lost on succession. I am wondering how exactly you can ensure not losing demesne titles upon death, so that the heir to the kingdom keeps the same demesne holdings as his father did?

A:

It depends on your succession laws. If you have gavelkind succession, your titles will be divided between your children. If you have primogeniture your eldest son will inherit all of your titles.
Now, lets say you rule more than one kingdom. In that case, each kingdom has its own succession laws. You can toggle between them by clicking on the respective coat of arms in the 'Laws' window.

You can read much more in the Succession Laws article on the CK2 wiki.