Q:

How to show the DrawerLayout when sliding from left to right, no matter where?

background
google has introduced the DrawerLayout, which shows a menu on the left area of the screen when you click on the "up" button of the action bar.
because the library isn't supported yet on actionBarSherlock, there is already a way to overcome it using this project .
it already has variants on many apps: currents, gmail, hangouts, youtube...
the question
on the "currents" app (and in youtube) , when the user slides the (most-left) page from left to right , the DrawerLayout appears, no matter where the finger has started the touch .
how can i achieve the same effect? maybe i should use onInterceptTouchEvent  ?
there isn't much documentation and tutorials of what cool things can be done , other than this link (ok and this one too) . they say (in the part of "Give the user a quick peek") that about 20dp on the left is used for this functionality, but i can see that "currents" work with much larger area.
it seems the library is still not quite finished, and so the layout xml file cannot even be shown in the visual UI editor...

EDIT: it seems that the library is open sourced. code is available on :
.../android-sdk\sources\android-18\android\support\v4\widget\DrawerLayout.java
.../android-sdk\sources\android-18\android\support\v4\widget\SlidingPaneLayout.java
.../android-sdk\sources\android-18\android\support\v4\app\ActionBarDrawerToggle.java

now the question is how to make it work as i've written, so that it would work like on youtube , allowing us to customize how it looks and from where to allow scrolling it.

A:

SlidingMenu is best sliding library I've ever found, It's very good library.
You can set getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN) enabling fling for all screen.

A:

The problem is that DrawerLayout uses ViewDragHelper which has a default EDGE_SIZE of 20dp which is used to calculate the mEdgeSize like this:
mEdgeSize = (int) (EDGE_SIZE * density + 0.5f);

Here is a function which sets mEdgeSize to a percentage of the display width:
public static void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
    if (activity == null || drawerLayout == null)
        return;

    try {
        // find ViewDragHelper and set it accessible
        Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
        leftDraggerField.setAccessible(true);
        ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
        // find edgesize and set is accessible
        Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
        edgeSizeField.setAccessible(true);
        int edgeSize = edgeSizeField.getInt(leftDragger);
        // set new edgesize
        Point displaySize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
        edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x * displayWidthPercentage)));
    } catch (NoSuchFieldException e) {
        // ignore
    } catch (IllegalArgumentException e) {
        // ignore
    } catch (IllegalAccessException e) {
        // ignore
    }
}

So, let's say you want 30% of your left edge to react to slide events and open the Navigation Drawer, then simply call:
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setDrawerLeftEdgeSize(this, mDrawerLayout, 0.3f);

A:

I tried changing default EDGE_SIZE solution, and encountered the long clicking problem too.
Finally, Ifound override dispatchTouchEvent and open drawer depending the sliding direction by calculating X offset.
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    int action = ev.getAction();
    switch (action) {
        case MotionEvent.ACTION_DOWN:
            startX = ev.getX();
            startY = ev.getY();
            break;
        case MotionEvent.ACTION_UP:
            endX = ev.getX();
            endY = ev.getY();

            float sensitivity = 5;
            // From left to right
            if (endX - startX >= sensitivity) {
                if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    mDrawerLayout.closeDrawer(Gravity.RIGHT);
                } else {
                    mDrawerLayout.openDrawer(Gravity.LEFT);
                }
            }

            // From right to left
            if (startX - endX >= sensitivity) {
                if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    mDrawerLayout.openDrawer(Gravity.RIGHT);
                }
            }

            break;
    }


Q:

Accessing VMWare Management Network from a different subnet

Here's the scenario...
We've got a VSphere ESXi 5 box running on a 9.x subnet, our office runs from the 1.x subnet. We can access the VM's running on the box without issue (which also have 9.x IP's) however we can ping the management network interface for the VM box but can't either browse to the box http/https nor use VSphere client to connect to it. The connection just times out. We have a VPN connection between the two subnets and have checked both firewalls and nothing is being blocked (which is also supported by the fact that all traffic can pass to/from the VM's).
Is there a setting within VMWare that restricts management traffic by default, to its local subnet? It would make sense for that to be the case...but I can't find any options within VSphere client. The default gateway is definitely correct for the management network, again supported by the fact that we can ping and get a response from its IP from our 1.x network.
If anyone has any suggestions, they would be kindly appreciated!
Thank you!

A:

This isn't anything whatsoever to do with vSphere, it's a simple Layer 3 routing issue, get some working routing in place, that's it.


Q:

Efficiently query for the latest version of a record using SQL

I need to query a table for the latest version of a record for all available dates (end of day time-series). The example below illustrates what I am trying to achieve.
My question is whether the table's design (primary key, etc.) and the LEFT OUTER JOIN query is accomplishing this goal in the most efficient manner.
CREATE TABLE [PriceHistory]
(
    [RowID] [int] IDENTITY(1,1) NOT NULL,
    [ItemIdentifier] [varchar](10) NOT NULL,
    [EffectiveDate] [date] NOT NULL,
    [Price] [decimal](12, 2) NOT NULL,

    CONSTRAINT [PK_PriceHistory]
       PRIMARY KEY CLUSTERED ([ItemIdentifier] ASC, [RowID] DESC, [EffectiveDate] ASC)
)

INSERT INTO [PriceHistory] VALUES ('ABC','2016-03-15',5.50)
INSERT INTO [PriceHistory] VALUES ('ABC','2016-03-16',5.75)
INSERT INTO [PriceHistory] VALUES ('ABC','2016-03-16',6.25)
INSERT INTO [PriceHistory] VALUES ('ABC','2016-03-17',6.05)
INSERT INTO [PriceHistory] VALUES ('ABC','2016-03-18',6.85)
GO

SELECT
    L.EffectiveDate, L.Price
FROM
    [PriceHistory] L
LEFT OUTER JOIN
    [PriceHistory] R ON L.ItemIdentifier = R.ItemIdentifier
                     AND L.EffectiveDate = R.EffectiveDate
                     AND L.RowID < R.RowID
WHERE
    L.ItemIdentifier = 'ABC' and R.EffectiveDate is NULL
ORDER BY
    L.EffectiveDate

Follow up: Table can contain thousands of ItemIdentifiers each with dacades worth of price data. Historical version of data needs to be preserved for audit reasons. Say I query the table and use the data in a report. I store @MRID = Max(RowID) at the time the report was generated. Now if the price for 'ABC' on '2016-03-16' is corrected at some later date, I can modify the query using @MRID and replicate the report that I ran earlier.

A:

A slightly modified version of @SeanLange's answer will give you the last row per date, instead of per product:
with sortedResults as
(
    select *
        , ROW_NUMBER() over(PARTITION by ItemIdentifier, EffectiveDate
                            ORDER by ID desc) as RowNum
    from PriceHistory
)

select ItemIdentifier, EffectiveDate, Price
from sortedResults
where RowNum = 1
order by 2


Q:

Nested transactions in Sql Server

Imagine the following scenario:
I am using SQL Server 2005. I have a transaction that is calling, among other SQL statements, a stored procedure that also has a transaction inside. The outer transaction sometimes fails and it is rolled back after the stored procedure is called and committed successfully.
My question is, does the stored procedure's transaction rollback too?

A:

With a nested transaction, a commit does not write any changes to disk, except for the top level transaction. A rollback, however works regardless of the level of the transaction, so yes, it will roll the inner transaction back.

A:

Absolutely yes, the top level transaction will own all the data changes until it is committed or rolled back.
However I would encourage you to think carefully about the transaction model. The more such scenarios exist in your system the greater your exposure to locking issues. Also the computational expense of the procedure increases.
It's remarkable how often, when rationalising SQL, I find transactions have been implemented where they just aren't required. I encourage you (and anyone working with transactions) to think carefully about why you are using them in each context and what would happen were the transaction not implemented. Just my 2c worth!


Q:

How do i convert benzoic acid to meta-fluorobenzoic acid?

in not more than 3 steps. i did it but the process was a little long.
here is my attempt

A:

Two steps should be enough ;-)

Nitrate benzoic acid. In J. Chem. Educ., 1967, 44, 464
(DOI), the authors added benzoic acid to fuming nitric acid at 0 °C. 3-nitrobenzoic acid is the major isomer (~ 75%). Recrystallize from ethanol.

Your product is an electron-deficient arene and $\ce{-NO2}$ is a decent nucleofuge. Try to replace it by fluorine in a nucleophilic aromatic substitution!

In the case of 4-nitrobenzoic acid, the transformation to 4-fluorobenzoic acid has been described to work with a yield of >95% in a room temperature reaction using DMSO as a solvent and anhydrous tretrabutylammonium fluoride (TBAF) as the reagent. (DOI)

A:

Your approach might be "three steps" according to some people. The last two reactions in your synthesis, converting the amine to the diazo salt followed by fluoridation, are usually done in the same reaction vessel with the diazo salt never isolated.
Your three steps would be:
$$\begin{aligned}
1.\ &\ce{->[\ce{HNO3}][\ce{H2SO4}]}\\
\\
2.\ &\ce{->[\ce{Sn}][\ce{HCl}]}\\
\\
3.\ &\ce{->[1)\ \ce{NaNO2,\ HCl}][2)\ \ce{HBF4}]}
\end{aligned}$$


Q:

Deploy Symfony app with LexikJWTAuthenticationBundle on Heroku

I have my app deployed to Heroku, then I added an api with LexikJWTAuthenticationBundle for authentication. I created public and private keys with a passphrase like the documentation says, and it works great on my local machine, yet I do not know how to create or copy those files to Heroku.

A:

With LexikJWTAuthenticationBundle v2.5.0, this is now possible to give keys as environment variables : commit 154c60e90b8f10e1fdca819a681b5f189e8ed9ef.
Replace keys path for string keys in lexik_jwt_authentication.yaml :
Before :
lexik_jwt_authentication:
    private_key_path: '%kernel.project_dir%/%env(JWT_PRIVATE_KEY_PATH)%'
    public_key_path: '%kernel.project_dir%/%env(JWT_PUBLIC_KEY_PATH)%'

After :
lexik_jwt_authentication:
    secret_key: '%env(JWT_SECRET_KEY)%'
    public_key: '%env(JWT_PUBLIC_KEY)%'

I didn't find a solution to paste full keys as string in .env file, so I kept private_key_path and public_key_path in config/dev/lexik_jwt_authentication.yaml for my dev environment, and used secret_key and public_key only in config/prod/lexik_jwt_authentication.yaml, for my Heroku production.
To finish, add env variables on Heroku, deploy and you're done :


Q:

Tiled gallery with -tag around images

I'm using pure CSS (Bootstrap 4) to display a tiled gallery.
To do this, I'm using the flexbox elements from Bootstrap (d-flex and flex-wrap).
Everything works fine if I only use <img>-tags.
But I want to wrap the images with an <a>-tag to link to a lightbox.
If I do this, the gallery breaks.
Here's an example of my code: https://codepen.io/cray_code/pen/RMrbzK
Is there anything I could do? I've tried to use the CSS from the img but it doesn't work.
And as optional question: Is it possible to force the gallery to display in two columns? The last image is almost square but shows as widescreen rectangle.

A:

You can probably achieve what you want if you make the <a> tag a flex item and flex container as well. So try adding this style:
.img-gallery a {
    flex-grow: 1;
    display:flex;
}

Here is an updated CodePen


Q:

Please explain rowspan and colspan, col and colgroup

Can anyone explain rowspan and colspan, col and colgroup? And are these W3C valid and semantically correct? Under which circumstances are these useful?

A:

colspan

    people are...

    monkeys
    donkeys

rowspan

    monkeys are...
    ... real monkeys

    ... 'unreal' monkeys (people...)

w3c
as you see, this is for connecting table-cells - and because this is sometimes neccessary, it's valid (RegDwights links will give more information...).
col/colgroup
colgroup and col are used to set attributes to every line in the table (so you don't have to write width="80" for the first td in every line(tr)):

  <colgroup>
    <col width="80">
    <col width="100">
    <col width="320">
  </colgroup>

    first line, first column
    first line, second column
    first line, third column

you can also group the cols, lets say the first and second column should get a with of 80, the third should get 320:

  <colgroup width="80" span="2"></colgroup>
  <colgroup width="320" span="1"></colgroup>

    first line, first column
    first line, second column
    first line, third column

A:

Yes, they are all recommended by W3C. Here are direct links to the documentation:

col
colgroup
colspan
rowspan


Q:

Remove a collection from a collection

I've been building a custom ticket system for my Laravel application, and users can place comments on their tickets.
When a new comment is placed, I want to send a notification to everyone involved in the ticket.
Users can be involved if they are:

the ticket owner
the agent assigned to the ticket
invited as a participant to the ticket

To do this, I am creating a collection of users and then looping through them to notify them. The only issue with this is that it currently includes the person making the comment too, and they don't need to be notified as they were the ones leaving the comment.
I've tried to filter the collection to remove the user if the id matches the currently logged in user, but this doesn't seem to work:
$ticket = App\Ticket::findOrFail(1);

//Create collection to hold users to be notified
$toBeNotified = collect();

//Add the ticket owner
$toBeNotified->push($ticket->owner);

//If an agent is assigned to the ticket, add them
if(!is_null($ticket->assigned_to)) $toBeNotified->push($ticket->agent);

//Add any active participants that have been invited
$ticket->activeParticipants()->each(function($participant) use ($toBeNotified) {
    $toBeNotified->push($participant->user);
});

//Remove any duplicate users that appear
$toBeNotified = $toBeNotified->unique();

//Remove the logged in user from the collection
$toBeNotified->filter(function($user) {
    return $user->id != Auth::user()->id;
});

//...loop through each user and notify them

Upon further reading, I think this is because you use filter to remove an element from a collection, rather than a collection that is inside a collection.
How can I remove a user from the collection if they are the currently logged in user?
When I dd($toBeNotified) after running the above, this is the result:

A:

You can use except to achieve this.
$toBeNotified = $toBeNotified->except(auth()->id());

As a side note you should use merge when you want to add more than one user.
$toBeNotified = $toBeNotified->merge($ticket->activeParticipants);

The filter method you use is correct as well, but it returns the filtered collection while keeping the original collection unchanged.
$toBeNotified = $toBeNotified->filter(function($user) {
    return $user->id != auth()->id();
});

Edit: The except would work only when you have an eloquent collection.


Q:

Check if PHP is running in local server

Well. I read some topics in SO but I not found a very specific answer.
I need to check with PHP if a PHP code is running in local or remote host. Currently I check with $_SERVER['SERVER_NAME'] but it is inconsistent. In this case, if I run PHP with listed IPs like 127.0.0.1 or localhost it'll consider local, otherwise remote. If I share my IP with a friend, my code still local, but it consider remote because the shared IP isn't listed.
Well, I think that check IP for localhost is not a good idea (except if you know a good method). I tried methods like gethostbyaddr() and gethostbyname() but don't work correctly too.
I don't have a PHP code to show, but my code is basically that:
// true = localhost
return $_SERVER['SERVER_NAME'] === '127.0.0.1';

The fundamental question is: what can determine that PHP is running local? What is "local" for PHP? I think that it can solve the problem.
Obs.: I don't have access to CMD/Shell with PHP.

A:

You could do what most PHP frameworks do and set a flag during your app's bootstrap phase that defines which environment the code is running in. In it's simplest form:
// the setting when run on a dev machine
define('ENV', 'local');

Then it's a simple case of:
if ( ENV == 'local' )
{
    // do stuff
}

A:

This is how I do it, which I find more reliable than trying to detect for 127.0.0.1:
if( strpos(gethostname(), '.local') !== false ) { }

Basically, the hostname's on my workstations all have .local appended to it. You can change this to match your workstation's hostname entirely.


Q:

hosting WCF service in IIS with windows authentication and without anonymous access

I would like to use WCF service hosted in IIS (5/6) with integrated windows authentication enabled and anonymous access disabled. I tried to do this by following http://msdn.microsoft.com/en-us/library/ff648431.aspx, but getting an error saying certificate is not installed.  But I don't need SSL. I don't have any clients expecting older ASMX services, so I don't need to use basicHttpBinding (and also it is not secure), so I tried to use wsHttpBinding.
How do I get wsHttpBinding with windows authentication to work without SSL? This is such a common requirement, but I couldn't find any solution for this. Can someone post the configuration for the client and the server please? I am using ASP.NET client.
My configuration below. and the exact error message is:

An error occurred while making the HTTP request to
  https://mymachine/WCFTest/Service1.svc. This could be due to the fact
  that the server certificate is not configured properly with HTTP.SYS
  in the HTTPS case. This could also be caused by a mismatch of the
  security binding between the client and the server.

I used "svcUtil" utility to generate the proxy class and configuration for the client.
server:
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="wsHttpEndpointBinding">
                    <security mode="Transport"/>
                </binding>
            </wsHttpBinding>
        </bindings>
        <services>
            <service behaviorConfiguration="WCFTest.Service1Behavior" name="WCFTest.Service1">
                <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" name="wsHttpEndpoint" contract="WCFTest.IService1"/>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WCFTest.Service1Behavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>

client:
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
            receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
            transactionFlow="false" hostNameComparisonMode="StrongWildcard"
            maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
            messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
            allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
              enabled="false" />
          <security mode="Transport">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                establishSecurityContext="true" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://mymachine/WCFTest/Service1.svc"
          binding="wsHttpBinding" bindingConfiguration="wsHttpEndpoint"
          contract="IService1" name="wsHttpEndpoint">
        <identity>
          <userPrincipalName value="mymachine\ASPNET" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>

A:

I ended up using basicHttpBinding as explained in the article http://msdn.microsoft.com/en-us/library/ff648505.aspx. posting the config for the client and the server below if anyone is interested. client config is generated using "svcutil".
server config:
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpEndpointBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="WCFTest.Service1Behavior" name="WCFTest.Service1">
        <endpoint address="" binding="basicHttpBinding"
          bindingConfiguration="BasicHttpEndpointBinding"
          name="BasicHttpEndpoint" contract="WCFTest.IService1">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCFTest.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

client config:
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
            receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
            bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://machinename/WCFTest/Service1.svc"
          binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpoint"
          contract="IService1" name="BasicHttpEndpoint" />
    </client>
  </system.serviceModel>


Q:

Test templates and variables used in Tornadoweb

I'm testing the MainHandler using the code below.
import tornado.httpserver
import tornado.httpclient
import tornado.ioloop
import tornado.web
import unittest

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        kwargs = {'name' : 'world'}
        self.render('template.html', **kwargs)

class TestTornadoWeb(unittest.TestCase):
    http_server = None        response = None

    def setUp(self):
        application = tornado.web.Application([
                (r'/', MainHandler),
                ])
        self.http_server = tornado.httpserver.HTTPServer(application)
        self.http_server.listen(8888)

    def tearDown(self):
        self.http_server.stop()

    def handle_request(self, response):
        self.response = response
        tornado.ioloop.IOLoop.instance().stop()

    def testHelloWorldHandler(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_client.fetch('http://localhost:8888/', self.handle_request)
        tornado.ioloop.IOLoop.instance().start()
        self.failIf(self.response.error)
        self.assertEqual(self.response.body, 'Hello, world')

if __name__ == '__main__':
    unittest.main()

The template.html:
Hello, {{name}}

I wanna test the template and its variables.
How I can test if name was received correctly?
There's some attribute that I can use to do the asserts or this should be done another way?

A:

That's essentially what you're already doing in your assertion. Since the client instance is pulling the rendered template, you can't match the template variable. By using your kwargs in the template, it's rendering those kwargs into the template - where {{name}} is 'world' (the expected output), your template variable has been received and rendered.
If you need to test specific output, a fairly inelegant solution could be to assign each variable a meaningless
 tag (i.e.,
{{name}}
) and then use the assertIn method (i.e., self.assertIn(self.response.body, '
world
')) to test for the correct output.


Q:

Connect to an online database (mySQL) from Swift, using PHP. (XCODE)

I want to connect my xcode app to online database and get the data from it and display in my app + write the data into online database using my app. I've already done with app but now it gives me an error.
ERROR :

I have my online database in my web page and i have uploaded two php files into the file manager in my web. One php file retrieving all the data in my database and encoding them to json. And second php file doing the query to write data into my online database from my app.

As in above pic im getting json output successfully but when i try to get the data  into an array in xcode it gives me that error.
This is my code
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableview: UITableView!
    @IBOutlet var inputFriendName: UITextField!
    @IBOutlet var inputFriendInfo: UITextField!

    var data: NSArray = []

    override func viewDidLoad() {
        super.viewDidLoad()
        data = dataOfJson("http://bishanonline.com/extra/serviceselect.php")
        println(data)

    }

    @IBAction func reload() {
        data = dataOfJson("http://bishanonline.com/extra/serviceselect.php")
        self.tableview.reloadData()
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    func dataOfJson(url: String) -> NSArray {
        var data = NSData(contentsOfURL: NSURL(string: url)!)
        return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: additionInfoCell = self.tableview.dequeueReusableCellWithIdentifier("customCell") as additionInfoCell
        var maindata = (data[indexPath.row] as NSDictionary)
        cell.friendName!.text = maindata["Name"] as? String
        cell.friendInfo!.text = maindata["Additional Info"] as? String
        return cell
    }

    @IBAction func uploadToDatabase() {
        var url: NSString = "http://bishanonline.com/extra/servicequery.php?x=\(inputFriendName.text)&y=\(inputFriendInfo.text)"
        url = url.stringByReplacingOccurrencesOfString(" ", withString: "%20")
        url = url.stringByReplacingOccurrencesOfString("/n", withString: "%0A")
        var data = NSData(contentsOfURL: NSURL(string: url)!)
        var result = NSString(data: data!, encoding: NSUTF8StringEncoding)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Issue is in this code lines
 func dataOfJson(url: String) -> NSArray {
    var data = NSData(contentsOfURL: NSURL(string: url)!)
    return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
}

Please help me to get json data into array. Appreciate any help.

A:

Finally problem resolved.First i am going to elaborate the exact problem then the solution will be posted.
The code you were doing was totally fine but the real problem was your backend

For serviceselect.php

The code you have done for fetching records is
func dataOfJson(url: String) -> NSArray
{
   var data = NSData(contentsOfURL: NSURL(string: url)!)
   return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
}
This above method is returing NSArray but the data you are getting from the server is kinda messed up because along with JSON data some garbage data is included as well.Check out the below image

So when try to generate JSON data from above string we are getting crashes and errors.
    May be due to free hosting service we are getting this message (Not sure)

Solution

   func getallrecords(){
    let url = NSURL(string: "http://bishanonline.com/extra/serviceselect.php")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        var d = NSString(data: data, encoding: NSUTF8StringEncoding)
        var arr = d!.componentsSeparatedByString("<") // spliting the incoming string from "<" operator because before that operator is our required data and storing in array
        var dataweneed:NSString = arr[0] as NSString // arr[0] is the data before "<" operator and arr[1] is actually no use for us
         if let data = NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray

// JSONObjectWithData always have first argument of NSData but our dataweneed is actually NSString so we are actually converting NSString to NSData
   {
            for dd in data{
                var name : String = dd["Name"]! as String
                var info : String = dd["Additional Info"]! as String
                println("Name is : \(name)") // MainDeveloper for 0 and BestBuddy for 1 index
                println("Info is : \(info)") // Bishan for 0 and AkilaPrabath for 1 index
     }
        }
    }

    task.resume()
    }

Final output

For servicequery.php

   func addrecord(x:String,y:String){
   let request = NSMutableURLRequest(URL: NSURL(string: "http://bishanonline.com/extra/servicequery.php")!)
            var postString : String = "x="+x+"&y="+y
            request.HTTPMethod = "GET"
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if error != nil {
                    println("error=\(error)")
                    return
                }

                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

                if jsonResult as String == "Successfully added "
                {
                 // Show an alert to notify user
                }
           }
            task.resume()
           }

Also remove "echo $query;" on line 30 of servicequery.php


Q:

Visualizing running services in Grafana

How to add query to visualize service running on Ubuntu using Grafana?
I tried to add conditions in where tag like service=cron, but it's not working.
FROM default processes WHERE host = ubuntu1604 AND service = cron
SELECT field(total)mean() GROUP BY time(10s)fill(null)F
FORMAT AS Time series
ALIAS BY Service

After adding service condition I'm not able to visualize the graph.

A:

Can you indicate exactly what the data source is? Is it InfluxDB? If so, you may need single quotes around what you are checking in where, such as:
host = 'ubuntu1604' and service = 'cron'


Q:

Email virus that sends to self?

Has anybody ever heard of an email virus that does something like this:
From: [Actual Friend's Name] (mailto: [Different, Unknown Email)
To: [My Name]
Subject: [My Name]

Hello [My Name]
    bad link

A relative of mine told me he got emails from me, but upon inspecting, the above is what I saw. I have never seen this before? It seems that maybe another account of his might be compromised and that is how it knows the names, but not the addresses?

A:

Yes it's called email spoofing

The technique is now used ubiquitously by bulk email software as a
means of concealing the origin of the propagation. On infection, worms
such as ILOVEYOU, Klez and Sober will often try to perform searches
for email addresses within the address book of a mail client, and use
those addresses in the From field of emails that they send, so that
these emails appear to have been sent by the third party. For example:
Alice is sent an infected email and then the email is opened,
triggering propagation. The worm finds the addresses of Bob and
Charlie within Alice's address book. From Alice's computer, the worm
sends an infected email to Bob, but the email appears to have been
sent by Charlie.


Q:

Why containers network throughput is low

I created a couple of containers using Dockers and measured the network performance by means of Netperf. However the throughput results to be quite low, around 563.81 Mb/s. Isn't the communication between 2 containers/processes done through main memory? Does anyone have an idea why I am having such a low throughput. Do I need a specific configuration?
Thanks,
Genc

A:

The question has been asked on the docker-user mailing list, and after some investigation, we found out that performance of veth in VMs with kernel 3.8 was "not great", and was significantly improved with kernel 3.10.
In other words:

if you run containers on bare metal, you will be fine (and see very fast transfer speeds between containers), regardless of the kernel version that you are using;
if you run containers in a VM (tested with Xen, VirtualBox, and KVM), you might see a huge drop in container-to-container transfer speed, if you run with kernel up to 3.8;
if you run kernel 3.10 or above, performance will be fine, regardless of the setup.

We haven't pinpointed the source of the problem yet, though.


Q:

Передача ответа команды ls в массив

Скрипт должен заполнить массив list именами файлов текущего каталога, чтобы в дальнейшем можно было по очереди эти файлы обрабатывать самыми разными способами в зависимости от имени.
Выдает ошибку

строка 2: $list: неоднозначное перенаправление

Плохо знаю синтаксис языка, чтобы написать самому правильно. Прошу подсказки
#!/bin/bash
ls -1 > $list
echo ${list[2]}

A:

получить результат выполнения команды: $(команда).
поместить строки в массив: m=('строка1' 'строка2')
получить первый элемент массива: echo ${m[0]}
всё вместе:
$ cd /
$ list=($(ls))
$ echo ${list[0]}
bin

предупреждение: строки в данном случае отделяются пробелами, поэтому если в именах файлов/каталогов есть пробелы, элементов массива будет больше, чем файлов/каталогов.
чтобы этого избежать, лучше не «парсить» вывод программы ls, а получить список файлов/каталогов «нативными» средствами:
$ list=(*)


Q:

Processing SQS queues with boto

I have a python script using the boto library on ec2 instance which is part of an autoscaling group. The script processes messages from a SQS queue:
import boto
from boto.sqs.message import Message

conn = boto.connect_sqs()
q = conn.create_queue('queue-name')

while (qin.count() > 0):
    m = q.get_messages()
    #do something with the message

Does using the while statement make sense? Does count() update in real time as:

other instances take messages off the queue (or am I going to double up)
new messages are added to the queue (or will I miss them?)

How do I make this script constantly listen for new additions to the queue, even while the queue is empty?
In this question Processing items in SQS queue with a php script it was mentioned that 'sqs ruby client library has a method "poll" which continuously polls the queue and on receiving a message in the queue passes it on to a block'. Is there an equivalent in Python?
It has also been suggested that the SNS could be used to notify the scripts of the message queue status but I do not see how you could configure a responsive system with SNS as the metric alarms are not fine grained enough.

A:

You shouldn't rely on the count for a queue as it's only meant to provide an approximate count and is not guaranteed to be accurate.
If you want to just keep polling forever, just do this:
while 1:
    messages = q.get_messages()
    # do something with messages
    time.sleep(N)

I have added the call to time.sleep to introduce a delay in the loop.  The value of N should be at least one second and could be considerably more, depending on how quickly you expect new messages to appear in your queue.  If you don't put some sort of delay in the loop you will probably start getting throttled by the service.
To avoid a message getting read multiple times, you should try to adjust the visibility timeout of the queue to be a value greater than the time it takes you to process a message and then make sure you delete the message when processing has completed.

A:

Example:
# wait_time_seconds count only 1 request in x seconds (0 - 20)
# num_messages get x messages in same request (1 - 10)
while 1:
    logger.info("... waiting messages ...")
    messages = queue_in.get_messages(wait_time_seconds=20, num_messages=10)
    for message in messages:
        logger.info('message: %s' % (message,))
        queue_in.delete_message(message)

A:

When you pull a message from SQS, the message becomes invisible and unreachable by other queue queries (edit - invisibility can be set between 0 and 12 hrs).
You will have to get the queue again each time new messages are added, but this should not be a problem - that's why the queuing service exists in the first place.

If you want to constantly poll the queue, try what's called Long Polling - you can have a continuous poll for up to 20 seconds that returns when the queue is populated.
Hope that's helpful, otherwise poke around the boto sqs documentation.


Q:

How to sort a collection using Collection.sort()

I am writing a program that stores an ArrayList of Person objects (input is from a text file).
This is the code for the Person class, which I will create Person objects from:
import java.io.Serializable;

public class Person implements Comparable<Person>, Serializable
{
private String firstName;
private String lastName;
private int age;

public Person(String firstName, String lastName, int age)
{
    this.firstName = firstName;
    this.lastName = lastName.toUpperCase();
    this.age = age;
}

public int getAge()
{
    return age;
}

public String getName()
{
    return firstName;
}

/**
 * @return a String of the details of a person in the format:
 *      Name: <firstName> <lastName> Age: <age>
 */
public String toString()
{
    return

            "Name: " + firstName + "" + lastName + "\t\t" + "Age: " + age;
}

/**
 * Compare the age of the current instance of Person to another age of the specified Person
 * @return negative number this < p
 * @return 0 if this == p
 * @return positive number if this > p
 */
public int compareTo(Person p) {
          return ((Integer)this.getAge()).compareTo(p.getAge());
}

And I created a Comparable interface:
public interface Comparable<T> {
public int compareTo(T o);
}

And here is the code for the class called Collection which will create an ArrayList to store Person objects, I ommitted parts of the code that were not relevant as it is long:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Iterator;

public class Collection
{
private ArrayList<Person> people;

public Collection()
{
    people = new ArrayList<Person>();
}

public void readFromFile(String filename)
{
    // code that will get input to assign values to fields to a Person

    Person newPerson = new Person(firstNameToken, lastNameToken, ageToken);
}

/**
 * Prints the details of each person held in the people ArrayList
 */
public void printDetails()
{
    Iterator<Person> it = people.iterator();

        while(it.hasNext())
        {
        Person p = it.next();
        System.out.println(p.toString());
        }
}

public static void main(String [] args) throws FileNotFoundException
{
    Collection c = new Collection();

    // check
    //for(Person person : c.people)
    //{
    //  System.out.println(person);
    //}

    Collections.sort(c.people);
}
}

However I get this error, the sort does not work:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type Person is not a valid substitute for the bounded parameter >

Does anyone know why? I am looking furiously around on google for solutions, I can't see what I am missing. I've implemented comparable..

A:

And I created a Comparable interface: public interface Comparable { public int compareTo(T o); }

You are not supposed to create your own interface. Use java.lang.Comparable<T>, the one that the Collections.sort() method expects your object to implement


Q:

php custom error handler how to print error in production?

I have an interface calling some php function by ajax.
There is an uncatched error that I have only in production. Due I make estensive use of getJson data exchange , I needed to silent errors and warnings with a custom php error handler.
The problem is that anyway when code generates an error in production I wish to print it out to the user, to understand where the problem is. My code is :
function myErrorHandler($errno, $errstr, $errfile, $errline)
{

switch ($errno) {
case E_ERROR:
    case E_USER_ERROR:
    $error= "My ERROR [$errno] $errstr
\n";
    $error.= "  Fatal error on line $errline in file $errfile";
    $error.= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
\n";
    $error.= "Aborting...
\n";
    if(isAjaxCalling()){
        $_SESSION['Errors']['Errors'][]=$error;
    }

    ini_set('display_errors',1);
    ini_set('error_reporting','E_ALL');
    echo $error;
    exit(1);
    break;
case E_WARNING:
case E_USER_WARNING:

....
}

A:

You need to let know the ajax handler on the client side that the returned value is in fact an error message, best to do it with status header:
header("HTTP/1.0 500 Internal server error");

Then either globaly, or individualy per ajax request, set function that will handle the error. In jQuery, how to do it globaly: http://api.jquery.com/ajaxError/ or individualy set 'error' option of ajax request.


Q:

phonegap on android unable to connect in corporate network

Problem: I can see the URL opens in Android browser but phonegap app always says A network error occurred.
I had seen reference to this question at multiple locations, tried every solution I encountered and still didn't find a solution. I am trying to load a webpage served by intranet into phonegap app on android using following code:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init();
    //WebView.enablePlatformNotifications(); // Enable proxy
    //setContentView(R.layout.main);
    //super.loadUrl("file:///android_asset/www/index.html");
    this.setIntegerProperty("loadUrlTimeoutValue", 60000);
    super.loadUrl("http://10.32.147.28:9080/MYWeb/IndexView.do");
}

I tried commenting and uncommenting many possible combinations above.
Here is the configuration: cordova_1.8.0.jar inside the app. cordova1.8.0.js is served by the page above and is not stored locally.
Appreciate any help.

A:

Have you set your application whitelist appropriate? You will need to whitelist your server IP.
http://docs.phonegap.com - on the left side, Domain Whitelisting Guide.


Q:

Encoding in Java

I have a string with special characters in Java.
"[^\\"]*\\"

I want to convert it to HTML entities like this:
"[^\\"]*\\"

How this could be achieved in Java?

A:

Use String.replace() as needed:
"[^\\\"]*\\".replace("\"", """);


Q:

Two-Way Parent Child Communication Using 2 Pipes in C on Linux

I'm trying to create a two-way communication between parent and child processes using 2 pipes using C on Linux. The parent is my program and the child is just a random program (say "cat").
I try to uses read() in parent to read child output, but it gives me errno 9, which is Bad file descriptor.
The following is my code
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define Read            0
#define Write           1
#define ParentRead      read_pipe[1]
#define ParentWrite     write_pipe[0]
#define ChildRead       write_pipe[1]
#define ChildWrite      read_pipe[0]

int main()
{
    int data_processed;

    /** Pipe for reading for subprocess */
    int read_pipe[2];
    /** Pipe for writing to subprocess */
    int write_pipe[2];

    char buffer[100];
    memset(buffer, '\0', 100);

    if (pipe(read_pipe) == 0 && pipe(write_pipe) == 0)
    {
        pid_t pid = fork();
        if (pid == (pid_t)-1)
        {
            fprintf(stderr, "Fork failure");
            exit(EXIT_FAILURE);
        }
        else if (pid == (pid_t)0) //Child process
        {
            close(Read);
            close(Write);
            close(ParentRead);
            close(ParentWrite);
            dup(ChildRead);
            dup(ChildWrite);
            execlp("cat", (char*)NULL);
            exit(EXIT_FAILURE);
        }
        else { //Parent process
            close(ChildRead);
            close(ChildWrite);

            write(ParentWrite, "abc", 3);
            int r = read(ParentRead, buffer, 99);
            printf("%d %d", r, errno);
            puts(buffer);
        }
    }

    exit(EXIT_SUCCESS);
}

A:

If you want to redirect stdin and stdout to pipes, you need to use dup2(2) system call.
dup2 (ChildRead, 0);
dup2 (ChildWrite, 1);

P.S.
Also I found wrong directions of reading/writing in pipes. Here is the correct way
#define ParentRead      read_pipe[0]
#define ParentWrite     write_pipe[1]
#define ChildRead       write_pipe[0]
#define ChildWrite      read_pipe[1]

Remember: pipe[0] is fd for reading, pipe[1] is fd for writing.
And one more error, in execlp. Do not forget to set the first argument you send to the executed programm as a name of the program
execlp("cat", "cat", (char*)NULL);


Q:

The difference between Plus and Minus

So i'm a newbie in Java and im just trying out simple stuff out in Java.
For Me This does not make much of a sense and google is not really helping me.
The Picture will probably tell my Problem exactly:

So i do not understand when you are doing a subtraction, why its not - and instead you still write the + sign.
if (userInput.hasNextInt())
        {
        int eingZahl = userInput.nextInt();

        System.out.println("Deine Eingegebene Zahl ist " + eingZahl);

        int plusRechnen = eingZahl + eingZahl;

        System.out.println(eingZahl + " + " + eingZahl + " = " + plusRechnen);

        int minusRechnen = eingZahl - eingZahl;

        System.out.println(eingZahl + " - " + eingZahl + " = " + minusRechnen);

    }

    else {

        System.out.println("Bitte Eine Zahl Eingeben!");

A:

In mathematics the + operator is the addition operator so 1+2=3 and 3.5+1=4.5 etc.
Sometimes though we want to concat strings together so we want to print to the console the value of eingZahl followed by character - followed by eingZahl followed by = followed by minusRenchen.
Reasonably concat is a different operator than addition so it should have been different but Java instead uses + for concat, even if + sounds logical only for numbers still Java in string context interpret it as concat, so to acheive what we want we do this :
System.out.println(eingZahl + " - "+eingZahl + " = " + minusRenchen);

If you want to understand better Imagine that Java chose a unique operator for string concatenation like the dot for example : eingZahl . " - " . eingZahl . " = " . minusRenchen, php did this, Java didn't :) .
You can go far and say that adding a number to a string isn't reasonable as well but Java when you add anything to a string it convert this "anything" to a string and perform concat, this is a matter of convenience to let us express more in less words, otherwise we would have to write this :
System.out.println(Integer.toString(eingZahl).concat(" - ").concat(Integer.toString(eingZahl)).concat(" = ").concat(Integer.toString(eingZahl)));

Obviously the first statement is more readable as long you remember what + does with strings.
By the way many languages let you put expressions right inside the string, something like this : "$eingZahl - $eingZahl = $minusRenchen" and result "1-1=0" when eingZahl equals 1, notable examples of those languages include some which can interoperate with java code seemlessly like Kotlin and Scala :) .


Q:

Differentiating both sides of an equality with respect to first variables? (Not answered)

I am proving a statement and the truth of the following proposition would help me with it. If anyone could say whether the proposition is true and give a hint how to prove it I would be very much thankful. I do not know where to start.
Proposition: Assume that $\exists$ a pair $(a,b)$ such that $f(a,b)=g(a,b)$ for the functions $f(x,y)$ and $g(x,y)$ both mapping from $R^2$ to $R^2$. Can I say that if so, then $d/dx f(x,y)=d/dx g(x,y)$ at those values?
$\mathbf A$$\mathbf D$$\mathbf D:$
$a\neq b$
Thanks in advance!

A:

No, you cannot. Let $f(x,y)=xy$ and $g(x,y)=x^2y^2$. Then $f(1,1)=g(1,1)$, but $\frac{\partial f}{\partial x}(1,1)=1$ and $\frac{\partial g}{\partial x}(1,1)=2$
Addendum: Letting $f(x,y)=x(y-1)$, $g(x,y)=x^2(y-1)^2$, and $(a,b)=(1,2)$ gives a counterexample where $a\neq b$. In fact, the property you want is usually false; the values $f(a,b)$ and $g(a,b)$ say nothing about their partial derivatives at that point.


Q:

Favored class bonus scaling overpowered?

The favored class option system says..

Finally, some of these alternate favored class benefits only add +1/2, +1/3, +1/4, or +1/6 to a roll (rather than +1) each time the benefit is selected [...]
In most cases, these benefits are gained on a level-by level basis—your character gains the specified incremental benefit each time she gains a level. Unless otherwise noted, these benefits always stack with themselves.

And they present an example:

Finally, some of these alternate favored class benefits only add +1/2, +1/3, +1/4, or +1/6 to a roll (rather than +1) each time the benefit is selected; when applying this result to the die roll, round down (minimum 0). For example, a dwarf with Rogue as his favored class adds +1/2 to his trap sense ability regarding stone traps each time he selects the alternate Rogue favored class benefit; though this means the net effect is +0 after selecting it once (because +1/2 rounds down to +0), after 20 levels this benefit gives the dwarf a +10 bonus to his trap sense (in addition to the base value from being a 20th-level Rogue).

I bold both parts of interest. Can I select a +1/2, +1/3, +1/4 bonus benefit multiple times?
Some FCO flat bonuses clearly say what their caps are:

Paladin: Add +1 to the paladin's energy resistance to one kind of energy (maximum +10).

And even some other +x/y got that (bolded):

Mesmerist: Increase the mesmerist's towering ego bonus by 1/3 point (to a maximum increase of +2)

Now if I got for example the rogue's of the example

Rogue: Add a +1/2 bonus on Disable Device checks […]

This mean that … I can take it multiple time, it's got no cap and it stacks with itself?
So what happen if I chose to select each level in the favored class the "Favored class option"?
Ll 1 - ( +1/2 ) bonus to Disable device  = lvl * 1/2 = +0
Lv 2 - ( +1/2 ) bonus to Disable device  = lvl * 2/2 = +2
Lv 3 - ( +1 HP) bonus to disable device  = lvl * 2/2 = 3 * 2/2 = 3
Lv 4 - ( +1/2 ) bonus to disable device  = lvl * 3/2 = 4 * 3/2 = 6
Am I overlooking something in this otherwise OP mechanic?

A:

You are missing a very important clause in the example:

For example, a dwarf with Rogue as his favored class adds +1/2 to his trap sense ability regarding stone traps each time he selects the alternate Rogue favored class benefit;

(emphasis mine)
The dwarf is selecting this bonus to trap sense each time he selects a favored class benefit, that is, every time he takes a level in rogue.
That means that when he takes his first level in rogue,

this means the net effect is +0 after selecting it once (because +1/2 rounds down to +0),

but after taking 20 levels of rogue and selecting the bonus 20 times,

after 20 levels this benefit gives the dwarf a +10 bonus to his trap sense (in addition to the base value from being a 20th-level Rogue).

The bonus is +½. Not half of something, especially not half of your level, but literally a half bonus each time you select it. That means you need to select it twice to actually see a benefit, and the bonus in this example, for trap sense, is +10 because it was selected 20 times, not +10 for selecting it once and then just being 20th level.

A:

Nowhere do these bonuses say they scale by level. They don't. When it says +1/2 bonus to a skill? It means only that +1/2 bonus. If you ever want to get any more of a bonus, you have to take it again.

A:

You seem to read 1/2 wrong.
1/2 does not mean 1 per 2 Levels, but a flat bonus of 0.5 (rounded down as per the rules) which means if you only take the Bonus once, it will stay at 0.5 (rounded down = 0), no matter what Level you are.
The example with the dwarf is poorly phrased, as it implies, but never actually tells you, that the dwarf chooses the Bonus at every Level, resulting in a total Bonus of +10. I think (but cant check at the moment) that they fixed it in the german translation i have at Home...
Also, even though it is no complete evidence and might technically happen with other stats too (e.g. Saving Throws, as pointed out in the comments): there are some bonuses that give you 1/3 as a bonus. If it scaled by Level, you would have about +6.66 (rounded down) as a bonus on Level 20, which would waste 2 Levels completely.


Q:

What is the relationship between Ubuntu Single Sign On and Launchpad Login Service?

Canonical operates at least two OpenID based login services within the Ubuntu online world: Ubuntu Single Sign On and the Launchpad Login Service. According to the information in the footer of both sites they share the same backing software which is called Canonical SSO provider.
My question is whether these two sites are entirely separate implementations or do they share the same user database? Alternatively, is there some other less direct relationship between the two services?
In other words, if I didn't have an account with either service and I created a new account with Ubuntu Single Sign On would I then also have a Launchpad Login Service account? What about the inverse scenario?
I know that the Launchpad Login Service existed earlier than Ubuntu Single Sign On. I also know that I was able to use my existing Launchpad login details with the Ubuntu SSO when it was launched. However, I've never been clear if these are the same account or if my Launchpad account was copied to the newer service and they are now separate.

A:

Afaik Launchpad and Ubuntu SSO are the one and same user/password database. In this sense they're like a Google account or Yahoo account that uses the same username and password for multiple services/sites.
Note: If you login to http://login.ubuntu.com you can manage your launchpad OpenID options.

A:

Yes, they share the same DB.  You only need one login for everything in Ubuntu.  I think it's actually that it was Launchpad Login Service and then they went and made it broader but the old name is still sitting around in some places and just hasn't been updated.

A:

Ubuntu SSO will replace LP's login service.
Source: https://login.ubuntu.com/+description and https://login.ubuntu.com/+faq


Q:

Changing the location of the components folder

In Visual Studio 2012, I am using a Xamarin.iOS project type and when I add components to a project, they're added to the folder: [Solution-directory]/Components/[component-name]/
Is it possible to choose where the components are stored?
My dependency management strategy is to store the dependencies outside of the project and solution area in their own folder.
I guess I could rip out the DLL from the /lib/ folder within the component directory, but I am wondering if there is an easier solution.

A:

You can specify the components directory with a components.config file. This is detailed here regarding Xamarin Studio, but I just tested this myself by having it in the root of the solution directory, and it did work.


Q:

RequestFactory's Entity Relationships

The details of the Request's with() implementation of RequestFactory in GWT is a bit unclear to me. See here for the official documentation.
Question 1:

When querying the server, RequestFactory does not automatically
  populate relations in the object graph. To do this, use the with()
  method on a request and specify the related property name as a String.

Does this mean that if the Entity at the server uses Lazy Fetching, the returned EntityProxy will have all the requested objects specified in with()? It seems a bit odd to instantiate the whole object graph of the Object server side, to only send a small piece to the client.
Question 2:
Does req.with("foo").with("foo"); do the same as req.with("foo"); ?
Question 3:
Does req.with("foo").with("bar"); do the same as req.with("foo","bar"); ?
NOTE: I'm having a really hard time finding the implementation details of with() in the source code and the API doesn't help me either.

A:

Question 1:
It probably depends on your server side implemenation.
The with invocation will only make sure that the corresponding getter (getFoo()) is called shortly before the RF call returns to the client.
That's the reason why you also have to make sure to use an OpenSessionInView pattern, otherwise you might run into NullPointeterExceptions.
Question 2:
I guess the Request<T> implements a builder pattern.
The end-result will be the same.
However I am not sure if the getter() will be called twice or if the with method will check if the getter is already requested.
Question 3:
Yes it's the same.
As a sidenote. You can use req.with("foo.bar").
On the backend this will lead to a getFoo().getBar() call.


Q:

My program will be crashed after a few seconds . why?

It works for a few seconds and suddenly will be crashed.
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class CanvasUnit extends Canvas {

    private Timer timer;
    private TimerTaskClass task;
    private int Top=13 , Left=48;
    private int width = getWidth();
    private int height = getHeight();
    private static int SWidth = 10;
    private static int SHeight = 10;
    private int LStep = 5;
    private int TStep = 5;

    public CanvasUnit() {
       timer = new Timer();
       task = new TimerTaskClass();
       timer.schedule(task,10);
    }

    public void paint(Graphics g) {

        g.setColor(0,0,0);
        g.fillRect(0, 0, width, height);
        g.setColor(255,255,255);

        g.drawRect(Left, Top, SWidth, SHeight);
    }
   private class TimerTaskClass extends TimerTask{

    public final void run(){

      if (Left > (width - SWidth)) {
        LStep = LStep * (-1);
      } else if (Left < 0) {
        LStep = Math.abs(LStep);
      }
      //
      if (Top > (height - SHeight)) {
        TStep = TStep * (-1);
      } else if (Top < 0) {
        TStep = Math.abs(TStep);
      }

      Left = Left + LStep;
      Top = Top + TStep;

      repaint();

      //Run the timer agian
      timer = new Timer();
      task = new TimerTaskClass();
      timer.schedule(task,10);
    }

   }
}

A:

Sorry my previous comments were not correct because I thought you are using LWUIT, don't know from where I got this idea. You should use something similar to this
import javax.microedition.lcdui.*;

public class CanvasUnit extends Canvas {

    private int Top = 13, Left = 48;
    private int width = getWidth();
    private int height = getHeight();
    private static int SWidth = 10;
    private static int SHeight = 10;
    private int LStep = 5;
    private int TStep = 5;

    public CanvasUnit() {
        Thread t = new Thread(new Runnable() {

            public void run() {
                while (true) {

                    if (Left > (width - SWidth)) {
                        LStep = LStep * (-1);
                    } else if (Left < 0) {
                        LStep = Math.abs(LStep);
                    }
                    //
                    if (Top > (height - SHeight)) {
                        TStep = TStep * (-1);
                    } else if (Top < 0) {
                        TStep = Math.abs(TStep);
                    }

                    Left = Left + LStep;
                    Top = Top + TStep;

                    repaint();

                    try {
                        Thread.sleep(10);

                    } catch (Exception ex) {
                    }
                }
            }
        });
        t.start();
    }

    public void paint(Graphics g) {

        g.setColor(0, 0, 0);
        g.fillRect(0, 0, width, height);
        g.setColor(255, 255, 255);

        g.drawRect(Left, Top, SWidth, SHeight);
    }

}


Q:

Displaying data from json file

I'm trying to get content from a json file, but until now I get nothing.
I have the status connection == 200 and I can see the content in the chrome console
but I get nothing when I try to display the data to html table, but when I use  the same jquery code with api from another service like import.io things works fine.
Can you tell me what am I doing wrong?
This api is from kimonolabs.
$(document).ready(function () {

    var tabel = '

Calendário

';
    tabel += '' + 'Hora' + '	' + '' + 'Equipas' + '	' + 'jornda' +
        '	' + 'Data' + '	';

    $.ajax({
        type: 'GET',
        url: 'https://api.myjson.com/bins/1dm6b',
        dataType: 'json',
        success: function (data) {
            console.log(data);

            $('#update').empty();

            $(data.m_Marcadores).each(function (index, value) {
                tabel += '
' + this.posicao + '	' + '' + this.golos + '
';
            }); //each

            tabel += '
';

            $("#update").html(tabel);

        } //data

    }); //ajax
}); //ready

A:

According to JSON structure you should iterate over data.results.m_Marcadores array:
$(data.results.m_Marcadores).each(function (index, value) {
    tabel += '
' + this.posicao + '	' + this.golos + '
';
});

Another problem. In header of the table you setup 4 colums, but in loop you are creating only two of them. Number of header columns should be the same as other row td.
Also you need to wrap th elements in tr. For example, fixed table header:
var tabel = '
' +
            '

Calendário

' +
            '
' +
                'Hora	Equipas	jornda	Data	' +
            '
';

Demo: http://jsfiddle.net/onz02e43/


Q:

Application Insights picks up SQL telemetry locally but not in a real environment

Generally I've had pretty good luck with Application Insights' auto-detection of a SQL dependency.  However, in a recent case where we added Application Insights to a Web API project, we are not seeing dependency tracking for SQL Server in the portal.  Version info:
 Application Insights 2.5.0
 Entity Framework 6.x
 .NET 4.5.2

The funny thing is that Azure will automatically pick up SQL calls when developers are using the debugger from Visual Studio.  What do we need to do to capture timings for SQL calls on a real environment?
Thanks,
BGU

A:

The solution was to upgrade the Web API project to a more recent version of .NET (4.6 or higher).  Good luck out there.


Q:

Config mailer in Symfony 1.4 - how in admin panel, not factories.yml?

How can i do configuration of emails in admin panel in Symfony?
Default i must set this in file factories.yml:
mailer:
  class: sfMailer
  param:
    logging:           %SF_LOGGING_ENABLED%
    charset:           %SF_CHARSET%
    delivery_strategy: realtime
    transport:
      class: Swift_SmtpTransport
      param:
        host:       localhost
        port:       25
        encryption: ~
        username:   ~
        password:   ~

I would like set host, port, encryption, username and password in admin panel and keep this in my database. So how can i get this data from database if i send mail?
    $message = $this->getMailer()->compose(
      array('jobeet@example.com' => 'Jobeet Bot'),
      $affiliate->getEmail(),
      'Jobeet affiliate token',
      <<<EOF
Your Jobeet affiliate account has been activated.

Your token is {$affiliate->getToken()}.

The Jobeet Bot.
EOF
    );

    $this->getMailer()->send($message);

I can get this data from database :) but i dont know how to write in to getMailer().

A:

There is an event fired when the mailer is configured.
$dispatcher->notify(new sfEvent($this, 'mailer.configure'));

So you can add a listener on this event, retrieve the mailer object, and re-configure it.
Or, as describe in this snippet, you can built manually the call to the mailer and define how you set the config (and got the advantage to use getMailer in a task): http://snippets.symfony-project.org/snippet/377


Q:

Temperature converter doesn't return correct value

         IDENTIFICATION DIVISION.
         PROGRAM-ID. TEMP1 .
         ENVIRONMENT DIVISION.
         DATA DIVISION.
         WORKING-STORAGE SECTION.
         01  WS-A PIC 9(2).
         01  WS-B PIC 9(2).
         PROCEDURE DIVISION.
             ACCEPT WS-A.
             COMPUTE WS-B ROUNDED = ( ( 9 / 5 ) * WS-A ) + 32.
             DISPLAY WS-B.
             STOP RUN.

This is my program for accepting temperature in Celcius and converting it to Fahrenheit. I have created a LOADLIB and a COPYLIB. Also one JCL for compilation and RUNJCL. No error is coming, but when I give any input (e.g. 98) in RUNJCL, it always shows 32 as output. What is the problem?

A:

If the result you are getting is always 32, then WS-A is zero, because something multiplied by zero and adding 32 will always be 32.
I suspect that you have in your JCL something like this:
//SYSIN DD *
00212

When you do the ACCEPT, you will only get 00 from that.
When using ACCEPT for little testing programs it is a good idea to DISPLAY what you get, so you can see.
Either make WS-A larger, or the value on the card following your SYSIN smaller.
It if also possible you have other problems causing the value of WS-A to be treated as zero. So, can you paste the JCL from file 2 on the spool for your JOB. With the line-numbers it generated :-)
And the SYSIN card data (your 98). Look out particularly for any "SYSIN generated" statements in your JCL output.
Here's your program. I've got rid of unnecessary things, and changed the names of WS-A and WS-B. Now that WS-B has a proper name, you can see as you create it that it is the wrong length, it needs to be at least three digits.
   ID DIVISION.
   PROGRAM-ID. TEMP1.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  INPUT-CENTIGRADE                    PIC 9(2).
   01  OUTPUT-FARENHEIT                    PIC 9(3).
   PROCEDURE DIVISION.
       ACCEPT                       INPUT-CENTIGRADE
       DISPLAY
               "CELSIUS COMING IN "
               ">"
                                    INPUT-CENTIGRADE
               "<"

       COMPUTE OUTPUT-FARENHEIT ROUNDED
                                    = ( ( 9 / 5 )
                                        * INPUT-CENTIGRADE )
                                      + 32

       DISPLAY
               "FARENHEIT GOING OUT "
               ">"
                                    OUTPUT-FARENHEIT
               "<"
       GOBACK
       .

The output from running the program is:
CELSIUS COMING IN >98<
FARENHEIT GOING OUT >208<

Running this version of your program with "0098" for input gives this:
CELSIUS COMING IN >00<
FARENHEIT GOING OUT >032<


Q:

How fast should a dynamically generated web page be created?

I have a number data-driven web based applications that serve both internal and public users and would like to gauge how fast you would expect a page to be created (in milliseconds) in order to maintain user satisfaction and scalability.
So, how fast does a page have be created to maintain a fast site?
The sites are developed in ASP classic, with a SQL Server backend generating XML recordsets that I render using XSLT.  Not the most efficient technique and pages take between 7ms to 120ms to create (i.e. Timer interval between first line of code and the 'Response.Write') depending on the complexity of the page.  Slower pages are due to the database running bigger and more complex queries.  Even if I re-wrote all the ASP classic to ASP.NET there will not be any significant improvement to the overall page render speed.
I've often heard Jeff say he wants SO to be the fastest site, and his blogs have discussed optimisation of his code and database but how far do you have to go in optimising your the code?  Is shaving off milliseconds by using StringBuffer instead of String + String a good use of my time?
[Clarification]
At what point do you start to think "This page is taking too long to create?".  Is it over 20ms, over 200ms or is it OK for a page to take over a second to build?  What are your "target times?"

A:

This depends entirely on your audience and targets - I've worked on apps with a target 'onload' event at <4secs, and on apps where the time on server is expected to be <1ms. It can go either way - but whatever you do you need to be aware that whatever performance optimisations you do at the server-side level are likely to be dwarfed by both network performance, still the major bottleneck with the web, and perceptive load times.
Yahoo has some excellent guidelines for general website performance, especially on the perceptive load area.
Hopefully you're already smart enough to be caching what you can and doing the little things like avoiding massive chains of Response.Writes...


Q:

301 redirect with subdomain

I have put the following content in my .htaccess file. What I want is redirect all mydomain.com/ to www.mydomain.com/. At the same time I want subdomain.mydomain.com/ should not get redirected anywhere. With the below code, I am able to achieve my 1st goal. But it redirects http://subdomain.mydomain.com/ to http://www.mydomain.com/subdomain. Please guide me on how to achieve both my modifying .htaccess.
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.mydomain.com$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]

A:

Make it more restrictive, i.e. apply rule only when host name is mydomain.com:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]


Q:

If statement involving modulo behaving erratically

I'm making a function to create a list of prime numbers from 0 to num. I start off with a list of integers from 2 to num, and iterate over each one that goes from 2 to i < num; if at any point item % i === 0, the item is removed from the list. This works fine:
function getPrimes(num) {
  // get list of ints from 2 to num
  let primes = [...Array(num + 1).keys()];
  primes = primes.splice(2);
  let lastNumber = primes[primes.length - 1];
  // make iterable, run its loop
  // for each number in primes
  for (let number of primes) {
    // use iterable to remove if not prime
    for (let i = 2; i < num; i++) {
      if (number % i === 0) {
        primes.splice(primes.indexOf(number), 1);
      }
    }
  }
  // add back two
  primes.unshift(2);
  return primes;

But when I try and make the iterable for each number only to up to Math.floor(num / 2) for the sake of efficiency, it breaks the code somehow:
function getPrimes(num) {
  // get list of ints from 2 to num
  let primes = [...Array(num + 1).keys()];
  primes = primes.splice(2);
  let lastNumber = primes[primes.length - 1];
  // make iterable, run its loop
  // for each number in primes
  for (let number of primes) {
    // use iterable to remove if not prime
    for (let i = 2; i < Math.floor(num / 2); i++) {
      if (number % i === 0) {
        primes.splice(primes.indexOf(number), 1);
      }
    }
  }
  // add back two
  primes.unshift(2);
  return primes;

When I tried it out, getPrimes(10) gives me [ 2, 3, 5 ]. So seven is missing from the list of prime numbers from 0 to 10. Why is that? I checked and 7 modulo 2, 3, and 4 returns 1, 1, and 3, respectively. So why is the code in the loop running that removes 7 from primes? It's the only place in the code where I put that I wanted to remove a number from the array.

A:

The first issue is that you are looping while removing items, which causes some items to be skipped. Loop backwards instead, so that only items that have already been checked are shifted. Second, num / 2 should be changed to Math.sqrt(number), as that is the maximum factor that needs to be checked before we can be sure that a number is prime. With this method, there is no need to add 2 back to the array.

function getPrimes(num) {
  // get list of ints from 2 to num
  let primes = [...Array(num + 1).keys()];
  primes = primes.splice(2);
  let lastNumber = primes[primes.length - 1];
  // make iterable, run its loop
  // for each number in primes
  for(let i = primes.length - 1; i >= 0; i--){
    let number = primes[i];
    // use iterable to remove if not prime
    for (let j = 2; j * j <= number; j++) {
      if (number % j === 0) {
        primes.splice(i, 1);
        break;
      }
    }
  }
  return primes;
}
console.log(...getPrimes(10));


Q:

Table griding HTML2PDF

I want to generate HTML table into PDF.
But I'm having trouble for gridding the table. I want to generate table like this:

I have this table from database:

Which is should fill this column:

and I have a second table from database like this:

which is should fill the rest of the columns except keterangan column.
I tried this code :

    Nomor
    Pemberian entertaiment dan sejenisnya
    Relasi usaha yang diberikan entertainment dan sejenisnya
    Keterangan

    Tanggal
    Alamat
    Jenis
    Jumlah
    Nama
    Posisi
    Nama Perusahaan
    Jenis Usaha

        <?PHP echo $row->nomor?>

        <?PHP echo $row->tanggal?>

        <?php echo $row->alamat?>

        <?PHP echo $row->jenis?>

        <?PHP echo $row->jumlah?>

    <?php
            foreach ($list->result() as $data){
        ?>

                <?PHP echo $data->nama?>

                <?PHP echo $data->posisi?>

                <?PHP echo $data->nama_perusahan?>

                <?PHP echo $data->jenis_usaha?>

        <?php
            }
        ?>

            <?PHP echo $row->keterangan?>

but this is the result :

A:

Try this:

    Nomor
    Pemberian entertaiment dan sejenisnya
    Relasi usaha yang diberikan entertainment dan sejenisnya
    Keterangan

    Tanggal
    Alamat
    Jenis
    Jumlah
    Nama
    Posisi
    Nama Perusahaan
    Jenis Usaha

        <?PHP echo $row->nomor?>

        <?PHP echo $row->tanggal?>

        <?php echo $row->alamat?>

        <?PHP echo $row->jenis?>

        <?PHP echo $row->jumlah?>

    <?php
            foreach ($list->result() as $data){
        ?>

                <?PHP echo $data->nama?>

                <?PHP echo $data->posisi?>

                <?PHP echo $data->nama_perusahan?>

                <?PHP echo $data->jenis_usaha?>

        <?php
            }
        ?>

            <?PHP echo $row->keterangan?>

Note the extra columns are added inside the loop to enable it to line up with you headers.


Q:

Meteor.Render or Template?

Just wondering when rendering a list of items.
Is it best for the performance to use Meteor.RenderList and Meteor.Render, or should I try to use Templates as much as possible?

A:

i use Template {{#each}} and Meteor.render with a backbone router.
i make a function wrap Meteor.render like this
render: (where, which, options) ->
    self = @
    self.options = options
    $ where.empty().html Meteor.render Template[which]

then inside backbone router it looks like
routes:
    '': 'home'

home: ->
    render 'body', 'page-home'

and a page-home.html include template and {{#each}} to get my list.
<template name="page-home">
    {{> module-streams-list}} blah blah blah
</template>

i want to know how people deal page Meteor.render/Meteor.renderList with routing too.


Q:

iPhone keyboard handling with custom textfield?

Is it possible to create a custom textfield on the iPhone?  What I would like to do is have an "alertview" that looks like it fits in with the app design and using an image as the dialog box/alert, not just the standard alertview.  So, I'll handle all the graphics and input handling, but how does one pop up the keyboard and deal with input without creating a TextField?
Side question - is this going to run afoul of Apple's input standards?
Thanks in advance,
Ben

A:

UITextField is already very customisable. I'm not sure you need to sub-class it.
In addition to its own properties to control the text and overlays, UITextView is a subclass of UIView so you can control the background colour and add your own subviews. If you do the latter, you must be careful about breaking the event handling within UITextView.
UITextView also handles all the keyboard behaviour you should look at UIKeyboardWillShowNotification and related notifications.
Nobody can say what Apple will and won't accept but as long as your custom UI is clear and usable, you should be OK


Q:

Summing Rows in Matrices created by lapply

I'm brand new to R and I'm trying to figure out how to sum the rows from the following output.
u <- c(1,2,3)
x <- lapply(u, replicate, rbinom(10,1,.5))

When I do this x is equal to
[[1]]
      [,1]
 [1,]    0
 [2,]    0
 [3,]    1
 [4,]    1
 [5,]    0
 [6,]    1
 [7,]    1
 [8,]    1
 [9,]    1
[10,]    0

[[2]]
      [,1] [,2]
 [1,]    0    1
 [2,]    0    1
 [3,]    1    0
 [4,]    1    1
 [5,]    1    1
 [6,]    1    1
 [7,]    1    1
 [8,]    1    0
 [9,]    1    0
[10,]    0    0

[[3]]
      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    1    1    1
 [3,]    1    0    1
 [4,]    1    0    1
 [5,]    0    0    1
 [6,]    0    0    1
 [7,]    0    1    0
 [8,]    1    1    1
 [9,]    0    1    1
[10,]    0    1    1

When I use the coding
rowSums(x)

or
rowSums(x[2])

I get this error
Error in rowSums(x) : 'x' must be an array of at least two dimensions

How can I sum the rows?  Also, is there a way to break up the tables so that I can do individual analysis.  Preferably a way that is not manual so I can use it if I have 100+ tables

A:

A loop over the individual elements of the list is conveniently performed using lapply(). You could try this:
lapply(x, rowSums)
#[[1]]
# [1] 0 1 0 1 1 0 1 1 1 0
#
#[[2]]
# [1] 2 1 2 2 1 2 1 1 0 1
#
#[[3]]
# [1] 1 1 2 1 1 0 1 1 1 1

data:
u <- c(1,2,3)
set.seed(123)
x <- lapply(u, replicate, rbinom(10,1,.5))


Q:

Normalised coordinates for OpenGL

I was trying to clip an image on my screen by limiting the viewing volume using glFrustum. In the official documentation for Glfrustum, it is mentioned that the left, right, top, bottom, near, far are the coordinates for the clipping. I thought them to be screen coordinates and tried doing:
glFrustum(100, 924, 100, 668, 3, 1000);

The above wasn't showing anything to me on the screen. So, I just looked up somewhere and saw some code as follows (but why are those coordinates negative?):
glFrustum(-1, 1, -1, 1, 0.5, 1000);

I used the excat same thing and started getting some portion of the image on the screen. Subsequently, I treied fiddling with coordinates for near and noticed how viewing volume changes.
glFrustum(-10,10,-10,10,10,1000);
glFrustum(-100,100,-100,100,100,1000);
glFrustum(-0.5,0.5,-0.5,0.5,0.5,1000);

All the above were giving the same output of the images to me on the screen. But most of the places where I have observed glFrustum being used, I noticed the values being used somewhere from [-1,1] (such as here) and folks talking about calculations in the normalised range. Why is doing the calculation for left, right, bottom, top, near, far important (near and far also included in normalised values?) in terms of normalised values? Can the same operations be performed using the values in screen coordinates as well?

A:

NOTE: This question and answer is only valid for older (before version 3) OpenGL.

First of all, glFrustum is independent of your screen resolution.
This function define a volume in which the scene will be drawn, that is, all element of your screne that throw outside this volume will be ignored/cut.
Coordenates for glFrustum are relative to your scene, not to your screen.

Take in consideration that for a correct representation, other parameters must be configured correctly like scene rotation/translation, etc.

glFrustum(-10,10,-10,10,10,1000);
glFrustum(-100,100,-100,100,100,1000);
glFrustum(-0.5,0.5,-0.5,0.5,0.5,1000);

All the above were giving the same output of the images to me on the screen

Not exactly, if your 3D model is near the POV (camara), example 2 will cut it where example 3 will not. But as you increment/reduce the "near" distance in proportion to "left", "top", "bottom" and "right", the result is similar.


Q:

Error installing 1.9.3 with RVM on Lion

I have burned an embarrassing number of hours trying to install ruby and rails on Mac.
I am using Lion 10.7.2, Xcode 4.2.1, rvm 1.10.0, and gcc 4.2.1
Does anyone have a surefire way to install ruby with rvm. Or, is there
rvm install 1.9.2 -C --with-readline-dir=$rvm_path/usr --with-iconv-dir=$rvm_path/usr

Produces the error
make[1]: *** [../../.ext/x86_64-darwin11.2.0/tcltklib.bundle] Error 1
make: *** [mkmain.sh] Error 1

Running
rvm install 1.9.3-p0  --with-gcc=clang

Produces the error
make: *** [.rbconfig.time] Abort trap: 6

Simply running
rvm install 1.9.3

Produces the error
make[2]: *** [../../.ext/x86_64-darwin11.2.0/tcltklib.bundle] Error 1
make[1]: *** [ext/tk/all] Error 2
make: *** [build-ext] Error 2

From reading this, I ran the below in the Terminal and my Mac would not restart until I put the libiconv.2.dylib back in place using Target Disk Mode.
rm /usr/local/lib/libiconv.2.dylib
ln -s /usr/lib/libiconv.2.dylib /usr/local/lib/libiconv.2.dylib

From this link, I also removed a previous install of Macfuse which is known to cause problems
I have reinstalled Xcode twice [Install Xcode from the Application Folder].
Is there another way to get Ruby Installed on Lion?
Many thanks as I'm fast running out of ideas
Graham

A:

The following worked for me:
$ rvm install 1.9.3 --with-gcc=clang

I got that from this page.

A:

I had this problem too and tried several of the listed solutions unsuccessfully. Then I downloaded XCode 4.3.1 for Lion and the Xcode command line tools update (dated March 7, 2012) from Apple's developer site and just re-ran 'rvm install 1.9.3'. Worked perfectly and installed 1.9.3p125.
Hope this helps


Q:

Find data within specific dates?

I'm learning database, and i have 2 questions:
How can I find out the how many Employees visited the shop in January 2010?
Table is as follows:
X:Employees(PK),VisitDate, EmployeeNumber(FK)
Y:EmployeeNumber
SELECT * FROM `X` WHERE `VisitDate ` BETWEEN '2010-01-01' AND '2010-01-31'

This just shows the data of people who visited between certain month, is it possible to find out the total amount of people?
Second Question is:
How can I use JOINS to show the EmployeeNumber as well as how many employees visited the shop in January 2010?

A:

To show the number of people visiting in January, you just need to modify your SQL as follows.
SELECT *
FROM
(
    SELECT EmployeeNumber, COUNT(1) AS TotalAmountOfVisitor
    FROM X
    WHERE VisitDate BETWEEN '2010-01-01' AND '2010-01-31 23:59:59'
    GROUP BY EmployeeNumber
) AS RefTable
INNER JOIN Y ON RefTable.EmployeeNumber = Y.EmployeeNumber

Thanks @zerkms for correcting.


Q:

Bind an event handler on a element who's inserted by the jQuery .html() function

I render some new content with .html() after ajax call into my site.
$.getJSON(scriptURL, $("#domainForm").serialize(), function(data) {
  $("#checkedDomain").html(data['html'])
});

Now. How can I bind an event handler to div tags in that replaced html without including the script again?
now the html the I render into my site looks like this:


Q:

Format String in Alias

Unable to get the result I seek using the alias script below:
alias cfb="ps -eaf | grep PRD_ | egrep startscen.sh | awk '{print $2\"\t\"$14}'"

some sort of a format issue with \ - Can anyone help?

A:

You can try something like this:
alias cfb=$(echo -e "ps -eaf | grep PRD_ | egrep startscen.sh | awk '{print \$2\"\t\"\$14}'")
It's a bit difficult to test it without you saying 1) what is the result you seek, 2) providing a testable reproducible example.


Q:

Scrapy loader data "disappearing" at input processor

I'm using Scrapy to extract certain price data from a website. The site's data always looks like:
Amazon Price: x円

or,
Search Price: x円

where x is a currency-formatted number without a decimal portion. I have a regular expression I'm using to extract this field, inside an item loader:
loader.add_css(Product..re(r'(?<=[(Amazon Price)(Search Price)]:\s)[,\d]+(?=円)')

Every test case I have run from the website I'm scraping shows that this regular expression works. In my item class I have:
price = Field(input_processor = Compose(lambda v: print(v), Join(separator = '')),
    output_processor = Compose(TakeFirst(), lambda v: print(v), lambda v: v.replace(',', ''), lambda v: int(v)),
    serializer = int)

where the print statements are being used for debugging output (if anyone knows a better way, I'd appreciate hearing about it). Since this field can be run from multiple spiders, where some might assign a list of integers-as-strings to price, I am using Join(separator = '') to collate them in that case. I have verified that this works as well. In output, I am usingTakeFirst()to get what should be the only element on the array, removing any commas withreplace(',', '') and casting the result to an int. I have verified that all of this code works.
Now, the reason for my question:
The first print statement in the input processor only ever shows a value of [].
I have checked the pages which show this output and have verified that they do not behave this way in testing. I also have no middlewares installed into the project and my pipelines should only be running after the item is loaded. So, as I am at my wit's end, please can someone explain why this is happening?
Additional points for feedback on my reg-ex because I think there should be a better way but haven't been able to figure one out yet.

A:

I have fixed the problem and in the process I found a couple issues that I think would help anyone who's new to scrapy. The first is that print doesn't actually return anything so when you put it in Compose it will actually halt execution, which was the first problem with what I was doing.
The second problem is that I was trying to pass loader between helper methods on my spider. This is a problem because when you do that, the item loader will assume the response you created it with so using loader.add_css will not work because your CSS selector will be parsed against the response you used to create the item loader in the first place, which is probably not what you want. What I did was create a middleware that zipped all my partial items together into a coherent response.


Q:

How to create HTML 5 project in Aptana Studio?

I installed Aptana Studio 3 on my windows machine.
I created new WEB Project but when I expand my Proj folder I can see only "Connection" tab. Nothing else. What is the prob? what should I do to get all the files?

A:

Forgive me if the following is what you already did but I was not certain what steps you took from your question/post ... I'm going through the standard steps for creating an HTML 5 Web Project with the Boilerplate templates:

Open Aptana ( duh :) )
File -> New -> Web Project
Provide a Project Name and select your directory if you don't want the default used
Press Next
Select the checkbox for 'Create the project using one of the templates'
Select the HTML5 Boilerplate (use the cached one - I can never get the other, networked one to work)
Select Finish

You should now see the new project and all its default files in your App Explorer view in Aptana.
If you followed those steps but it still fails, I would file a bug (or, at the least, check the existing issues with Aptana) at:
http://jira.appcelerator.org/browse/APSTUD (bugs)


Q:

How to go to the last files in visual studio?

I open
File1.cs
then
File2.cs
Then
File3.cs
Now I want to go back two editor views, is that possible?
e.g. press a button that takes me back to File2.cs
press again
then it takes me back to File1.cs

A:

You can use:

ctrl + - to go back
ctrl + shift + - to go forward

Or you can use your side mousebuttons the same as in a browser (if you have any, highly recommended):

Finally you have the UI:


Q:

Android questions on superuser getting closed as "not computer related"

Android questions on superuser are getting closed as "not computer related". Examples:

https://superuser.com/questions/116579/does-terminal-emulator-work-the-same-as-android-debug-bridge-closed
https://superuser.com/questions/116960/htc-android-mail-imap-folders-not-synchronous-closed
https://superuser.com/questions/115514/on-demand-rtsp-to-android-closed
https://superuser.com/questions/114340/is-there-a-database-app-for-android-and-if-not-whats-the-problem-closed
https://superuser.com/questions/115739/android-mail-app-thread-vs-conversation-closed

Lots more on https://superuser.com/questions/tagged/android, almost all of them are closed as "not computer related".
The FAQ states: "Super User [...] is not about [...] cellphones or mobile devices, except smartphones such as iPhone that interface with your computer"
However:

Android per se is just a platform, an operating system. It's not a device.
Android runs on lots of devices, including netbooks and even standard x86 architectures (any PC). Android is fundamentally different from iPhone because of this, so the same criteria for superuser questions cannot be applied.
Android devices do interface with other computers (via TCP/IP, HTTP, IMAP, and any standard protocol) just like any other computer, because they are computers.

Let's pick one of the closed questions: https://superuser.com/questions/116960/htc-android-mail-imap-folders-not-synchronous-closed . How is this different from a question about Thunderbird or Outlook?
Another: https://superuser.com/questions/115514/on-demand-rtsp-to-android-closed . How is it different from a question about any RTSP client/server on a PC or MAC ?
Other similar meta questions on this topic:

https://meta.stackexchange.com/questions/13289/is-asking-phone-questions-permitted-on-superuser
https://meta.stackexchange.com/questions/16087/are-iphone-ipod-ipod-touch-questions-computer-related-superuser

I think either the FAQ has to be revised to be more clear about this, or the moderators need to be moderated.

A:

Did you know about this one?
Android Enthusiasts:

Android Enthusiasts Stack Exchange is a question and answer site for
  enthusiasts and power users of the Android operating system. It's 100%
  free, no registration required.

It's actually one of the more active StackExchange sites.


Q:

GKLocalPlayer isAuthenticated property always return NO

i use to check if a local player authenticated  with Game Center with Block of code
if ([[GKLocalPlayer localPlayer] isAuthenticated])
{
    NSLog(@"authenticated");
}

this code runs when i first login with GameCenter. When i kill my app and start again it returns NO (Player is not authenticated)
Do i have to login each time when i start the app?
Is there any other solution?

A:

You have to authenticate localPlayer every time your app becomes active but the user only has to input his user/password info the first time. After that it "remembers" who the user is.
Note that the authentication method in iOS 5 is not the same as iOS 6.


Q:

Negation of "If...Then" Statements

I am just being introduced to how logic is used in mathematics and my lecturer mentioned that $\sim(P\rightarrow Q) \equiv p\wedge\sim q$. This is quite hard to grasp at first glance, so he gave an example: The negation of "if $x\neq 0$ then $y=0$" is "$x\neq 0 \wedge y\neq 0$".
Well, my question is, why should that be the case? Why is the negation of "if $x\neq 0$ then $y=0$" not "$x\neq 0 \wedge y=0$"?
Any explanations will be greatly appreciated :)
EDIT: Thank you all for your comments! I think I understand the logic better now!

A:

One can show $A\Rightarrow B \equiv \neg A\lor B$ using truth tables. By De Morgan's laws one concludes
$$\neg (A\Rightarrow B) \equiv \neg (\neg A\lor B) \equiv A\land \neg B. $$

$x\neq 0\ \land\ y=0$ does not negate the initial statement, but implies it, in fact. For if "$x\neq 0\ \land\ y=0$", then certainly "if $x\neq 0$, then $y=0$".

A:

If a implies b, that means every time a occurs, b must also occur. So if a occurs and not b, we now the implication ist false.

A:

"If I come from Paris then I am French".
The negation is certainly not "I come from Paris and I am French" - because what if I really do come from Paris and am French? In that case, both the statement and its "negation" are true!

"If a person is French then they come from Paris". This is false, of course, but why?
To falsify "If a person is French then they come from Paris", I need to demonstrate an example of someone who is French but who does not come from Paris.


Q:

iOS hiding keyboard on "Return" press, resignFirstResponder vs endEditing

I was searching for hiding the iOS keyboard when you press "return", and about half the answers are to use self.view.endEditing(true) and the other half textField.resignFirstResponder(). Is one a better way than the other?
For reference or anyone coming here from Google or something, you need to add UITextFieldDelegate to your class inheritance, add self.<your_TF_var_name>.delegate = self in viewDidLoad(), then make a function
func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
//OR
     textField.resignFirstResponder()
     return true

A:

In this case, it doesn't really matter which you use though technically, using textField.resignFirstResponder() is more efficient because you already know that is the text field you need to resign.
The call to self.view.endEditing(true) is going to have to figure out what the current first responder is and then call resignFirstResponder on it.
My general rule of thumb is to use resignFirstResponder if you have a reference to a specific view you wish to resign. And use endEditing if you don't and you just want the current first responder to be resigned.
On a side note, you should return false from textFieldShouldReturn in either case. There is an edge case where returning true can lead to a newline being added to a UITextView after resigning the UITextField. So as a rule I always return false.