Q:

Offset Div background on page load

I currently have a div with a background that is offset -500px x -200px, and reacts with mouse movement. The way I have it set up, it only offsets after the mouse is moved. I have tried several times to get .onload to work so it would offset it as soon at the page loaded, but I'm new to javascript and Jquery and I'm stumped.
Code to move the background of the div:
$(document).ready(function(e){
    $('.landing-content').mousemove(function(e){
       var x = -(e.pageX + this.offsetLeft) / 80;
       var x2 = x * -1 - 500;
       var y = -(e.pageY + this.offsetTop) / 80;
       var y2 = y * -1 - 200;
       $(this).css('background-position', x2 + 'px ' + y2 + 'px');
    });
});

Live example: http://afrohorse.netau.net/
If you move your mouse around the screen, then press refresh, you'll see what I mean.
Any help is appreciated, thanks in advance! :)

A:

When your page is loaded, your background position will be what you have set it to in CSS (0, 0 by default, or -500px -200px if you have that set).
Now once a user starts moving his mouse around on your page, you execute the following code:
$('.landing-content').mousemove(function(e){
   var x = -(e.pageX + this.offsetLeft) / 80;
   var x2 = x * -1 - 500;
   var y = -(e.pageY + this.offsetTop) / 80;
   var y2 = y * -1 - 200;
   $(this).css('background-position', x2 + 'px ' + y2 + 'px');
});

Seeing as how you calculate the offset, it seems pretty logical that you can see it jump when it first initialises. For example, if your CSS sets the offset to -500px -200px, on mousemove jQ will suddenly set it at -580px -256px (depending on where your mouse is located).
You'll need to find a way for JQ to set the background position on pageload, so that it perfectly matches whatever outcome your mousemove calculation will give it once a user starts moving his cursor around.


Q:

Ampersands (&) in xlink:href attributes of SVG images?

I'm building an SVG document which contains various image tags. The xlink:href (source URL) attributes for the images contain query strings with ampersands. If I escape them as %26 or the ascii encoding ? they're not valid query strings and the server won't deliver the image. I can't escape them with CDATA because they're attributes (not nodes). I've tried creating an xlink:href node within the image tag but that get's ignored by the SVG parser. I want to use pure SVG (not SVG within HTML) so that I can convert to a JPG later, thus scripting is out...
Any hints on how I can make the below work?
<image x="0" y="0" width="306" height="306" xlink:href="http://host.com/image.jpg?token=asdf&expiration=9384029&etc=etc"/>

Thanks!

A:

The solution is to replace the ampersands with the correct ascii code #38 and Not #63 (which is a question mark '?') as I had initially tried after mis-reading this question: using "?" in SVG href
Thanks to Stunti https://stackoverflow.com/users/54949/stunti
http://www.ascii.cl/htmlcodes.htm


Q:

Opencv build do not set tbb as ON

I have downloaded latest source of tbb and run the following commands (working on raspbian):
sudo make CXXFLAGS="-DTBB_USE_GCC_BUILTINS=1 -D__TBB_64BIT_ATOMICS=0"
source tbbvars.sh (in the related folder)

but when I do
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON

it do not actually set TBB:ON. So I do not continue with make, make install. What am I missing?

A:

Seems like it takes much work to make tbb visible
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_TBB=ON ..

just does the trick. Hope this will help other beginners as well.


Q:

factory_girl linter failing because of ActionView::Template::Error

I'm in the process of working out the bugs for updating an app from rails 4.1 to rails 5. When I try to run my tests the factory_girl linter complains that some of the factories are invalid:
/Users/stephen/.rvm/gems/ruby-2.3.1@ssa/gems/factory_girl-4.7.0/lib/factory_girl/linter.rb:13:in `lint!': The following factories are invalid: (FactoryGirl::InvalidFactoryError)

* call_log - Undefined variable: "$green". (ActionView::Template::Error)
* sms_log - Undefined variable: "$green". (ActionView::Template::Error)

etc.
This is all factory girl really gives me for a stack trace. It tells me the where the linter is called but that is it. No indication where something might be going in the view. Is there a way for me to determine this? It seems like this is going to be very difficult to debug fi I don't know where it's coming from.

A:

Having investigated by sitting right next to you, I am going to go out on a limb and say that the model has a callback that sends an email, which triggers the whole ActionView rendering, which apparently has some errors.
More proof that callbacks are bad - particularly ones that send emails.


Q:

ember-cli --proxy works for GET but fails on PUT and POST

I'm trying to move my application from Ember Appkit to ember-cli and I'm having trouble replicating the proxy functionality previously provided by the APIMethod and proxyURL methods.
I'm starting the server to proxy to localhost:3000
ember serve --proxy http://localhost:3000/
This will read my data from the rails server correctly.  However, when I try to write to the server, I get an error message
POST http://localhost:4200/api/v1/posts 408 (Request Time-out)
It's trying to post to port 4200, which is where the ember app is being served, but I want it to post to port 3000. How can I get it to do so?
I'm using ember-cli 0.28, ember 1.5.1, ember-data 1.0.0-beta.7, and rails 4.1.

A:

The solution was to comment out app.use(bodyParser()); in server/index.js


Q:

jQuery droppable accordion

I've been playing around with trying to create a droppable accordion for a little while, and haven't gotten it to be very responsive.  When I drag an item over the accordion, it takes 5+ seconds for the accordion element to open (if it does at all).  Sometimes I have to "wave" the dragged element over the accordion element.
I know I read something a while back about event processing in javascript - something along the lines of the browser not always passing control to the javascript engine when you think it does, or something like that, resulting in weird timing.
Has anyone else seen tried to do this before?  Have you found jquery/javascript to be this slow?  Do you have any references for how to get a responsive droppable accordion (the jQuery UI site doesn't seem to, and I didn't find anything on SO or Google).
Thanks!

A:

Hiya! I posted a demo where you can drag a list item and place it into an accordion menu.
The key to it is using the dropover bind event added by the .droppable() script. But, it's not perfect because the closed accordion height is still used when the dropover event is called, so the header works great for dropping the item, but the hidden list beneath it doesn't always register and the accordion closes. You'll have to return the draggable item and start again. You'll see what I mean when you mess around with the demo. Anyway, here is the basic setup:
CSS
 #droppable { width: 250px; height: 500px; padding: 0.5em; float: left; margin: 10px; background: #ddd; color:#000; }
 #draggable { width: 250px; height: 500px; padding: 0.5em; float: left; margin: 10px; background: #999; color:#000; }
 .fade { opacity: 0.3; }

 ul#droppable { list-style-type: none; }
 #droppable h5 { background: #08f; color: #fff; margin: 5px 0; padding: 3px; font-size: 14px; }
 #droppable .item, .item ul li { padding: 0 5px; background: #ccc; }

HTML

Header #1

Item #1.1

Item #1.2

Header #2

Item #2.1

Item #2.2

Script
$(document).ready(function(){

 // make accordion
 var item = $('#droppable li.item');
 // dropover event is for droppable
 item.bind('mouseover dropover', function(){
  item.removeClass('selected');
  $(this).addClass('selected').find('ul').slideDown(300);
  item.not('.selected').find('ul').slideUp(300);
 }).not('.selected').find('ul').hide();

 // set up droppable
 item.droppable({
  drop: function(e,ui) {
   ui.draggable.appendTo($(this).find('ul'));
   ui.helper.remove();
  }
 });

 // set up draggable
 $('#draggable li').draggable({
  helper : 'clone',
  revert : true,
  start: function(e,ui){
   $(this).addClass('fade');
   ui.helper.css('background','#ddd');
  },
  stop: function(e,ui){
   $(this).removeClass('fade');
   ui.helper.css('background','transparent');
  }
 });

});


Q:

Intermittent slow response & timeouts - Apache + mod_wsgi + Web2py

I've Ubuntu 14.04.5 LTS (i686) on a Digital Ocean droplet with 2x2.4GHzCPU & 4gb physical memory. I am running a web2py application on it with Apache and mod_wsgi. There are a few additional python modules installed on the box, like numpy and opencv2. The database is MySQL 5.5.
A Wordpress website on another server calls this web2py application using php-curl. Usually the response time is 2-5 seconds. But occasionally it timeouts (response time goes to >1000 seconds). I've added logging points in the Web2py application and they tell that after reaching the application, everything completes in 2-3 seconds. But in Apache2 access log, response time logged as a number higher than 1000 seconds. In the access log, the request time is approximately the same when request is initiated from the Wordpress website.
Can anyone point out how to find-out the reason of this intermittent slow response?
Thanks

A:

Finally I've been able to find out the cause of the problem. It was a  connection statement to a remote database in the default model file of the web2py application. This database connection was not being used in the application anywhere. But since it was in a model file, whenever a controller function is called the application tries to unnecessarily connect to that remote database.
Initially I added logging points everywhere in the application but didn't add in the default model file of the application; Therefore logs were silent about the root cause. Then I tested the application by just replacing the application folder contents one by one with the files of a demo application (which comes with web2py) and helped revealing the root cause of the problem. The root cause was then verified by adding the logging at the start and end of the default model files of the application.


Q:

Python Request Stream

I am trying to scrape a website that seems to dynamically downloads some data to the website. I want to scrape.
The website starts with:

    Text - "TEST_NAME

    Text - TEST_NAME_1

    Text - TEST_NAME_2

    Text - '-'

Then the website will load information in as:

        Text - "TEST_NAME

        Text - TEST_NAME_1

        Text - TEST_NAME_2

        Text - '999999.99'

I am trying to use Python request and stream to get the data after it loads, but I am not having much success.
import requests
from bs4 import BeautifulSoup

tarball_url = xxxxx
r = requests.get(tarball_url, stream=True)

soup = BeautifulSoup(r)

td = soup.findAll('td')

for line in td:
    print(str(line.get_text()))

This Returns:
TEST_NAME
TEST_NAME_1
TEST_NAME_2
 -

Is there a way I can scrape the data after the website updates the datacell? It is normally pretty fast within a few seconds.

A:

I found following link. This seems to work great for me.
http://koaning.github.io/html/scapingdynamicwebsites.html


Q:

Grails Per-User Database Authentication

First off, I know the best-practice is to use a single database user account in your web app to take advantage of connection pooling to keep the app nice and responsive. However, due to the REQUIREMENTS (as in no changing this under any circumstances), I must authenticate each user with his or her database account.
The context is a warehouse management application that runs on Android, but gets its data from web services that I'm probably going to write in Grails unless a suggestion here shows me a tech more suitable for my requirements. Due to the nature of the application, the users would likely only need to authenticate once or twice a day, so I was thinking I could simply persist the Connections in a HashMap keyed by the hash code of the username concatenated with the password. That should allow the application to maintain the same or similar performance level as the best practice.
Now, my issue is in using the persisted Connection objects. I know that I will not be able to use them with GORM without a significant amount of customization, so I was planning on using them with groovy.sql.Sql, which works out well because most of the business logic is in PL/SQL packages anyway.
My question is how does the groovy.sql.Sql class deal with its Connection object? Will I run into issues of Connections being closed by it, or can I safely use my HashMap to persist the Connections?

A:

groovy.sql.Sql will not close your connection. In the class spec you can find:

If this SQL object was created with a Connection then this method
  closes the connection.

So SQL class is really if you want to do things by yourself, not trusting entirely on Hibernate. Although, I think you can use Spring's UserCredentialsDataSourceAdapter for your solution.  It uses ThreadLocal to set credentials for each thread, so the call to: UserCredentialsDataSourceAdapter.setCredentialsForCurrentThread(String username, String password)
would solve. There are other aproaches you could try here.


Q:

Looking for a page designer

My site currently has some static pages. I'm looking for a rails wysiwyg webtool with which I can change those static pages (with images) dynamically. The number of pages is fixed and I don't have to be able to dynamically add new.
Update
The site already has a design template assigned which I don't need to change. I only need to be able to change the content of some of the pages.
Someone can suggest me something?
Thanks
Stijn

A:

Are you looking for a server site tool that facilitates editing static HTML files but uses a web browser interface?
If so I think that only solves part of the problem.  You pages still have, presumably, some common "furniture" like a Banner pane, Left pane, Right pane, Footer.  If you want to change these you will have to edit every file.  What about if you have telephone number in the Banner - if that changed it would be better to just change that centrally.
These are problems that a Content Management System addresses, so if you are not familiar with that you may want to read up on CMS.
To compare CMS systems see: http://cmsmatrix.org/matrix/cms-matrix?func=search
You can enter "Rails" or maybe "Ruby" in the Language field of the Search form


Q:

xpages design elements not shown

I;m using IBM Notes 9 - social edition and I saw that some design elements are missing: for example, paragraph and script editor.
Should I import them or they are just hidden?
Thanks for your time!

A:

You just need to change your IBM Domino Designer preferences to show them in the palette. In Domino Designer go to File - Preferences and then go to Domino Designer - XPages - Palette.

Paragraph is in the Other Controls palette category while Output script is in the Core Controls palette category.


Q:

std::vector and double* - How safe is this?

Is it safe to do this?
double darray[10];
vector<float> fvector;
fvector.insert(fvector.begin(), darray, darray + 10);  // double to float conversion

// now work with fvector

VS2008 gives me a warning about the double to float conversion. How do I get rid of this warning? I don't think it makes sense  to cast darray to float* as that would change the step size (stride) of the pointer.
Update: I know what the warning indicates. But unlike the "afloat = adouble;" scenario where I can easily apply a cast, I am unable to eliminate the warning in this case.
Edit: I've edited the code so that darray is no longer a function argument. Thanks to all those of you who pointed it out.

A:

Use std::transform() this allows you to provide a conversion method.
Then you just need a conversion method that does not generate a warning:
#include <vector>
#include <algorithm>
#include <iterator>

struct CastToFloat
{
    float operator()(double value) const { return static_cast<float>(value);}
};

int main()
{
    double  data[]  = { 1, 2,3,4,5,6,7,8,9,10};
    std::vector<float>  fl;

    std::transform(data, data+10,
                    std::back_inserter(fl),
                    CastToFloat());
}

A:

You get the warning because you are losing precision in the double to float conversion, that's all. Assuming that you really need fvector to be a vector<float> and not a vector<double>, it is clear that you can live with this precision loss, so the warning is not important.


Q:

Why do @synthesize variable names begin with an _?

I'm just starting to use Objective-C and I need to clarify something
When I @synthesize a @property, it is common convention to do the following:
@interface Class : ParentClass

@property propertyName

@end

@implementation

@synthesize propertyName = _propertyName;

@end

I've seen plenty of questions and answers suggesting that "_propertyName" is widely accepted as the "correct" way to synthesize properties.  However, does it serve ANY purpose? Or is it merely to increase readability and identify instance variables?

A:

From http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

You Can Customize Synthesized Instance Variable Names
As mentioned earlier, the default behavior for a writeable property is
  to use an instance variable called _propertyName.
If you wish to use a different name for the instance variable, you
  need to direct the compiler to synthesize the variable using the
  following syntax in your implementation:
@implementation YourClass @synthesize propertyName =
  instanceVariableName; ... @end

Also:

Note: The compiler will automatically synthesize an instance variable
  in all situations where it’s also synthesizing at least one accessor
  method. If you implement both a getter and a setter for a readwrite
  property, or a getter for a readonly property, the compiler will
  assume that you are taking control over the property implementation
  and won’t synthesize an instance variable automatically. If you still
  need an instance variable, you’ll need to request that one be
  synthesized: @synthesize property = _property;


Q:

How to use pyqt evaluate javascript

I am learning pyqt,use for parse webpage.
Now i want use pyqt evaluate javascript function just like this answer do:
spidermonkey evaluate js function which in remote js file

import urllib2
import spidermonkey
js = spidermonkey.Runtime()
js_ctx = js.new_context()
script = urllib2.urlopen('http://etherhack.co.uk/hashing/whirlpool/js/whirlpool.js').read()
    js_ctx.eval_script(script)
    js_ctx.eval_script('var s = "abc"')
    js_ctx.eval_script('print(HexWhirlpool(s))')

I want know how to achieve the same effect by using pyqt instead of spidermonkey.

A:

PyQt is a UI framework, so it might not be the best arrow in your quiver.
You can use WebView to load and display the web page. Since WebView uses WebKit, it will load and parse the HTML and all CSS and JavaScript in it. But that means you just get the final result - you don't have much control what is loaded and when.
Or you can use a tool like Beautiful Soup to parse the HTML. This gives you full control. You can then try to use spidermonkey to run the JavaScript but that will fail since many global variables like window or document will be missing. Also, there won't be a DOM.
For this, you'd need something like Envjs but there is no Python integration.
Maybe PhantomJS (a script driven Chrome/Chromium browser) is an option. See this question: Is there a way to use PhantomJS in Python?


Q:

Using calculation in Case Statement - Oracle SQL

Hi sql wizards and sorcerers,
I am trying to work out SLA days based on a particular parameter (case-type). For each case type, the SLA days are worked out slightly differently. My question is: do I use CASE STATEMENT to achieve this? I'll put down what I have so far, which isn't working:
fifthlevel --with statement declaring sla days
AS (SELECT

     CASE sla_days
     WHEN fourthlevel.case_type = 'Complaint'
     THEN sla_days =

      ( SELECT COUNT (*)
        FROM (SELECT business_date
              FROM ( SELECT TO_DATE ('01-01-2011', 'dd-mm-yyyy') + LEVEL - 1
                               business_date
                     FROM DUAL
                     CONNECT BY LEVEL <=
                                 TO_DATE ('31-12-2099', 'dd-mm-yyyy')
                               - TO_DATE ('01-01-2011', 'dd-mm-yyyy')
                               + 1) date_tab1
                     WHERE TO_CHAR (business_date, 'DY') NOT IN ('SAT', 'SUN')
                     AND business_date NOT IN (SELECT holiday_dt
                                               FROM cisadm.ci_cal_hol
                                               WHERE calendar_cd = 'WAW01'
                                              )
                   ) work_days1
             WHERE work_days1.business_date > fourthlevel.correspondence_date
             AND work_days1.business_date <= fourthlevel.close_date
             )
     WHEN fourthlevel.case_type = 'Enquiry'
     THEN sla_days = (SELECT COUNT (*)
                      FROM (SELECT business_date
                            FROM (SELECT TO_DATE ('01-01-2011',
                                                   'dd-mm-yyyy')
                                            + LEVEL
                                            - 1
                                               business_date
                                   FROM DUAL
                                   CONNECT BY LEVEL <=TO_DATE('31-12-2099',
                                                                'dd-mm-yyyy')
                                                      TO_DATE('01-01-2011',
                                                              'dd-mm-yyyy')+ 1
                                  ) date_tab1
                            WHERE TO_CHAR (business_date, 'DY')
                                  NOT IN ('SAT', 'SUN')
                             AND business_date
                                  NOT IN (SELECT holiday_dt
                                          FROM cisadm.ci_cal_hol
                                          WHERE calendar_cd = 'WAW01'
                                         )
                            ) work_days1
                      WHERE work_days1.business_date > fourthlevel.agreed_Date
                        AND work_days1.business_date <=
                               fourthlevel.close_date
                     )
     END
    FROM fourthlevel,

    fourthlevel.* --also wanting to select * from preceding WITH statement
    FROM fourthlevel)

Ok so that looks a bit messy but essentially I am trying to get two different calculations based on the case_types of 'Complaint' and 'Enquiry'.
Can anyone point me in the right direction?
Let me know if I can provide any further information.
Legends!

A:

Extract work_days1 subquery as a separate cte:
, work_days1 as (
SELECT business_date
       FROM (    SELECT TO_DATE ('01-01-2011', 'dd-mm-yyyy') + LEVEL - 1
                           business_date
                   FROM DUAL
             CONNECT BY LEVEL <=
                             TO_DATE ('31-12-2099', 'dd-mm-yyyy')
                           - TO_DATE ('01-01-2011', 'dd-mm-yyyy')
                           + 1) date_tab1
      WHERE     TO_CHAR (business_date, 'DY') NOT IN ('SAT', 'SUN')
            AND business_date NOT IN (SELECT holiday_dt
                                        FROM cisadm.ci_cal_hol
                                       WHERE calendar_cd = 'WAW01')),
fifthlevel --with statement declaring sla days
 AS (SELECT
 CASE
 WHEN fourthlevel.case_type = 'Complaint'
 THEN (SELECT COUNT(*) FROM work_days1 WHERE
 work_days1.business_date > fourthlevel.correspondence_date
    AND work_days1.business_date <= fourthlevel.close_date)
 WHEN fourthlevel.case_type = 'Enquiry'
 THEN sla_days = (SELECT COUNT (*) work_days1 WHERE
 work_days1.business_date > fourthlevel.agreed_Date
                    AND work_days1.business_date <=
                           fourthlevel.close_date) END as sla_days, *
      FROM fourthlevel)


Q:

What is the fastest way to compute the levels of each node of a directed graph?

Given a hierarchical graph represented by two lists of its respective nodes and links, what is the optimal solution to find all the nodes level?
The names of the following nodes are purely fictive, and will not be ordered.
Please note that the source node should be found easily, as it is the only one without parent.
If a special case occur (like multiple levels), only the biggest one should be returned.
Illustration :

Input:
g = Graph()
g.addNodes([0, 1, 2, 3, 4, 5, 6, 7])
g.addLink(0, 1)
g.addLink(0, 2)
g.addLink(1, 3)
g.addLink(1, 4)
g.addLink(1, 5)
g.addLink(2, 6)
g.addLink(6, 7)
getLevels(g.nodes, g.links)

Output:
#Node : Level
0 : 0
1 : 1
2 : 1
3 : 2
4 : 2
5 : 2
6 : 2
7 : 3

A:

From the way you're talking about it, it sounds like you want a tree more so than a graph. Otherwise you're not really coding up a "levels" algorithm but a "distance from node" algorithm. Trees can have levels, you're asking for the farthest distance between two nodes on a graph.
If you're down to code it yourself, you can basically do a breadth first search type algorithm, where you take your source node (in this case 0) figure out what's linked to it. If you're returning a map set the keys equal to those nodes and the values to 1. Then find the next links to those, excluding prior nodes, iterate over those and save the values to the map except with a value of 2 now. Loop til you have no more children. If you do this with a tree you get to remove the check to exclude prior nodes.


Q:

How is audio encrypted?

I was wondering how is audio encrypted. I know about other data files but dont have any idea about audio files. Any help is appreciated.

A:

For educational reasons, I suggest you look at how IPSec's Encapsulating Security Payload is constructed.  There is an IV (for whatever mode of encryption is employed), ciphertext, an authentication tag, and a counter.  For each packet the sender increments the counter so if all is well on the network then packets will arrive with sequential count values.
The receiver remembers the keys to enable authentication and decryption but also remembers two other important datums: a base count and a bit mask.  The base count is the oldest count that will be accepted.  The bit mask indicate if the count at baseCount + bitPosition have been received.  The receiver can accept packets out-of-order (up to the size of the bitmask) without being exposed to replay attacks.
Your question has gone unanswered for a while in part because it is unclear.  Most of encrypting realtime data is still just traditional cryptography.  There are engineering tricks to improve performance and handle things like dropped or out-of-order packets, but that is arguably a different topic than cryptography (e.g. network engineering).


Q:

Counting results of rows in SQL Server

I need your help, i have this SQL :
SELECT
    (SELECT
         COUNT(b.IDPerfilPortal)
     FROM
         UseCRM.dbo.Produtos b
     WHERE
         a.IDProduto = b.ID AND b.IDPerfilPortal = 1) AS Completo,
    (SELECT
         COUNT(b.IDPerfilPortal)
     FROM
         UseCRM.dbo.Produtos b
     WHERE
         a.IDProduto = b.ID AND b.IDPerfilPortal >= 2) AS Segmentado
FROM
    UseCRM.dbo.Contratos a
WHERE
    (a.DataHoraCancelamento IS NULL)
    AND (GETDATE() BETWEEN a.DataInicio AND a.DataTermino)

And I'm getting this :
Completo  Segmentado
--------------------
    1         0
    0         1
    1         0
    1         0
    1         0

I need to count the number of Products in Completo and Segmentado. Like this:
Completo  Segmentado
--------------------
  100         55

I need only one row. How can I do it?

A:

Instead of doing count twice for the different items, you can do sum with case like this:
SELECT
    sum(case when b.IDPerfilPortal = 1 then 1 else 0 end) AS Completo,
    sum(case when b.IDPerfilPortal >= 2 then 1 else 0 end) AS Segmentado
FROM
    UseCRM.dbo.Contratos a
    join UseCRM.dbo.Produtos b on a.IDProduto = b.ID
WHERE
    (a.DataHoraCancelamento IS NULL)
    AND (GETDATE() BETWEEN a.DataInicio AND a.DataTermino)


Q:

Change direction of axis marks in a barplot

I need the following barplot with special axis marks. I tried for while but have difficulties getting it to work. Especially my axis-labels need to change their direction. I know that I have to use axTicks, axis and barplot commands. Anyone with an idea?
How it should look like:

Here is my data:
bpsamplevalues<-structure(c(21.3389252731795, 18.9930828477016, 19.4378755546201,
22.1009743407998, 23.8099463895258, 18.9706355343085, 19.4619810121121,
19.3433394825869, 26.8760997862876, 19.0948710373689), .Names = c("Div 1",
"Div 2", "Div 3", "Div 4", "Div 5", "Div 6", "Div 7", "Div 8",
"Div 9", "Div 10"))

I started with this code but I can not find a solution to get further:
barplot(bpsamplevalues, col="#87DEE1", axes=F, names.arg=F)

A:

You may try this. It is the las argument which sets the orientation of axes labels. See ?par for more information.
barplot(bpsamplevalues, col = "#87DEE1", axes = FALSE, las = 2)
axis(side = 2, tick = FALSE, las = 1)
grid(nx = NA, ny = NULL, col = "white", lty = "solid")


Q:

Invalid Error when Retrieving JSON API with jQuery

I am passing a variable into a URL, which then calls an API filtered by the variable passed. However, I can't seem to get the JSON to load, and returns an Invalid Error in Console of Firebug in JS. Thoughts?
$("a").click(function() {
    var apiurl = "http://api.example.com" + $(this).text() + "&limit=500" + "?callback=?";

    $.ajax({
        url: apiurl,
        success: function(json) {alert(json.data.results);},
        error: function() { alert("error"); },
        dataType: "json",
        contentType: "application/json;charset=utf-8",
    });
});

This is the error:
invalid label
error source line:
[Break On This Error]
{"code":200,"status":"Ok","data":{"offset":0,"limit":500,"total":17,"target":"ch...

A:

Remove: contentType: "application/json;charset=utf-8" from your request. Also you could use the $.getJSON() method which is a shorthand for what you have written. And don't forget to return false from your click handler otherwise your call might never have time to execute before the browser redirects away following the href of the anchor that's being clicked. Another thin go to notice is that you should use '&callback=?' instead of '?callback=?' in the url because apparently you already have the limit query string parameter so you are just adding another one. I suppose in this case that $(this).text() contains somewhere the ? which indicates the start of the query string:
$('a').click(function() {
    var apiurl = 'http://api.example.com' + $(this).text() + '&limit=500' + '&callback=?';
    $.getJSON(apiurl, function(json) {
        alert(json.data.results);
    });
    return false;
});

Also I hope you realize that callback=? means JSONP that the API that you are trying to invoke must support. Otherwise your call will always be failing because you are violating the same origin policy restriction.


Q:

How to mutate() a list of columns using map2() in dplyr

I recently had to compile a data frame of student scores (one row per student, id column and several integer-valued columns, one per score component). I had to combine a "master" data frame and several "correction" data frames (containing mostly NA and some updates to the master), so that the result contains the maximum values from the master, and all corrections.
I succeeded by copy-pasting a sequence of mutate() calls, which works (see example below), but is not elegant in my opinion. What I would have wanted to do, was instead of copying and pasting, to use something along the lines of map2 and two lists of columns to compare the columns pair-wise. Something like (which obviously does not work as such):
list_of_cols1 <- list(col1.x, col2.x, col3.x)
list_of_cols2 <- list(col1.y, col2.y, col3.y
map2(list_of_cols1, list_of_cols2, ~ column = pmax(.x, .y, na.rm=T))

I can't seem to be able to figure out to do it. My question is: how to specify such lists of columns and mutate them in one map2() call in dplyr pipe, or is it even possible – have I gotten it all wrong?

Minimum working example
library(tidyverse)

master <- tibble(
  id=c(1,2,3),
  col1=c(1,1,1),
  col2=c(2,2,2),
  col3=c(3,3,3)
)
correction1 <- tibble(
  id=seq(1,3),
  col1=c(NA, NA, 2 ),
  col2=c( 1, NA, 3 ),
  col3=c(NA, NA, NA)
)

result <- reduce(
  # Ultimately there would several correction data frames
  list(master, correction1),
  function(x,y) {
    x <- x %>%
      left_join(
        y,
        by = c("id")
      ) %>%
      # Wish I knew how to do this mutate call with map2
      mutate(
        col1 = pmax(col1.x, col1.y, na.rm=T),
        col2 = pmax(col2.x, col2.y, na.rm=T),
        col3 = pmax(col3.x, col3.y, na.rm=T)
      ) %>%
      select(id, col1:col3)
  }
)

The result is
> result
# A tibble: 3 x 4
     id  col1  col2  col3
  <int> <dbl> <dbl> <dbl>
1     1     1     2     3
2     2     1     2     3
3     3     2     3     3

A:

Rather than do a left_join, just bind the rows then summarize. For example
result <- reduce(
  list(master, master),
  function(x,y) {
    bind_rows(x, y) %>%
      group_by(id) %>%
      summarize_all(max, na.rm=T)
  }
)
result
#     id  col1  col2  col3
#   <dbl> <dbl> <dbl> <dbl>
# 1     1     1     2     3
# 2     2     1     2     3
# 3     3     2     3     3

Actually, you don't even need reduce as bind_rows can take a list
Adding another table
correction2 <- tibble(id=2,col1=NA,col2=8,col3=NA)
bind_rows(master, correction1, correction2) %>%
  group_by(id) %>%
  summarize_all(max, na.rm=T)


Q:

Adding a seperate class to list items parent using jquery?

I have a list with different levels of depth:

Item 1

Item 2

Sub item 1

Sub item 2

Sub item 3

Subsub item 1

Subsub item 2

Sub item 4

Item 3

I am using the following jquery script to add a class to the parents:
$("ul li ul").parent().addClass("menuparent");

Is there a way to add this class only to the top level parent li's and a different class for all other (deeper) parent li's?

A:

For top level lis
$("#top-level > li").addClass("menuparent");

and for lower level li
$("#top-level li li").addClass("someotherclass");


Q:

Rails View Undefined Method

A little background for my app. I have users that have 1 quiz and a quiz that belongs to a user. I am trying to list the quizzes that the users have taken but I get an error.
NoMethodError in Users#index
Showing /Users/Daniel/Documents/cis196/CollegeConnection/app/views/users/index.html.erb where line #24 raised:
undefined method `userName' for nil:NilClass
Extracted source (around line #24):
<% @user.each do |u| %>

<%= u.quiz.userName%>

<%= u.quiz.q1 %>

    <% for q in u.quiz.q2 %>
      <% if q != nil %>

Rails.root: /Users/Daniel/Documents/cis196/CollegeConnection
Application Trace | Framework Trace | Full Trace
app/views/users/index.html.erb:24:in block in _app_views_users_index_html_erb__3921348574137420689_70261694365660'
app/views/users/index.html.erb:22:in_app_views_users_index_html_erb__3921348574137420689_70261694365660'
app/controllers/users_controller.rb:25:in `index'
Here's some relavent code.
class User < ActiveRecord::Base

has_one :quiz, :class_name => 'Quiz'

attr_accessible :name, :email, :password, :password_confirmation, :position, :remember_me
validates :name, :presence => true
validates_length_of :name, :maximum=>30
validates :name, :format => { :with => /\A[a-zA-Z]+\z/,
:message => "Only letters allowed" }
validates_presence_of :position
validates :email, :presence => true
validates :email, :uniqueness => true

scope :college,    where(position: 'College')
scope :highschool, where(position: 'High School')

end

class Quiz < ActiveRecord::Base
belongs_to :user

validates :q1, :presence => true
validates :q2, :presence => true
validates :q3, :presence => true
serialize :q2
has_many :activities

 end

def create
@quiz = current_user.quizzes.build(params[:quiz])
# @quiz = Quiz.new(params[:quiz])
@quiz.userName=current_user.name
@activities = Activity.all

respond_to do |format|
  if @quiz.save
    format.html { redirect_to @quiz, notice: 'Thank You for Taking the Quiz!.' }
    format.json { render json: @quiz, status: :created, location: @quiz }
  else
    format.html { render action: "new" }
    format.json { render json: @quiz.errors, status: :unprocessable_entity }
  end
end
end

<% @user.each do |u| %>

<%= u.quiz.userName%>

<%= u.quiz.q1 %>

  <% for q in u.quiz.q2 %>
  <% if q != nil %>

<%= q  %>

  <% end %>
<% end %>

<%= u.quiz.q3 %>

X

<% end %>

This is the view with the error. Any help would be great!

A:

You're calling the instance variable @user from your view but you don't instatiate it anywhere in your controller, therefore it's nil (doesn't exist).
In the controller that calls the view file, you have to instatiate the variable like this:
# assuming you've already did something like
# @quiz = Quiz.find(params[:id]
# in order to retrieve the quiz
@user = @quiz.user

This should make @user available in the view. For more info refer to the ActiveRecord Associations guide: http://guides.rubyonrails.org/association_basics.html


Q:

ONDELETE object event in javascript

I have a modal object that creates DOM elements when its created.
I would like to know if its possible to remove the nodes whenever user calls 'delete' on the object. Something like:
var modal = function (options) {
    var domHolder = null;

    function build() {
        domHolder = document.createElement("div");
        //construct a modal window inside the element...
    };

    this.ondelete = function() {
        domHolder.parentNode.removeChild(domHolder);
    }

    build();
};

//destruct the object and remove the nodes
var myModal = new modal();
delete myModal;

A:

delete doesn't trigger the onDeleteEvent , delete is an operator;

The delete operator removes a property from an object.

You shoud call the ondelete method to remove the element from DOM.
var myModal = new modal();
myModal.ondelete() ;

JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the Garbage Collectior decides to run and the object is eligible for that.
The delete operator has nothing to do with directly freeing memory (it only does indirectly via breaking references). See the memory management page for more details).


Q:

PUT to update resource with partial data?

Let's say that we already have a Book resource at /books/123. This Book has several properties, like: isbn, year, title.
PUT method is used to update whole resource. So if we want to update just the title we need to pass everything else, too.
PATCH can be used to update only some properties of the resource.
What should happens if we do PUT with partial data? For example, PUT with only title and isbn?
As I see, this should replace existing resource and no error should be signalized back. Right?

A:

If you are asking, should, then I would agree with you. It should replace the existing resource and no error would be signaled back. Of course, if the data is incomplete, e.g. you did PUT with only the title, and isbn is required, then you might get a 400 error back, whereas PATCH would be just fine with that.
However, many many (most? never surveyed) REST APIs do not follow it. About the only thing that I commonly see well-followed is that GET /resource is the list and GET /resource/:resource is a single resource. Many such APIs use POST for update, when POST is intended for create, etc.
So, if you are asking:

Do APIs currently in place have PUT be strictly replace, the answer is no.
If you are designing a new API, I would recommend sticking to what you outlined.


Q:

Expressions in SQL Views

I'm new to SQL Views so be gentle!
I have the following SQL view:
SELECT        dbo.product.name AS [Product Name],
              ROUND(CASE [vat] WHEN 1 THEN [packcost] * 1.2 ELSE [packcost] END, 2) AS [Pack Cost],
              ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2) AS [Unit Cost],
              dbo.purchase.unitsaleprice * dbo.product.units AS [ Pack Sale Price], dbo.purchase.unitsaleprice AS [Unit Sale Price],
              dbo.product.units * (dbo.purchase.unitsaleprice - ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2)) AS [Pack Profit],
              dbo.purchase.unitsaleprice - ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2) AS [Unit Profit]
           FROM dbo.product INNER JOIN
              dbo.purchase ON dbo.product.id = dbo.purchase.productID

But it seems inefficient as I am rewriting a lot of this.
For example I would like to define the [Pack Cost] column:
ROUND(CASE [vat] WHEN 1 THEN [packcost] * 1.2 ELSE [packcost] END, 2) AS [Pack Cost]

to be used elswhere instead of rewriting it.
e.g so I could use:
[Pack Cost] / [Units]

To define unit cost instead of:
ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2) AS [Unit Cost]

Not sure if I'm getting the right end of the stick though, or whether it is appropriate to do this.

A:

Create a new User-Defined Scalar-valued Function as follows:
CREATE FUNCTION [dbo].[GetPackCost]
(
    @vat int
    ,@packcost decimal
)
RETURNS decimal
AS
BEGIN
    DECLARE @packcost_calculated decimal

    SELECT @packcost_calculated = ROUND(CASE @vat WHEN 1 THEN @packcost * 1.2 ELSE @packcost END, 2)

    RETURN @packcost_calculated

END

GO

In your query, you would select is as follows:
SELECT        dbo.product.name AS [Product Name],
              dbo.GetPackCost([vat],[packcost]) AS [Pack Cost],
              dbo.GetPackCost([vat],[packcost]) / [units] AS [Unit Cost],
              dbo.purchase.unitsaleprice * dbo.product.units AS [ Pack Sale Price], dbo.purchase.unitsaleprice AS [Unit Sale Price],
              dbo.product.units * (dbo.purchase.unitsaleprice - ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2)) AS [Pack Profit],
              dbo.purchase.unitsaleprice - ROUND(CASE [vat] WHEN 1 THEN ([packcost] * 1.2) / [units] ELSE [packcost] / [units] END, 2) AS [Unit Profit]
           FROM dbo.product INNER JOIN
              dbo.purchase ON dbo.product.id = dbo.purchase.productID


Q:

Calculating Total Overtime MySQL

I am creating a timeclock system and management website. I am trying to pull the amount of overtime for a particular department with a MySQL query.
The timeclocks update a MySQL table called events, which stores the employee_id, the job they are working on, the time_in and the time_out. I can produce a table of the total hours worked from each employee_id with:
SELECT employee_id,
       SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))) AS hours
  FROM events
 GROUP BY employee_id;

This will return a table of employee_ids and the total hours they worked. To create a table of employee_ids overtime I use:
SELECT employee_id,
       IF(HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))>40,
          HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))-40,
          0) AS overtime
  FROM events
  GROUP BY employee_id;

This returns a table of employee_ids and the amount of overtime they have worked.
The trouble I am having starts when I want to find a total of the overtime worked for all employees. I assumed I would be able to just put the IF function to find overtime inside of SUM() however when i run the following statement:
SELECT SUM(IF(HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))>40,
              HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))-40,
              0)) AS overtime
 FROM events;

I get this error back:
ERROR 1111 (HY000): Invalid use of group function

I have looked all over for this but have found little in way of SUM(IF(SUM())) functions.
Note: The overtime has to be calculated individually, I cant just take total hours worked / number of employees - 40. If one worker works 30 hours in a week, and another works 50, there are 10 hours of overtime, but the average says there isn't any.

A:

How about this?
SELECT SUM(overtime)
  FROM
  (
    SELECT employee_id,
           IF(HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))>40,
              HOUR(SEC_TO_TIME(SUM(TIMEDIFF(time_out,time_in))))-40,
              0) AS overtime
      FROM events
     GROUP BY employee_id
  )TOTAL

When you're using SQL to implement complex business logic, nested queries have a key advantage: they let you test each level of the logic and build it up in a reliable way.


Q:

How to create Event-source server using Spring boot?

How to create event-source server using spring boot application?
From the below link, I don't see Java-spring boot example.
Any reference would help.
http://www.html5rocks.com/en/tutorials/eventsource/basics/

A:

This is a simple implementation with Spring 4.2. Don't take into account the Thread, it's there only for demo purposes:
@RestController
public class AccountsRestController {

    @RequestMapping("/accounts/alerts")
    public SseEmitter getAccountAlertsNoPathVariable(HttpSession session) {

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        Thread t1 = new Thread(() ->{
            try {
                int i = 0;
                // Send 10000 messages
                while(++i<=10000){
                    Thread.sleep(1000);
                    System.out.println("Sending");
                    try{
                        emitter.send(new Alert((long)i, "Alert message"+i));
                    }catch(ClientAbortException cae){
                        //The client is not there anymore, we get out of the loop
                        i = 10000;
                    }
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();

        return emitter;
    }


Q:

How can i pass props through methods inside components?

i have a react component named "List" that renders smaller components "Post" using a button through  method "Addpost()" that takes 2 props from the input form. I have saved the input in 2 varables but i don't know how to pass these props to the Addpost() method inside the return of List's render().
//=========== List component ==============
class List extends React.Component{

renderPost(title,content){
    return(
        <Post titolo={title} contenuto={content}/>
    );
}

renderPost just render the Post component in a  in the HTML
 addPost(title,content){
     title = document.getElementById("inputTitle").value;
     content = document.getElementById("inputContent").value;
    console.log(title, content)
    this.renderPost(title,content);
}

addPost should take the input value and use renderPost to render the Post component with that title and content
    render(){
        return(

          {this.renderPost("testTitle","testContent")}

       <form>
             Title:

             <input type="text" id="inputTitle"/>

             Content:

             <input type="text" id="inputContent"/>
       </form>

       <button className="square"

how can i make this work? title and content are not defined
 onClick={() =>
               this.addPost(title,content)
               Add Post!
       </button>

        );
    }
}

//=========== Post component ==============
class Post extends React.Component {

  render() {
    return (

      `enter code here`

        {this.props.titolo}

      {this.props.contenuto}

    );
  }
}

A:

Basically, whenever you're dealing with forms and inputs, you would use refs.
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import PostList from './components/PostList'
import AddPostForm from './components/AddPostForm'

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      posts: [] //state is handled here
    }

    this.addPost = this.addPost.bind(this)
  }

  addPost(title, content) {
    let newPost = { title, content }
      this.setState(({ posts }) => { return { posts: [...posts, newPost] } } )
  }

  render() {

    const { posts } = this.state

    return (

        <AddPostForm onNewPost={this.addPost} /> //we pass addPost to the component

        <PostList posts={posts} />

    );
  }
}

export default App;

Post.js
import React from 'react';

function Post({titolo, contenuto}) {
    return (

      `enter code here`

        {titolo}

      {contenuto}

    );
}

export default Post

AddPostForm.js
import React from 'react';

const addPostForm = ({onNewPost = f => f}) => { //onNewPost method is passed by props from the parent
    let _titleInput, _contentInput //these are our refs, see the docs for more information

    const submit = (e) => {
        e.preventDefault()
        onNewPost(_titleInput.value, _contentInput.value) //here we call the addPost function that was passed to the component
        _titleInput.value = '' //empty the inputs
        _contentInput.value = ''
        _titleInput.focus() //set focus
    }

    return (
        <form onSubmit={submit}>
            Title:

             <input type="text" ref={title => _titleInput = title} />

{/* Note the ref attribute */}
             Content:

             <input type="text" ref={content => _contentInput = content} />
             <button className="square">Add a new post</button>
        </form>
        )
}

export default addPostForm

PostList.js
import React from 'react';
import Post from './Post';

const PostList = ({ posts=[] }) => {
    return (

            {
                posts.map((post, index) =>
                    <Post key={index} titolo={post.title} contenuto={post.content} />
                )
            }

    )
}

export default PostList

And the result:


Q:

How to set up autoscaling for ECS cluster that uses scheduled tasks and no service?

I have an ECS cluster which i have an ec2 instance tied to and a scheduled task set to run daily using the 'Scheduled Tasks' functionality on the ECS dashboard.
This task runs a a bunch of containers that are each relatively expensive in memory, and this is compounded even more so with all the containers running at once.
I do not currently have a service set up for the ECS cluster and it is my understanding that for my goals, running a set task on some interval, a service would not be used.
AWS's definition of a service in there ECS docs says:
An Amazon ECS service enables you to run and maintain a specified number of instances of a task definition simultaneously in an Amazon ECS cluster.

Since this is not what I want; instead i need to just run a task on some scheduled interval i gather i do not need an service tied to my ECS cluster.
My question is on how to set up autoscaling for my scheduled tasks? The only references i can find to auto scaling within an ECS cluster are to do with creating ecs services that auto scale - which again, is not what I want (at least from how i understand ecs services to work).
What I need is for my ec2 instances to auto scale with my scheduled task running, allocating more resources as need for the task to run. Would I just need to set up auto scaling on the specific ec2 instance the ecs cluster is tied to from within the ec2 dashboard or is there some other way to do this from ECS directly?

A:

I want; instead, I need to just run a task on some scheduled interval I gather I do not need a service tied to my ECS cluster.

For the above use case better to use fargate and you will not maintain or worry about auto-scaling scheduling, all you need to setup schedule task and AWS will take care of memory and other resources required for your task plus you will only pay for the resources that were used by you ECS task, unlike EC2 type task where you pay for the container instance.

AWS Fargate is a serverless compute engine for containers that works with both Amazon Elastic Container Service (ECS) and Amazon Elastic Kubernetes Service (EKS). Fargate makes it easy for you to focus on building your applications. Fargate removes the need to provision and manage servers, lets you specify and pay for resources per application, and improves security through application isolation by design.

aws fargate
Create a cloud watch rule base on some schedule that will trigger the task, make sure that the container exit once it completes the job, fargate will automatically stop the container.

cloudwatch-event-rule-to-invoke-an-ecs-task


Q:

Python: Open Excel file with win32

My code was working yesterday but today when I tried running it again it threw me an error and I've try to figure this out but I couldn't. Hope you can help me out here. Thanks much!
import fnmatch
import os
import scipy as s
import pandas as pd
import win32com.client as win32

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.xlsx'):
    print(file)
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(file)
    excel.Visible = False
    excel.DisplayAlerts = False
    wb.DoNotPromptForConvert = True
    wb.CheckCompatibility = False

    ws = wb.Worksheets('Exec Summary')
    ws.Activate
    canvas = ws.Shapes

    for shp in canvas:
        if shp.TextFrame.Characters:
            print("Comments Found")
            print(shp.TextFrame2.TextRange)
            break
            wb.Close(True)

And this is the error the system threw:
---> 11         wb = excel.Workbooks.Open(file)
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find ZPC.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)
I have checked and confirm that the file is already in the directory. Have you guys encountered this before?

A:

Can you try doing a print of your file and see what comes up?
What is likely happening here is that you are not indicating the directory path correctly in os.listdir('.').
os.listdir('.') will check the default directory in which the python script you are running is located in.
If it is the same folder, it will work.
But if it is not, you have to specifically include the exact path of the folder. Example of how your exact filepath should look like:
filepath = r'C:\Users\yournamehere\Desktop\yourfolderhere\\' + 'ZPC.xlsx'

Example of how your os.listdir should look like:
dirpath = r'C:\Users\yournamehere\Desktop\yourfolderhere\\'
for file in os.listdir(dirpath):
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(dirpath + file)

Also, if you wish to have a more elegant way of joining dirpath and file
You can use
os.path.join(dirpath, file)


Q:

What is the most semantically-correct HTML element for a form field hint/note?

The label and the field are easy; we have  and then the relevant input field. But what is the most semantically-correct HTML element to use for the smaller informational text that goes under the field?

A:

I don't know of a specific element or attribute to connect them, but you can do so using the ARIA attribute aria-describedby:
First Name
<input type="text" id="firstname" aria-describedby="firstname-explanation" />

e.g. John

But including everything in the label seems good to me either (also gives good styling abilities, as you have a  - semantic - container):

    First Name
    <input type="text" id="firstname" />
    e.g. John

Or you could even mix the two.
Another approach could be to put the description in the title (or placeholder as suggested by @Alohci) attribute of the input element (semantically this is the one describing it), but in this case you have to insert it to the markup through Javascript (or CSS using input:after { content : "e.g. " attr(placeholder) } - suggested by @Alohci).


Q:

if -else in shell script, matching argument with string

For the following shell script -
#!/bin/sh
main_version=0
feature_version=0
patch_version=0
if [[ $1 -eq "m" ]]; then
    main_version=$((main_version+1))
fi

if [[ $1 -eq "f" ]]; then
    feature_version=$((feature_version+1))
fi

if [[ $1 -eq "p" ]]; then
    patch_version=$((patch_version+1))
fi

echo $main_version
echo $feature_version
echo $patch_version

It is incrementing all the variables even though i pass m as argument using ./<script-name>.sh m
What is the reason for that?

A:

-eq uses arithmetic comparison. Sh arithmetic operations treat non-numeric operands as 0, so you're just checking [[ 0 -eq 0 ]] in all three cases.
For string comparison you want [ "x" = "y" ] instead. (That's the POSIX shell syntax.)
The Bash syntax is [[ x == y ]] with double =, but it is not a good idea to use bashisms/kshisms when your script header declares /bin/sh. Either change the header to require Bash, or stick to only POSIX shell syntax.


Q:

Why is responseText outputting?

CodeIgniter 3.0
Form uses button as the submit event:
<button type="button" name="submit">SEARCH</button>
Here is the very simple javascript I have so far, and I don't see why it should be outputting the form page in an alert box:
$( document ).ready(function() {
    $("button[name='submit']").click(function(){
        //
    });
});

Produces an alert box with readystate, statustext, and responsetext:
200 , OK, <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
(...and the entire html output of the form page goes here...)
</body>
</html>

I don't understand why my js should output anything if I haven't told it to.

A:

As it turns out, I was calling another javascript in my head, which had an identical $(document).ready(function script section. Even the <button name='submit'] was the same, so my javascript much have got confused and just threw up the status codes and responsetext.


Q:

Ruby/Rails/AJAX/JQuery - On link click, passing a parameter and performing a controller action

I'm trying to use clicking a link to perform and action in my controller called 'yes' but do so client side rather than having to refresh everytime a user clicks.
Before I had an link_to that routed to a action called "yes" and passed the id of a model I have called 'event'
      <%= link_to "yes", yes_path(event)%>   (in view)

      match 'user/:id/yes' => 'user#yes', :as => "yes"   {in routes.rb)

The problem issue is that every time the user clicks the link the page refreshes while it performs the yes action, so it will flow alot smoother if I can tell the backend to perform the actions client side.
S0  I found a reference here :   execute controller/action from javascript in rails3
and took a look at the documentation :  http://api.jquery.com/jQuery.ajax/
And came up with this.  Where if the post is successful at the previous route from above change a css class for the link (change color).
 $.ajax({
       type: "POST",
       url: "/user/" + $(this).attr('event') + "/yes/",
       success: function(){
           $(".like").click(function() {
           if ($(this).hasClass("selected")) {
           $(this).addClass("selected");
           return false;  }
    });

I also added this is the bottom of the controller that the desired javascript is being used.
respond_to do |format|
     format.html { }
     format.js
end

So now my link_to looks like this
 <%= link_to "yes", yes_path(event), :class => "like", :remote => true %>

But the page is still refreshing and It doesnt look like its calling the AJAX at all.

am I passing the parameter "event" properly as a jquery attribute?
am I calling the link_to properly?
This is my first time so I have no idea what I'm doing wrong, possibly a few things?

I'd really appreciate any help

A:

Is this what you're after?
$(".like").click(function(evt) {
    evt.preventDefault();

    var $self = $(this);
    $.post($self.attr("href"), function(response) {
        $self.addClass("selected");
    });
});

The first line binds the JavaScript to all elements with a class of like. preventDefault is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). $.post() is shorthand for $.ajax({ type: "POST" }).
Whatever you want to happen after a successful post to the server goes that finally function call. The first argument is the response from the server.
Rich


Q:

How Do I Type with IPA (International Phonetic Alphabet)?

How Do I Type with IPA (International Phonetic Alphabet)? I need to type in Phonetics, but I cannot find a keyboard. I tried the IPA Unicode 6.2 keyboard, but it did not work. It installed, but when I selected it, I could only type the normal english-latin characters. I cannot use copy/paste sites like This, as I need to type a lot.
I am using a MacBook Pro, With Sierra

A:

If the standard IPA layout doesn't work for you, I would suggest making a custom keyboard layout with Ukelele (or if you prefer text-based editing, KeyLayoutMaker).
Alternatively, if you don't need quite the level of speed that can offer, you can simply use the Character Palette (Edit > Emoji and Symbols) to type the characters by double-clicking them. To get the "Phonetic Alphabet" pane to show up, customize which are visible with the gear icon in the top left.


Q:

Mostrar SplashScreen mientras se carga la aplicación en Android

Tengo implementado una splashcreen mediante una activity que se infla de su layout con una imagen centrada, pero lo que me encuentro que si es la primera vez que se instala la app, durante la carga/compilación se muestra una pantalla en blanco, más o menos 6 segundos, la segunda vez que inicias la app inicia directamente con la SplashScreen.
Graficamente así
La Primera vez que se ejecuta la app despues de instalación o borrar datos del menú configuración
(click abrir app).........................(splashscreen)------(listo)
La segunda vez que se abre la app
(click abrir app)(splashscreen)------(listo)
Mi pregunta si hay alguna forma de poner una splashcreen durante ese periodo de pre-carga de Android.
Manifest.xml
<activity
    android:name=".SplashActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:theme="@style/AppTheme.SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Estilo AppTheme.SplashTheme del Tema que hereda la activity
<style name="AppTheme.SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
</style>

Layout XML splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorSplashScreen">

    <LinearLayout
        android:id="@+id/splashscreen"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:contentDescription="@string/about.alt_logo"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:layout_gravity="center"/>

        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:layout_marginTop="8dp" />

    </LinearLayout>

</LinearLayout>

SplashActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;

/*
config_longAnimTime   = 400
config_mediumAnimTime = 300
config_shortAnimTime  = 150
*/
public class SplashActivity extends AppCompatActivity {

    private String TAG = "SplashActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final int SPLASH_DISPLAY_LENGTH = 1200;
        final int SPLASH_DISPLAY_OFFSET = getResources().getInteger(android.R.integer.config_shortAnimTime);;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        Log.d(TAG, "onCreate() called with: " + "savedInstanceState = [" + savedInstanceState + "]");
        final Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                final LinearLayout img = (LinearLayout) SplashActivity.this.findViewById(R.id.splashscreen);

                Animation fadeOut = new AlphaAnimation(1, 0);
                fadeOut.setInterpolator(new AccelerateInterpolator());
                fadeOut.setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));

                fadeOut.setAnimationListener(new Animation.AnimationListener()
                {
                    public void onAnimationEnd(Animation animation)
                    {
                        img.setVisibility(View.GONE);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //Create an intent that will start the main activity.
                                Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
                                SplashActivity.this.startActivity(mainIntent);

                                //Apply splash exit (fade out) and main entry (fade in) animation transitions.
                                overridePendingTransition(R.anim.zoom_enter, android.R.anim.fade_out);

                                //Finish splash activity so user cant go back to it.
                                SplashActivity.this.finish();

                            }
                        }, SPLASH_DISPLAY_OFFSET);

                    }
                    public void onAnimationRepeat(Animation animation) {}
                    public void onAnimationStart(Animation animation) {}
                });

                img.startAnimation(fadeOut);

                Log.d(TAG, "finish SplashScreen: " + SPLASH_DISPLAY_LENGTH);

            }
        }, SPLASH_DISPLAY_LENGTH);

    }

}

Actualización:
Se muestra la pantalla blanca porque hereda del tema light, porque si añado el estilo del tema, se muestra negra la pantalla.
    <item name="android:background">#FF000000</item>
    <item name="android:colorBackground">#FF000000</item>

Creo que la solución recae en implementar dibujar el icono mediante la carga del tema antes de usar un layout xml,  abrir app ---> se aplica tema ----> carga layout en la interfaz.

A:

Cuando deseas que al iniciar la pantalla de inicio de la aplicación  (SplashScreen) no muestre ese molesto fondo blanco, se pude solucionar fácilmente creando un tema el cual relacionarias a la actividad:
 <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/fondo_splash</item>
   </style>

En realidad la propiedad que define el fondo al iniciar la actividad es android:windowBackground y puedes agregar una imagen (@drawable/ )
    <item name="android:windowBackground">@drawable/fondo_splash</item>

o un color (@color/):
    <item name="android:windowBackground">@color/fondo_splash</item>

Dentro de nuestro AndroidManifest.xml podemos definir el tema en el nivel de la aplicación :
  <application
        android:theme="@style/SplashTheme">

o de alguna actividad especifica:
<activity android:name=".SplashScreenActivity"
   android:theme="@style/SplashTheme" >

con esto siempre aseguramos cargar un fondo (drawable o color), antes de cargar una imagen o iniciar completamente la aplicación.

A:

Update
Leyendo ese post Un splashscreen eficiente (en)
Añado lo opaque
Definir el fondo del splashscreen en un drawable background_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item android:drawable="@color/colorSplashScreen"/>
    <item android:top="-48dp">
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>
</layer-list>

Aplico un desplazamiento superior para ajustar bien la transición de la pantalla pre-carga hacia el splashscreen
Asignar como fondo el drawable creado en styles.xml
<style name="AppTheme.SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>

De paso elimino la idea de tener texto que aparece debajo del icono de la app, porque no encontrado como hacerlo directamente como un drawable.
layout splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@color/colorSplashScreen">

    <LinearLayout
        android:id="@+id/splashscreen"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|center_horizontal">

        <ImageView
        android:layout_width="wrap_content"
        android:contentDescription="@string/about.alt_logo"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"/>

</LinearLayout>

Código opcional para cambiar el tema al vuelo, en caso de no hacer un splascreen con un activity intermedio:
public class MyMainActivity extends AppCompatActivity {
 @Override
  protected void onCreate(Bundle savedInstanceState) {

    setTheme(R.style.Theme_MyApp); //Tu Tema general
    super.onCreate(savedInstanceState);
    // ...
  }
}


Q:

Image upload not placing Image in Server Folder

I am having trouble with uploading an Image to my server files.
I am building an online store where, when i add a product, a can select an image for it to.
I have checked my php.ini file to allow uploads, as well as sufficient size of file allowed.
I have set the permissions to the folder where the images are supposed to go to "full control" for "Everyone"
(just to avoid any problems there)
I have one physical PC with multiple small drives.
Only one drive has my web server files.
The others have Minecraft and TeamSpeak.
The PC is in a room next to my office at home on a local network.
I could upload the images manually with file browser or FTP but,
In the near future there will not only be me uploading and adding products to the store locally.
Now, when i open my add product page there is a "Upload Image" button next to a text field,
that opens a separate window containing the upload page code.
The text field is to link the image on my database.
So I click on the "Upload Image" button and  the following happens:
Small separate window appears with 2 buttons, Browse and Upload.
I click on browse, and select my image.
The image name now displays next to the browse button.
When I click Upload, it closes the page, the image name displays in the text field next to the "Upload Image"
button in the product adding list for database reference.
I click on add product, and the product , including the image name displays on the database.
But the image did not upload to the specified server folder.
I have tried inserting the entire file path...
"D:/Web/shop/graphics/products"
Didn't work.
(D:/Web.. is the drive and root folder with the website content)
WEB FOLDER STRUCTURE:
Web-->
      [main_page_images]
      [shop_root]-->
                    [shop_admin]-->
                                   [shop_images]-->
                                                   [products]-->
                                                   (where the image should go)
                    index.php
                    add_product.php
                    add_image.php
      index.php
      web.config
(there are some other folders in the structure but they are not relevant)
add_image.php code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>CompuShop Image Chooser</title>

<?php if ((isset($_POST["send"])) && ($_POST["send"] == "form1")) {
    $file_Name = $_FILES['userfile']['name'];
    move_uploaded_file($_FILES['userfile']['tmp_name'], "../shop_images/products".$file_Name);
?>

<?php
}
else
{?>
<form action="add_image.php" method="post" enctype="multipart/form-data" id="form1" />

    <input name="userfile" type="file">

    <input type="submit" name="button" id="button" value="Upload Image" />

    <input type="hidden" name="send" value="form1" />
</form>
<?php }?>

Now that I have give all the Info i posably can...
Am I missing something?
Am I doing something wrong?
Please help.

A:

I'm answering my own question today coz I can.
I'm not exactly shoor how I fixed this but it is working. (please reply if you know the solution)
I went through some other posts and one of them mentioned settings in my PhP config itself.
the latest PhP upload settings are by default...
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

So I changed it to...
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir = D:/Web/temp

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2048MB

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

I first changed the "upload_max_filesize" to 1024MB
Did not work.
Then to 2048MB
Same result.
Now here is what I think did the trick...
I then specify the "upload_tmp_dir" and it is uploading now.
My page code just for reference...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Shop Database Image Chooser</title>

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

 if ((isset($_POST["send"])) && ($_POST["send"] == "form1")) {
    $file_Name = $_FILES['userfile']['name'];
    move_uploaded_file($_FILES['userfile']['tmp_name'], "../shop_images/products/".$file_Name);
    ?>

<?php
}
else
{?>
<form action="image_adding.php" method="post" enctype="multipart/form-data" id="form1" />

    <input name="userfile" type="file">

    <input type="submit" name="button" id="button" value="Upload Image" />

    <input type="hidden" name="send" value="form1" />
</form>
<?php }?>

Thx to the guys from phphelp.com for all the patiance.


Q:

Jumping Animation: First animation duration doesn't work. IOS

I have an animation that, when a button is pressed, is supposed to jump up, then float back down. I use to animations one to make it float up, the second to make it come down. No matter what I do the first animation doesn't float, it just teleports to the top, and the second does exactly what it should.
This is what I have:
//This animation does not respond to its duration.
[UIView animateWithDuration:.5 delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     CGRect f = imageView.frame;
                     f.origin.y -= 40;
                     imView.frame = f;
                 }
                 completion:nil];

[UIView animateWithDuration:.7 delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     CGRect f = imageView.frame;
                     f.origin.y += 40;
                     imView.frame = f;
                 }
                 completion:nil];

another problem I have it that I want to change the image through out the animation but it always ends up starting with the image I declare last. Thank you!

A:

Your second animation overwrites the first animation because it doesnt have a delay.  Try starting the second animation from the first animation's completion block.
[UIView animateWithDuration:.5 delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     CGRect f = imageView.frame;
                     f.origin.y -= 40;
                     imView.frame = f;
                 }
                 completion:^{
                     [UIView animateWithDuration:.7 delay:0.0
                                         options:UIViewAnimationOptionCurveEaseOut
                                      animations:^{
                                         CGRect f = imageView.frame;
                                         f.origin.y += 40;
                                         imView.frame = f;
                                      }
                                      completion:nil];
                 }];


Q:

Mockito Spring Camel @Autowire fail

I'm trying to unit test a camel route.  The route under test extends a custom abstract RouteBuilder (I know about favouring composition over inheritance - this is maintenance code).  I've set up my test as @Roman Vottner did over here.  Everything works (is initialized) until I hit the first abstract class up the hierarchy.  It has an @Autowired class which wasn't initialized (is null) even though it was mocked and @Autowired when the test started.  Any ideas on how to solve my injection problem?
@RunWith(CamelSpringRunner.class)
@BootstrapWith(CamelTestContextBootstrapper.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {FooRouteTest.ContextConfig.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class FooRouteTest {

  @Configuration
  @PropertySource({"classpath:some.properties", "classpath:environment.properties"})
  public static class ContextConfig extends CamelConfiguration {

    @Bean
    public UserServices userServices() {
      return mock(UserServices.class);
    } //and many more of the like
  }

  @Autowired
  private UserServices userServices; //and all the others too

  @Test
  public void testAfoo() throws Exception {
//....
    template.setDefaultEndpointUri("direct://getTheData");
    template.sendBody(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
//...
  }
}

in the abstract super class while debugging:
@Autowired
public ClientServices clientServices;
//...
String clientNumber=clientServices.getLoggedInNumber();  //clientServices is null and not mocked!
//...

A:

Solved this by explicitly declaring FooRoute as a bean:
@Bean
public FooRoute fooRoute(){
  return new FooRoute();
}

@Override
public List<RouteBuilder> routes() {
  final List<RouteBuilder> routes = new ArrayList<>();
  routes.add(fooRoute());
  return routes;
}


Q:

IE driver server unexpected close error working with selenium python

I'm working with python and selenium web-driver to test a web software. I have a simple script, which I have to put some wait on it while IE web-driver is up in order to do some actions with other test elements. After that wait seconds, first try to access web elements results in close error. An alert shows that the IE driver server has been stopped and I should close or restart the program.
There is also some logs in the system exception information as below:
Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: IEDriverServer.exe
  Application Version:  2.33.0.0
  Application Timestamp:    519d056f
  Fault Module Name:    IEDF41E.tmp
  Fault Module Version: 0.0.0.0
  Fault Module Timestamp:   519d0564
  Exception Code:   c0000005
  Exception Offset: 00015a90
  OS Version:   6.1.7601.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

I got nothing from the provided link and also this file which is C:\Windows\system32\en-US\erofflps.txt. I'm using Windows 7 AMD64 and python 2.7 with selenium 2.9. Any idea about this issue?

A:

As @Arran said, the problem was about updating IE driver serve; since I updated my driver exe file to the latest version from this link, there is no more exceptions.


Q:

How to remove text above JSlider

I have a JSlider in my GUI that goes from 0 to 100. For some reason, there is text above the slider position that displays the current value of the slider and it follows my slider around.  I.e., if I move my slider halfway, "50" appears above where my slider currently is.  However, I can't figure out what that text field is called, all I know is its part of the slider.
I want to either remove it or be able to change it to something else, how would I do that?

A:

I would have just commented on Etaoin's answer, but I don't have the reputation for it yet.
At any rate, call this before instantiating the JSlider:
UIManager.put("Slider.paintValue", false);

Note the capital 'V' in paintValue.
Furthermore, to print all of the fun things that are currently set by your UIManager, enter this code anywhere after the UIManager has been instantiated:
Iterator<Entry<Object, Object>> it = UIManager.getDefaults().entrySet().iterator();
while(it.hasNext())
    System.out.println(it.next());

A:

This bothered me on a project once, and I found the following workaround. Call this once before instantiating your JSlider -- I put it in a static block in my JPanel subclass:
UIManager.put("Slider.paintValue", false);

That'll take care of it.


Q:

Trying to index data into Amazon elastic search

I am going through the following tutorial on Amazon's website to learn about how to use elastic search in my application: https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-gsg-upload-data.html
When I run the command:
     curl -XPOST MY_DOMAIN_ENDPOINT/_bulk --data-binary
     @bulk_movies.json -H 'Content-Type: application/json'

I am getting the following message:
curl: (3) Port number ended with 'a'

What is going wrong?

A:

OP was facing the issue as he wasn't passing the proper endpoint, once he passed the proper endpoint he issue was resolved.
So to avoid these kinds of issue, Please don't copy everything from the tutorial and pass the actual values.
One issue which happens very frequently, although which wasn't the case here is quotes changes when copying from different sources like editors sublime etc or from slack etc if it's not in the code block of slack.


Q:

Testing WML on mobile browsers

I am developing a mobile web application which is implemented in WML (to minimize roundtrips to the server).
I've tested the application on the following browsers:

IE for Windows Mobile 5
IE for Windows Mobile 6
Opera Mobile
Nokia Series 40 web browser
Nokia Series 60 web browser
NetFront (for Symbian)
NetFront (for Sony Ericsson)
NetFront (for Samsung)
Fly SX210 (don't know neither platform nor browser name, HTTP_USER_AGENT says FLY-SX210/Profile/MIDP.2.0Configuration/CLDC.1.0)

IPhone does not support WML, I use IUI for IPhone instead.
What else widely used mobile browsers should I test the application with?

A:

The only big one I think your missing is the Verizon HTML Browser, standered on most touch screen phones Verizon has.


Q:

Output Json Array in cpp using nlohmann

I created json objects using nlohmann library with this code:
nlohmann::json dataJson;
auto data = dataJson.array();

data[0]["message"] = "String";
data[0]["timestamp"] = 123;

The output is
{"message":"String", "timestamp": 123}

but i want the output to be
[{"message":"String", "timestamp": 123}]

in an array in order to have the ability to have multiple messages.
So i want to ask what is the best way to add the values in the array, because when I print it, the ouput of the array is null.
I am new at cpp so I want to apologize for the question if is considered too easy, but any help would be appreciated.

A:

nlohmann_json is a very useful library but it does have a few quirks. I find it's best to be explicit about intent.
Lambdas can be very useful here:
#include <iostream>
#include <nlohmann/json.hpp>

int main() {

  auto make_object = []
  {
    auto result = nlohmann::json::object();
    result["message"] = "String";
    result["timestamp"] = 123;
    return result;
  };

  auto make_array = [&make_object]
  {
    auto result = nlohmann::json::array();
    result.push_back(make_object());
    return result;
  };

  auto data = make_array();
  std::cout << data.dump() << std::endl;

  return 0;
}

expected output:
[{"message":"String","timestamp":123}]


Q:

Delphi XE7 crashses at shutdown

Since I installed Delphi XE7 I have this nasty crash as shutdown:
Description:
  Stopped working

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: bds.exe
  Application Version:  21.0.17707.5020
  Application Timestamp:    545bd62d
  Fault Module Name:    rtl210.bpl
  Fault Module Version: 21.0.17707.5020
  Fault Module Timestamp:   545bd940
  Exception Code:   c0000005
  Exception Offset: 00016a9c
  OS Version:   6.1.7601.2.1.0.768.3
  Locale ID:    1033

After I click the 'Close program' I get:

Exception EAccessViolation in module rtl210.bpl at 00016A9C.
  Access violation at address 50066A9C in module 'rtl210.bpl'. Read of
  address 075F2AF8.

I checked the call stack but it doesn't really makes any sense.
To see the call stack I started Delphi, then in 'Load process' I entered Delphi's path ( "C:\Delphi\XE7\bin\bds.exe" ).
I cannot set the '-p delphi' parameter in 'Parameters' box because when the second Delphi process is started it will complain that it cannot access the license file (which is blocked by the first Delphi process).
Call stack:
:50066a9c rtl210.@System@@IntfClear$qqrr44System@%DelphiInterface$17System@IInterface% + 0x10
:08baffdd fmx210.@System@Generics@Collections@%TList__1$56System@%DelphiInterface$29Fmx@Behaviormanager@IListener%%@SetCount$qqri + 0x49
:50061099 rtl210.@System@@Halt0$qqrv + 0xb1
:77378bd4 ntdll.wcsncmp + 0x88
:77342710 ; ntdll.dll
:7737cb10 ntdll.LdrUnloadDll + 0x4a
:753b8be4 KERNELBASE.FreeLibrary + 0x82
:2063a191 coreide210.@Exptmain@TExpertLib@$bdtr$qqrv + 0xa9
:5005f10b rtl210.@System@TObject@Free$qqrv + 0xb
:5070ba40 vcl210.@Vcl@Forms@TCustomForm@$bdtr$qqrv + 0x58
:210f57c0 designide210.@Deskform@TDesktopForm@$bdtr$qqrv + 0x40
:761aee1c kernel32.BaseThreadInitThunk + 0x12
:7738399b ntdll.RtlInitializeExceptionChain + 0xef
:7738396e ntdll.RtlInitializeExceptionChain + 0xc2

It says something about FMX but I never do FMX projects (still too unripe to be used). So I disable it.
What could cause the crash?

A:

This is a Delphi bug

SOLUTION: Enable 'FMX Standard Components' package.

Details: I turned out that I had the 'FMX Standard Components' package disabled - Seems logical to disable such a large library since I don't use it.
Well... Delphi don't like that! I enabled the library back and now I have no crash!
I could have delete the question since nobody answered posted any answer but I thought it will be useful to keep it. It documents a very important feature of Delphi: crash when the developer won't use FMX lib :)


Q:

How to debug TypeScript Express app in Visual Studio Code

I tried to debug the TypeScript Express App https://github.com/schul-cloud/node-notification-service/ in Visual Studio Code.
in launch.json I added the configuration
{
        "name": "notification service launch",
        "type": "node",
        "request": "launch",
        "args": ["src/app.ts"],
        "runtimeArgs": ["-r", "ts-node/register"],
        "outFiles": [ "${workspaceRoot}/build/**/*.js",  "${workspaceRoot}/node_modules/**/*.js" ],
        "cwd": "${workspaceRoot}",
        "protocol": "inspector",
        "internalConsoleOptions": "openOnSessionStart"
    }

But when I run the configuration the debugger fails with
Error: Cannot find module '@/routes/mail'

How do I start the debugger correctly so that it finds the modules?

A:

node-notification-service is using tsconfig-paths to get runtime module resolution to honor the paths defined in tsconfig.json, as you can see in package.json:
  "scripts": {
    // ...
    "server": "ts-node -r tsconfig-paths/register src/app.ts",
    // ...
  },

So you'll need to add tsconfig-paths to your launch configuration, like this:
"runtimeArgs": ["-r", "ts-node/register", "-r", "tsconfig-paths/register"],


Q:

Segmentation fault. Occured in an array element assignment, but now in printf

(Update: Problem solved. It all came down to a stupid typo on my part, causing me to write the wrong part of memory, which in turn caused some pointer to point to someplace that was off limits.)
So, I'm taking a course that involves some programming, and we've essentially been thrown in the deep in of the C pool. I've programmed in other languages before, so it's not all new, but I don't have a solid set of tools to debug my code when the proverbial shit hits the fan.
I had, essentially, the following
int nParticles = 32;
int nSteps = 10000;
double u[nParticles], v[nParticles];

for (i = 0; i < nSteps; i++) {
...
    for (j = 0; j < nParticles; j++) {
        u[j] = 0.001 * v[j];
    }
...
}

as one part of a bigger program, and I was getting segmentation fault. In order to pinpoint the problem, I added a bunch of
printf("foo\n");

and eventually it turned out that I got to step i = 209, and particle j = 31 before the segmentation fault occured.
After a bit of googling, I realised there's a tool called gdb, and with the extra printfs in there, doing bt in gdb tells me that now it's printf that segfaulting. Keep in mind though, I got segfaults before adding the diagnostic printfs as well.
This doesn't make much sense to me. How do I proceed from here?

Update:
valgrind gives me the following
==18267== Invalid read of size 8
==18267==    at 0x400EA6: main (in [path redacted])
==18267==  Address 0x7ff001000 is not stack'd, malloc'd or (recently) free'd
==18267==
==18267==
==18267== Process terminating with default action of signal 11 (SIGSEGV)
==18267==  Access not within mapped region at address 0x7FF001000
==18267==    at 0x400EA6: main (in [path redacted])
==18267==  If you believe this happened as a result of a stack
==18267==  overflow in your program's main thread (unlikely but
==18267==  possible), you can try to increase the size of the
==18267==  main thread stack using the --main-stacksize= flag.
==18267==  The main thread stack size used in this run was 10485760.
==18267==
==18267== HEAP SUMMARY:
==18267==     in use at exit: 1,136 bytes in 2 blocks
==18267==   total heap usage: 2 allocs, 0 frees, 1,136 bytes allocated
==18267==
==18267== LEAK SUMMARY:
==18267==    definitely lost: 0 bytes in 0 blocks
==18267==    indirectly lost: 0 bytes in 0 blocks
==18267==      possibly lost: 0 bytes in 0 blocks
==18267==    still reachable: 1,136 bytes in 2 blocks
==18267==         suppressed: 0 bytes in 0 blocks
==18267== Rerun with --leak-check=full to see details of leaked memory
==18267==
==18267== For counts of detected and suppressed errors, rerun with: -v
==18267== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
Segmentation fault (core dumped)

I don't know what that means.

Update:
I tried commenting out the array assignment that initially caused the segfault. When I do that, but leave most of the diagnostic printfs in, I get a segfault at i = 207 instead.
Update:
Problem solved. In the outer loop (where i is the counter, representing time steps), I had a couple of inner loops (all of which reused j as a counter, iterating over a bunch of particles). In one of the inner loops (not the one that segfaulted, though), I was accidentaly assigning values to E[i] where E is an array of nParticles size, so I was running way out of bounds. Fixing this stops the segfault from happening.
So, it all came down to a silly silly typo on my part.

Update:
I spoke to my brother, and he explained the problem in a way that at least satisfies my limited understanding of the situation.
By accidentaly writing things in E way beyond the end of that array, I probably overwrote the pointers associated with my other arrays, and then when I go to access those other arrays, I try to access memory that's not mine, and I get a segfault.
Thank you all so much for helping me out and putting up with my lack of knowledge!

A:

This got too long for a comment, but is not a complete answer. It's impossible to tell why your program dies without seeing a minimal example of the code.
printf normally segfaults for one of three reasons: Either

you are passing it a parameter it can't access (for instance a char * that does not point to correctly allocated memory containing a zero terminated string), or
you've run out of stack space (stack overflow) due to too much recursion, or
you have corrupted the heap by writing beyond a dynamic memory allocation.

My advice would be:

Compile your program with the -Wall option. Fix every warning, and understand why the warning occurs rather than just hiding the problem. Compiling with -Wall is a good habit to get into, and finds a large number of errors.
Download valgrind and run your program in valgrind. This will catch a lot of stuff.
Learn to use gdb. Tutorial here.
Comment or #if out large chunks of your program until you come down to the simplest case that does not error. Add bits back in and find out what the issue is.

A:

See these kind of errors mostly happens when the stack is corrupted.
please check if you have some where crossed the boundaries of an array(specifically local arrays)


Q:

Getting LINQ to Entities does not recognize the method 'Double GetProximityInMiles(double, double)'...

Here's the full message:
Getting LINQ to Entities does not recognize the method 'Double GetProximityInMiles(double, double)' method, and this method cannot be translated into a store expression.
Here's the code:
    public Maid[] GetMaidsByZipCode(string Zip, int Distance)
    {
        MaidsListEntities Context = new MaidsListEntities();

        return Context.Maids.Where(m => m.Zip == Zip && Distance <= GeoLocationProvider.Instance.GetProximityInMiles(Zip, m.Zip)).ToArray();
    }

A:

You are seeing this error because your method (GetProximityInMiles) could no be translated to a SQL query. You can try doing that part of the query in memory:
return Context.Maids.ToArray().Where(m => m.Zip == Zip && Distance <= GeoLocationProvider.Instance.GetProximityInMiles(Zip, m.Zip)).ToArray();

The first call to ToArray materializes all the Maids. The rest of the query is then performed in memory.
Note that this approach might cause performance problems if the record count in your table is too big.


Q:

error Type referred to is not an annotation type:

I got the following Aspect
@Around("execution(public * (@DisabledForBlockedAccounts *).*(..))" + " && @annotation(denyForTeam)")
public Object translateExceptionsDenySelectedAccount(ProceedingJoinPoint pjp, Deny deny) throws Throwable
{
    Account account = (Account) pjp.getArgs()[0];
    Account selectedAccount = (Account) pjp.getArgs()[1];

    if (ArrayUtils.contains(deny.value(), account.getRole()))
    {

        if (account.getType().equals(Type.CHEF) && !selectedAccount.getType().equals(Type.CHEF))
        {
            throw new IllegalAccessException("");
        }
    }
    return pjp.proceed();
}

and this Annotation:
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface DenyForTeam
{

Role[] value();

}

I get the error:error Type referred to is not an annotation type: denyForTeam
Why is DenyForTeam no Annotation? It is marked with @interface

A:

I solved my issue by specifying the package explicitly
change the following
@Around("@annotation(SessionCheck)")
public Object checkSessionState(ProceedingJoinPoint joinPoint) throws Throwable {
    // code here
}

to
@Around("@annotation(my.aop.annotation.SessionCheck)")
public Object checkSessionState(ProceedingJoinPoint joinPoint) throws Throwable {
    // code here
}

or put them in the same package

A:

There needs to be a method argument of the name denyForTeam whose type should be DenyForTeam annotation. @annotation - bind the annotation to a method argument with the same name.
@Around("execution(public * (@DisabledForBlockedAccounts *).*(..))" + " && @annotation(denyForTeam)")
public Object translateExceptionsDenySelectedAccount(ProceedingJoinPoint pjp, Deny deny, DenyForTeam denyForTeam) throws Throwable
{

If you don't want the annotation passed as an argument then include the @DenyForTeam (full qualified) in the pointcut expression.
@Around("execution(@DenyForTeam public * (@DisabledForBlockedAccounts *).*(..))")
public Object translateExceptionsDenySelectedAccount(ProceedingJoinPoint pjp, Deny deny) throws Throwable
{