Q:

Moving the mysql query out of the loop

i have the following code
function cron_day_counts()
{
    $subids = get_subids();
    array_push($subids, '');
    $from = '2011-10-19';
    $to = '2011-10-20';
    $days = days_interval($from, $to);
    $result_array = array();
    foreach ($subids as $subid)
    {
        for ($i = 0; $i < $days; $i++)
        {
            $date = date('Y-m-d', strtotime($from . '+ ' . $i . ' day'));
            $date_prev = date('Y-m-d', strtotime($date . '- 1 day'));

            $unique_id_query = mysql_query('SELECT (SELECT COUNT(DISTINCT `id`,`subid`) FROM `tb_stats` WHERE `date` <= \'' . $date . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : '') . ') - (SELECT COUNT(DISTINCT `id`,`subid`) FROM `tb_stats` WHERE `date` <= \'' . mysql_real_escape_string($date_prev) . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : '') . ') AS `unique_ids`');
            $unique_id_result = mysql_fetch_assoc($unique_id_query);

            $total_id_query = mysql_query('SELECT COUNT(DISTINCT `id`,`subid`) AS `total_ids` FROM `tb_stats` WHERE `date` = \'' . mysql_real_escape_string($date) . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : ''));
            $total_id_result = mysql_fetch_assoc($total_id_query);

            $unique_ip_query = mysql_query('SELECT (SELECT COUNT(DISTINCT `ip`,`subid`) FROM `tb_stats` WHERE `date` <= \'' . $date . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : '') . ') - (SELECT COUNT(DISTINCT `ip`,`subid`) FROM `tb_stats` WHERE `date` <= \'' . mysql_real_escape_string($date_prev) . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : '') . ') AS `unique_ips`');
            $unique_ip_result = mysql_fetch_assoc($unique_ip_query);

            $total_ip_query = mysql_query('SELECT COUNT(DISTINCT `ip`,`subid`) AS `total_ips` FROM `tb_stats` WHERE `date` = \'' . mysql_real_escape_string($date) . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : ''));
            $total_ip_result = mysql_fetch_assoc($total_ip_query);

            $global_query = mysql_query('SELECT COUNT(`id`) AS `global` FROM `tb_stats` WHERE `date` = \'' . mysql_real_escape_string($date) . '\'' . (!empty($subid) && is_numeric($subid) ? ' AND `subid` = \'' . mysql_real_escape_string($subid) . '\'' : ''));
            $global_result = mysql_fetch_assoc($global_query);

            $result = array();
            $result['subid'] = $subid;
            $result['date'] = $date;
            $result['unique_ids'] = $unique_id_result['unique_ids'];
            $result['total_ids'] = $total_id_result['total_ids'];
            $result['unique_ips'] = $unique_ip_result['unique_ips'];
            $result['total_ips'] = $total_ip_result['total_ips'];
            $result['global'] = $global_result['global'];

            $result_array[] = $result;
        }

    }
    //db insert
    return $result_array;
}

I want to move all the query out of the foreach and for loops, I believe it would work faster. I'm stuck o this, having no idea how to do this. Any help would be appreciated.

A:

I would say at the very least you should combine the queries in the loop to just one for each day. So for a 5 day range you would have 5 queries.
Or you could have a single query for the whole date range and move it outside the loop (as described by ajreal). Then use PHP to sort it all out.
For large databases I would rather split up queries a little to balance out the load and risk of timeouts. Also helps keep the code maintainable.
You should also look at how your database is structured and indexed.
Is it noticeably slow?
and is the array_push function necessary? (not that it would save much, just wondered cause it looks redundant)
If its really slow then maybe think about restructuring the process completely depending on how you use it.
You could, for example, at 00:01 each day do something like this:

query the days log and count the unique/total IP/ID amounts
insert just the count numbers and date in to a separate table
archive the days log in to a separate archive table or even a separate db like mongoDB

This way you can perform simple querys to view the data and manipulate the numbers to your hearts content with good performance. And by archiving you're keeping the query table small by removing unecessary rows but maintaining a log if needed later.
Of course, this may not fit in with how your db is setup.


Q:

PureCSS stop page reload on form submit but retain form validation

I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.
I know I can stop the page reload using onsubmit="return false;"
Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.
Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.
Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?
FYI, here's the html:
<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
  id="save-simulation-button" onClick="PostSettings();"
  onsubmit="return false;">
    <i     class="fa fa-save"></i> Submit Simulation Parameters
</button>

A:

Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:
In the html I had to add a return here: onClick="return PostSettings();"
Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:
function PostSettings() {
    //event.preventDefault(); <<- commented out per Vigneshs suggestion

    var name = $("#simulation-name").val(); // jquery to get form values
    var description = $("#description").val();

    // Code to validate form: name and description cannot be blank
    if (name === "" || description === "") {
        console.log("name or description fields cannot be blank");
        return true; // <<- returning true allows PureCSS validation to continue
    }

    // Code passed validation so post the data...
    // POST code omitted for brevity

    return false; // <<- returning false stops the page reload
}

So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.
Hope this helps others who want to accomplish this in the future!


Q:

Java class path in manifest not starting libraries

I have compiled a .jar file and I edited the archive of the MANIFEST.MF to add the Class-Path
I have a couple libraries that I need to be in the class-path in order to run the application, here is my classpath:
Class-Path: lib\commons-net-3.1.jar lib\org.eclipse.swt-3.1.jar lib\prompt.jar lib\zip4j_1.3.2.jar

the folder config is like so:
Root directory ('dist'):
-lib folder
-myProgram.jar
So what am I doing wrong for the class-path not to recognize the libraries in the lib folder?

A:

Use
  lib/org.eclipse.swt-3.1.jar

instead of
  lib\org.eclipse.swt-3.1.jar

when adding libs in manifest
  Class-Path: lib/commons-net-3.1.jar lib/org.eclipse.swt-3.1.jar lib/prompt.jar lib/zip4j_1.3.2.jar


Q:

some criteria peg CPU using Scripting Bridge and NSPredicate

I'm trying to get a list of tracks out of iTunes via Scripting Bridge. I'm using NSPredicate because that's the recommended way. This works very well in some cases, and is unusably slow in others. For instance, this will execute very quickly:
NSString *formatString = @"artist == ABC AND album == XYZ";
NSPredicate *trackFilter = [NSPredicate predicateWithFormat:formatString];
NSArray *tracksToPlay = [[libraryPlaylist fileTracks] filteredArrayUsingPredicate:trackFilter];

(libraryPlaylist is an iTunesLibraryPlaylist object that was created elsewhere.)
But if I add either kind or videoKind to the mix, iTunes hits 100% CPU for a minute or more.
NSString *formatString = @"artist == ABC AND album == XYZ AND kind != 'PDF document' AND videoKind == %@", ;
NSPredicate *trackFilter = [NSPredicate predicateWithFormat:formatString, [NSAppleEventDescriptor descriptorWithTypeCode:iTunesEVdKNone]];
NSArray *tracksToPlay = [[libraryPlaylist fileTracks] filteredArrayUsingPredicate:trackFilter];

But that will eventually work. The real failure is albumArtist. If I try
NSString *formatString = @"albumArtist == ABC AND album == XYZ";
NSPredicate *trackFilter = [NSPredicate predicateWithFormat:formatString];
NSArray *tracksToPlay = [[libraryPlaylist fileTracks] filteredArrayUsingPredicate:trackFilter];

iTunes will go to 100% CPU and sit there for I don't know how long. (I gave up after 3 or 4 minutes.) Am I missing something or is this a bug in iTunes?
Additional info
My code takes the resulting tracks and calls another method to add them to a playlist (also using Scripting Bridge). I noticed when trying to filter by kind, the tracks would slowly pop onto the list one by one while iTunes hammered the CPU. This can only mean that filteredArrayUsingPredicate has already returned its results, so what is iTunes working so hard on?

A:

Another post indirectly helped me find the answer.
Using the “Library” playlist causes a number of unusual problems. Using the “Music” playlist instead seems to fix them. In the example above, setting libraryPlaylist this way is what caused the problem:
iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
iTunesSource *library = [[[[iTunes sources] get] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"kind == %i", iTunesESrcLibrary]] objectAtIndex:0];
iTunesLibraryPlaylist *libraryPlaylist = [[[library libraryPlaylists] objectAtIndex:0];

Getting the "Music" playlist instead of the "Library" playlist is the answer:
iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
iTunesSource *library = [[[[iTunes sources] get] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"kind == %i", iTunesESrcLibrary]] objectAtIndex:0];
iTunesLibraryPlaylist *libraryPlaylist = [[[[library playlists] get] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"specialKind == %i", iTunesESpKMusic]] objectAtIndex:0];

Other things to be aware of

The "albumArtist == ABC AND album == XYZ" filter in the original question was actually running pretty quickly. What's slow is anything you do with the result afterward. Calling get right away is a partial solution. (get runs as slow as anything else, but by doing it up front, you limit the slowness to a single operation. Also note that get only works on an SBElementArray.)
I've also found that calling fileTracks re-introduces some slowness. Using tracks instead fixes that. So the filter should read:
NSArray *tracksToPlay = [(SBElementArray *)[[libraryPlaylist tracks] filteredArrayUsingPredicate:trackFilter] get];

(When using "Library", only fileTracks would return objects with a location property, which you need to add them to a playlist. After switching to "Music", tracks seems to return objects with a location as well.)


Q:

How to add date picker control to my toolbox

I am using visual studio 2005 and I have added Datepicker dll in my bin folder.And By doing right click on solution Explorer  Add:references,choosed the that dll.But I want display that control in my toolbar.Does I need to create tab for it.Or it automatically get created.

A:

You need to go to your toolbox then right click anywhere in the toolbox area click choose item and then you can sleect your server control dll from there and it should appear in your toolbox


Q:

Increase related products on single product page (woocommerce)

I'm doing some work on a website running wordpress - woocommerce styled by Jupiter theme.
The problem is that I've asked the developers for help but that's been a while already.
I'm looking for a way to increase the "related products" at the bottom from 2 to 4 so it fills out the template.
In related.php, i thought i found the values to change the amount of related products, but i was wrong. It does nothing at all, which is strange in itself for me.
OLD
 <?php
/**
 * Related Products
 *
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product, $woocommerce_loop;

$related = $product->get_related( $posts_per_page );

if ( sizeof( $related ) == 0 ) return;

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
        'no_found_rows'        => 1,
    'posts_per_page'       => $posts_per_page,
    'orderby'              => $orderby,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id )
) );

$products = new WP_Query( $args );

$woocommerce_loop['columns'] = $columns;

if ( $products->have_posts() ) : ?>

<?php _e( 'Related Products', 'woocommerce' ); ?>

        <?php woocommerce_product_loop_start(); ?>

            <?php while ( $products->have_posts() ) : $products->the_post(); ?>

                <?php wc_get_template_part( 'content', 'product' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

<?php endif;

wp_reset_postdata();

NEW
<?php
/**
 * Related Products
 *
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

 global $product, $woocommerce_loop;

 $related = $product->get_related( 6 );

 if ( sizeof( $related ) == 0 ) return;

 $args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 6,
    'orderby'              => $orderby,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id )
 ) );

 $products = new WP_Query( $args );

 $woocommerce_loop['columns'] = 4;

 if ( $products->have_posts() ) : ?>

<?php _e( 'Related Products', 'woocommerce' ); ?>

        <?php woocommerce_product_loop_start(); ?>

            <?php while ( $products->have_posts() ) : $products->the_post(); ?>

                <?php wc_get_template_part( 'content', 'product' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

      <?php endif;

 wp_reset_postdata();

So I'm really baffled right now, hope anyone has suggestions or solutions on how to change it.

A:

You need to redefine a WooCommerce function to override the default values it contains:
In your functions.php add this:
// Redefine woocommerce_output_related_products()
function woocommerce_output_related_products() {
     woocommerce_related_products(4,2); // Display 4 products in rows of 2
}

You'll need to edit the numbers in brackets to suit your requirements.


Q:

So long, Sklivvz

Today we all learned that, after tomorrow (also known as "today" in UTC+ parts of the world), Sklivvz will no longer be a Stack Overflow employee. This marks the end of a nearly four-year run as a software engineer here, so I think it's worth taking a moment to look back on his time here with the company, as punishment for his sins as a way of bidding fond farewell...
Sklivvz joined us here after a solid tenure as both a long-time Stack Overflow user and founding moderator on Skeptics (he'll retain that status after leaving). His primary focus was on work that affected the Q&A sites.
Sklivvz was active in many different areas during his time here: continuing to moderate Skeptics, helping to guide new users and moderators, traveling the world to share what he'd learned with others face-to-face, occasionally reminding us that there are other countries besides the USA... Among the hundreds of bugs and features that Sklivvz worked on here (including many things most of us probably use daily, like the Help Center and mobile web theme), there are two that I think deserve special recognition:

New Navigation: based on the idea that, as these sites grow, they reach a point where it becomes difficult if not impossible to find questions that interest you as an answerer, this is intended to provide a solid foundation for a more intelligent site navigation UI, one that is customized to each individual user's interests and preferences. Shelved in 2016 so that we could spend more time shipping (and unshipping) other features, the release candidate version remains available on Stack Overflow for those who wish to try it.
Continuous voting fraud detection: This has actually been running and collecting data for several years now, but we haven't yet put the data to good use beyond verifying its results against other methods of detecting fraud (and, occasionally, ad-hoc investigation of reported anomalies). The big advantage of this as compared to the more familiar voting anomaly scripts is that it takes multiple factors into consideration, compiling a "fraud signal strength" for each vote in the system, which can then be used to automatically nullify votes when sufficiently suspicious, or highlight individual users for further investigation by moderators or staff.

I want to highlight the work on both of these, not just because neither will come to fruition until long after Sklivvz is gone, but also because of how the work itself was done: careful analysis of the problem, followed by discussion of possible solutions. Even when the project was something I fully intended to hate (new nav...), the attention to detail that Sklivvz put into researching the problem and defining the goals before venturing to suggest a solution invariably won me over; his work - whether contributing his own ideas or critiquing others' - invariably held to an uncommon sort of persistent honesty that I'll deeply miss.
Please join me in thanking Sklivvz for the work he's done here, and wishing him well in his future endeavors!

A:

Thanks, Josh and Tim, and the community whole. These have been four fantastic years!
I've written a little something to explain my thoughts more fully, but TLDR: thanks, you have made me a better person.
<3

A:

Fun fact, Sklivvz is the second Stack Overflow employee to give a talk to many very curious and inquisitive developers in The Philippines :) Here's a great shot of him doing it:

The talk was all about performance, and how Stack Overflow manages to load in an amazingly short amount of time, and he completely captivated the room of 100 something people during the entirety of a talk that went over time for about 40 minutes. There were no less than 30 really good questions after he wrapped up. If you've ever given talks like that, you probably realize that's rather uncommon.
We love pictures in The Philippines, I'm not sure if he was ready to be in over 100 of them before heading out.
Here he is with one of our top users from Manila, Jon, along with me:

Something that he and I both love to do is actually get out there and spend time in the real world with the people that use and care about what you build. While I'm sure that I'll run into Sklivvz 'on the road', I'm going to make sure that we keep that tradition going in hopes that we one day actually meet a robot.
Sklivvz also has quite the appetite for S.E. Asian cuisine, so we hung out at my place the day he was flying back and cooked some Philippine comfort food known as crispy pata - a pork leg and trotter braised until it falls off the bone, with the cap made nice and crispy:

Fun fact: Sklivvz can drink 10 shots of espresso in the space of approximately three hours. I know this because that's how many I made for him so he could fight jet lag long enough to get on his flight out.
Gonna miss you Marco, but I'm sure I'll see you around :)


Q:

php class inheritance $this->... is undefined?

EDIT: solved, I was using private instead of protected properties in the Controller class.
I'm getting an error when trying to use a property from a class im inheriting. My Controller class looks like this.
<?php

namespace App\Controllers;

use Http\Request;
use Http\Response;
use App\Templates\Renderer;

class Controller{
    private $request;
    private $response;
    private $renderer;

    public function __construct(Request $request, Response $response, Renderer $renderer){
        $this->request = $request;
        $this->response = $response;
        $this->renderer = $renderer;
    }
}

and the Pages class that I'm extending from looks like this.
<?php

namespace App\Controllers;

use App\Models\Book;

class Pages extends Controller{

    public function index(){
        $book = new Book;
        $book->title = 'test';
        // $book->save();
        // echo 'Book created';
        $html = $this->renderer->render('index');
        $this->response->setContent($html);
    }
}

And the error im getting looks like this
Undefined property: App\Controllers\Pages::$renderer

A:

You should change the visibility of your $renderer field from private to protected.
And that's because

private fields/functions can be accessed only from their own classes
public fields/functions can be accessed from anywhere
protected fields/functions can be accessed from all classes that extend current class including the parent class

http://php.net/manual/en/language.oop5.visibility.php


Q:

PHP string concatenation within class definition

Possible Duplicate:
Initializing PHP class property declarations with simple expressions yields syntax error

Is it possible to achieve the following in PHP 5.2.17 ?
$basePath = '/final';

class Foo {
    public $data = $basePath . '/data';
}

A:

The default values for properties must be constant in the source, e.g. strings and array literals. No expressions.
Use the __construct() method for anything more complicated.


Q:

Unexpected XML tag error when calling eBay API via Jax-WS

I'm trying to use the Ebay trading API using JAX-WS.  (yes, i know there's an SDK for the trading API webservice, but I'm trying to avoid using it, since the other Ebay APIs don't have an SDK.  Doesn't make sense for me to code half my program using an SDK)
https://go.developer.ebay.com/api-documentation
First, I created JAX-WS stubs using wsimport, then I created the jar file.
I was following this documentation: http://java.boot.by/ocewsd6-guide/ch06.html
I'm trying to call the GetSessionID function.  The documentation is here:
http://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetSessionID.html
I was able to get this far:
        ebay.apis.eblbasecomponents.EBayAPIInterfaceService eais = new ebay.apis.eblbasecomponents.EBayAPIInterfaceService();
        ebay.apis.eblbasecomponents.EBayAPIInterface eport= eais.getEBayAPI();

        //here, need to build a request
        ebay.apis.eblbasecomponents.GetSessionIDRequestType gsr = new GetSessionIDRequestType();
        gsr.setRuName(runame);

        //http://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/twbs_cookiejaxws.html
        // Set up the Map that will contain the request headers.
        Map<String, Object> req_ctx = ((BindingProvider)eport).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://api.ebay.com/ws/api.dll");

//        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://api.ebay.com/wsapi");

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("runame", Collections.singletonList("BLAHBLAH"));
        headers.put("X-EBAY-API-COMPATIBILITY-LEVEL", Collections.singletonList("907"));
        headers.put("X-EBAY-API-DEV-NAME", Collections.singletonList("BLAHBLAH"));
        headers.put("X-EBAY-API-APP-NAME", Collections.singletonList("BLAHBLAH"));
        headers.put("X-EBAY-API-CERT-NAME", Collections.singletonList("BLAHBLAH"));
        headers.put("X-EBAY-API-CALL-NAME", Collections.singletonList("GetSessionID"));
        headers.put("X-EBAY-API-SITEID", Collections.singletonList("US"));
        headers.put("Content-Type", Collections.singletonList("text/xml"));

        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

        GetSessionIDResponseType gsResponse = eport.getSessionID(gsr);

But then, I get the error below.

Can someone tell me what I'm doing wrong?
Better yet, can anyone generate sample code to call this API?

Error:
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:363)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:303)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: com.sun.xml.internal.ws.protocol.soap.MessageCreationException: Couldn't create SOAP message due to exception: unexpected XML tag. expected: {http://schemas.xmlsoap.org/soap/envelope/}Envelope but found: {urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse
    at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.decode(SOAPBindingCodec.java:304)
    at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.createResponsePacket(HttpTransportPipe.java:268)
    at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:217)
    at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:130)
    at com.sun.xml.internal.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:124)
    at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:1121)
    at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:1035)
    at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:1004)
    at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:862)
    at com.sun.xml.internal.ws.client.Stub.process(Stub.java:448)
    at com.sun.xml.internal.ws.client.sei.SEIStub.doProcess(SEIStub.java:178)
    at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:93)
    at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:77)
    at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:147)
    at com.sun.proxy.$Proxy35.getSessionID(Unknown Source)
    at Ebluna.main(Ebluna.java:101)
    ... 11 more
Caused by: com.sun.xml.internal.ws.streaming.XMLStreamReaderException: unexpected XML tag. expected: {http://schemas.xmlsoap.org/soap/envelope/}Envelope but found: {urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse
    at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.verifyTag(XMLStreamReaderUtil.java:261)
    at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(StreamSOAPCodec.java:205)
    at com.oracle.webservices.internal.impl.encoding.StreamDecoderImpl.decode(StreamDecoderImpl.java:49)
    at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(StreamSOAPCodec.java:234)
    at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(StreamSOAPCodec.java:151)
    at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.decode(SOAPBindingCodec.java:299)
    ... 26 more
Exception running application Ebluna

A:

The caused-by exception is a big clue. Because you're using a JAX-WS client created from a WSDL, the runtime is expecting a SOAP xml response with a root xml element of <Envelope> but is instead getting a <GetSessionIDResponse> as root element in the HTTP response.
Per the eBay trading API docs, they have a plain xml-over-http endpoint and a SOAP-over-http endpoint url. Since you're using SOAP, you need to use only the SOAP endpoint URL; your code is actually specifying both endpoints (luckily last one wins and you're actually using the right one - but you don't need to set the endpoint twice): https://api.ebay.com/wsapi
I believe the reason you may be getting a non-SOAP response may be because of the HTTP headers you are passing. The docs say these are only for use with the non-SOAP endpoint; yet you are using the SOAP endpoint and passing them anyways. For the SOAP interface you're supposed to pass these params as URL query string parameters on the endpoint URL.
For example:
Example: Specifying Routing Information in the Request URL
// Define the endpoint (e.g., the Sandbox Gateway URI)
String endpoint = "https://api.sandbox.ebay.com/wsapi";
// Define the query string parameters.
String queryString = "?callname=AddItem"
                                        + "&siteid=0"
                                        + "&appid=myappid"
                                        + "&version=349";
                                        + "&Routing=new";

String requestURL  = endpoint + queryString;
EBayAPIInterfaceServiceLocator  sl = new EBayAPIInterfaceServiceLocator();
EBayAPIInterface       privBinding = sl.geteBayAPI(new URL(requestURL));
((EBayAPISoapBindingStub)privBinding).setTimeout(60000);


Q:

What's $T\left(n\right)$?

If $T\left( n \right) = 8T\left( n-1 \right) - 15T\left( n-2 \right); T\left(1\right) = 1; T\left( 2 \right) = 4$,
What's $T\left(n\right)$ ?

I use this method:
Let $c(T(n) - aT(n-1)) = T(n-1) - aT(n-2)$
from $T(n) = 8T(n-1) - 15T(n-2)$, we can get $\begin{cases}c = \frac{1}{3}\\a = 5\end{cases}$ and  $\begin{cases}c = \frac{1}{5}\\a = 3\end{cases}$,
then, we get $\frac{T(n)-5T(n-1)}{T(n-1)-5T(n-2)} = 3$,
so, we reach the answer: $T(n) = \frac{3^{n-1}+5^{n-1}}{2}$.

Sorry for my poor English.

A:

This is second order recurrence equation. Since $T(n)=8T(n-1)-15T(n-2)$, we first solve the quadratic equation: $x^2=8x-15$. Its roots are $3$ and $5$. Therefore, $T(n)$ must be in the form:
$$T(n)=a\cdot 3^n+b\cdot 5^n, n\geq 1$$for some constants $a$ and $b$.
To find $a$ and $b$, since $1=T(1)=3a+5b$ and $4=T(2)=9a+25b$, we get $a=1/6$ and $b=1/10$, i.e.
$$T(n)=\frac{1}{6}\cdot 3^n+\frac{1}{10}\cdot 5^n, n\geq 1$$


Q:

Match Arrays in jQuery

I'm working on a tic tac toe project with a simple 3x3 grid.  I'm pushing the index of each selected box to an array for each player.  In an attempt to check for a winner, I can't seem to get my player arrays to match up with my winner array.  I've tried the indexOf method and the inArray method--but to no avail.
Here's my winner array:
const winners = [
    [0,1,2],
    [3,4,5],
    [6,7,8],
    [0,3,6],
    [1,4,7],
    [2,5,8],
    [0,4,8],
    [2,4,6]
];

And code which tracks player moves (including the push of selected index value). Note that my console log is showing the correct index values being pushed to the player's array.
//Check for player move and change box to active if available
    currentPlayer = 0;
    player1Mouseover()
    $boxes.click(function(){
          if ((currentPlayer == 0) && ($(this).hasClass('box box-filled-1') || $(this).hasClass('box box-filled-2'))){
            alert("Whoa whoa--no no bad selection kiddo. Try again.");
          } else if ((currentPlayer == 0) && ($(this).hasClass('box'))){
            //highlight selected box with a 'O' image
            $(this).addClass('box-filled-1');
            //increment total player moves
            move ++;
            //push player one's selections to array
            player1Selections.push(($(this).index()));
            //set to player two
            currentPlayer = 1;
            //set conditions for mouseover events
            player2Mouseover();
            //check to see if there is a winner
            checkWinner();
            //add active class to player two's image at top of screen
            $('#player2').addClass('active');
            //hide active class for player one's image at top of screen
            $('#player1').removeClass('active');
          } else if ((currentPlayer == 1) && ($(this).hasClass('box box-filled-1') || $(this).hasClass('box box-filled-2'))) {
            alert("Whoa whoa--no no bad selection kiddo. Try again.");
          } else if ((currentPlayer == 1) && ($(this).hasClass('box'))){
            //highlight selected box with a 'X' image
            $(this).addClass('box-filled-2');
            //increment total player moves
            move ++;
            //set back to first player
            currentPlayer = 0;
            //set conditions for player one mouseover events
            player1Mouseover();
            //check for a winner
            checkWinner();
            //change classes for player one and two
            $('#player1').addClass('active');
            $('#player2').removeClass('active');
        }
    });

here is my arraysEqual and checkWinner function which I'm only testing on player one for the moment.
//Check to see if there is a winner
    function arraysEqual(a, b) {
      if (a === b) return true;
      if (a == null || b == null) return false;
      if (a.length != b.length) return false;

      // If you don't care about the order of the elements inside
      // the array, you should sort both arrays here.

      for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
      }
      return true;
    }

  function checkWinner(){
        isEqual = arraysEqual(winners,player1Selections);
        console.log(player1Selections);
        if (move >= 5){
            if (isEqual){
                finish.style.visibility = "visible";
                board.style.visibility = 'hidden';
                console.log("winner");
            } else {
                console.log("no winner");
            }
        }

complete code here if needed github

A:

You cannot compare arrays in javascript this way.
[0,1,2]==[0,1,2] // false

So comparing arrays (or one subarray with a different array, but same values) doesn't work. Both arrays are not the same, only the values are the same.
You can define your own function to achieve this:
Array.prototype.equals = function(array) {
  if(this.length != array.length) return false;
  for(let i=0;i<this.length;i++)
    if(this[i]!=array[i]) return false;
  return true;
}

This will work in your case. It is NOT ment to work with all kinds of arrays. If you need a comparation of multidimentional arrays it won't work and you will need to define a function that's complexity is a little higher.
What you need is to compare all the subarrays of the winners array with one array that could match.
This can be done with using the Array.prototype.some function: winners.some((subArray)=>arrayEquals(subArray, the_other_array)) (this statement is true, if one of the subarrays matches the given other array)


Q:

ollydbg plugin patch notification

Im developing a plugin in which I would like to be notified when user makes some modification to the code. I know there is a patch table which can be accessed through Plugingetvalue function but I would like to do some actions as soon as user modifes code and not to check patch table every now and then. Is it possible to do this and how?

A:

Given your reference to Plugingetvalue(), it looks like you're trying to write your plugin for OllyDbg v1.
In that case, you could do the following:

Get the address of the patch table's t_table: pPatchTable = Plugingetvalue(VAL_PATCHES);
Hook Addsorteddata(), such that any time you see it called with sd == &pPatchTable->data, you'll see that the user just added a patch.
Analyze the item value passed to Addsorteddata() above as a pointer to a t_patch structure, which will give you the base address of the patch in memory, the size of the patch, the type of patch, the original code, and the patched code.

There may be a formal way to get patch notifications, but if not, the above solution should work.


Q:

Hide WYSIWYG editor on certain templates

I hope the title makes sense. I currently want to hide the default WYSIWYG editor on some of the pages but display it on others.
Is there a filter or a hook for the functions file?

A:

I hope I understood your question right.
The following code will remove the editor from the pages using particular templates:
<?php

function wpse242371_remove_editor_from_some_pages()
{
    global $post;

    if( ! is_a($post, 'WP_Post') ) {
        return;
    }

    /* basename is used for templates that are in the subdirectory of the theme */
    $current_page_template_slug = basename( get_page_template_slug($post_id) );

    /* file names of templates to remove the editor on */
    $excluded_template_slugs = array(
        'tmp_file_one.php',
        'tmp_file_two.php',
        'tmp_file_three.php'
    );

    if( in_array($current_page_template_slug, $excluded_template_slugs) ) {
        /* remove editor from pages */
        remove_post_type_support('page', 'editor');
        /* if needed, add posts or CPTs to remove the editor on */
        // remove_post_type_support('post', 'editor');
        // remove_post_type_support('movies', 'editor');
    }

}

add_action('admin_enqueue_scripts', 'wpse242371_remove_editor_from_some_pages');


Q:

I have a Wordpress driven site, my contact form 7 plugin is adding a ton of whitespace to the bottom of the form and I'm not sure why

For some odd reason, my contact form 7 plugin, which I have embedded into the front-page.php file using the following code:

Contact Us

    <?php echo do_shortcode('[contact-form-7 id="180" title="Request A Quote"]'); ?>

is adding a ton of whitespace below the submit button.  Upon examining the code, I see that the culprit is

I'm not sure how to stop this, or why this is happening.  I've tried to disable other plugins but nothing seems to work.  I've tried the form on a separate page and it seems to work fine (you can click the Start Your Project link at the top and see for yourself)
Stylesheet contact code
/* Contact */
#contact { }

#contact .container {
    font-size: 12px;
}

A:

This is the problem I think:
media="all"
.pad-section img {
   width: 100%;
}

I disabled that in the DOM using inspect element, and it fixed the extra padding, so I would set that value to "none" or just delete ".pad-section img" class altogether.
media="all"
.pad-section img {
   width: none;
}

Or remove the class.  Give it a shot.


Q:

Help identify antique rear steer tandem bike

I'm trying to identify an antique tandem bike.  I have looked at over 6000 of them on the internet with no luck.  Many are similar, but this one has some unique items.  Not the top rail, it stops at the passenger seat.  The bottom frame rail is quite beefy in comparison to others.  It has dual drum brakes.   The rear steering setup is very crude looking, like a prototype.  It appears to be a 6 speed bike.  The head logo has a sticker over it, so I can not see the head logo, but I will try to remover the sticker soon.

A:

It didn't leave a factory like that.
From the area around the rear handlebars you can see it's been modified. A head tube (blue rather than the black of the rest of the frame) has been welded to the front seat post, reversed. I suspect the rear top tube has been cut off, weakening the frame a lot, and the steerer parts attached to the stub of that. It looks like the top of a set of forks is still present and used in the linkage. Close-ups of the top of both seat tubes and the areas around them would help be more certain.
It looks like the front bars have turned with the wheel. Is it front and rear steer? It's also interesting that it's got a single brake lever at the front. Disabling one brake on a tandem seems a bad decision, or does the lever operate both (or have I missed something)?
It's a curiosity, but I don't see it being a worthwhile restoration project given the way the modifications affect the safety.


Q:

Store weak pointer to self

I work with a codebase that was partially implemented by someone who was in love with overly complex solutions to simple problems (e.g. template classes with two parameters that were only ever instantiated for one pair of types).  One thing she did was to create objects in a smart pointer, and then have the object store a weak pointer to itself.
class MyClass {
    //...
    boost::weak_ptr<MyClass> m_self;
    //...
};

boost::shared_ptr<MyClass>
Factory::Factory::Factory::CreateMyClass() {
    boost::shared_ptr<MyClass> obj(new MyClass(...));
    boost::weak_ptr<MyClass> p(obj);
    obj->storeSelfPointer(p);
    return obj;
}

The class then proceeds to use m_self by locking it and passing around the resulting shared pointer.
For the life of me, I cannot fathom what she was trying to accomplish.  Is there some pattern or idea that would explain this implementation?  It looks to me like this is completely pointless and I'd like to refactor it away.
EDIT: I should mention that none of the places that use the resulting smart pointer obtained from locking m_self actually retain the smart pointer.

A:

A possible use of this "design" could be to use m_self.lock() to generate shared pointers from this.
If you remove this weak pointer member, the reference count hold by the generated shared pointer from this would be incorrect.
It achieves the same than std::enable_shared_from_this, interestingly enough, cppreference.com mentions this design :

A common implementation for enable_shared_from_this is to hold a weak
  reference (such as std::weak_ptr) to this. The constructors of
  std::shared_ptr detect the presence of an enable_shared_from_this base
  and assign the newly created std::shared_ptr to the internally stored
  weak reference

And the C++ standard, section § 20.8.2.4 10 , mention the same possible implementation :

The shared_ptr constructors that create unique pointers can detect the
  presence of an enable_shared_- from_this base and assign the newly
  created shared_ptr to its
  __weak_this member

Possible Refactoring :

If you are using C++11, you can remove the std::weak_ptr member, and publicly inherits from std::enable_shared_from_this<T>. You should retrieve a shared pointer from this by calling shared_from_this().
If you are not using C++11 but can use boost, use boost::enable_shared_from_this, see the boost documentation. You should retrieve a shared pointer from this by calling shared_from_this().
If you are not using C++11, and can't use boost, you can bring the proposed implementation of the standard to your code base, it is short enough :

Code : (copied from § 20.8.2.4 - 11, remove leading underscores, and you probably want to rename it)
template<class T> class enable_shared_from_this {
    private:
     weak_ptr<T> __weak_this;
    protected:
     constexpr enable_shared_from_this() : __weak_this() { }
     enable_shared_from_this(enable_shared_from_this const &) { }
     enable_shared_from_this& operator=(enable_shared_from_this const &) { return *this; }
     ~enable_shared_from_this() { }
    public:
     shared_ptr<T> shared_from_this() { return shared_ptr<T>(__weak_this); }
     shared_ptr<T const> shared_from_this() const { return shared_ptr<T const>(__weak_this); }
};

And use shared_from_this() to make a shared pointer. If you do copy this code, note that constructing shared pointers from this by other means would not work. The shared pointers constructors need to be modified (as explain by the standard quote above).


Q:

Insert COUNTIF formula when you have variable holding the value

Consider:
 Cells(2, "Q").Formula = "=COUNTIF(P$1:P1,P2)=0"

How do I insert these formulae when I have a variable holding a value?
I have to start the formula at 3550 row and 4000 row somtimes. It depends on the data. Well, when I googled it, I found nothing. They all used the same formula, but I need to insert the countif function at a particular cell, may be at 300 or 500 - it depends in the variable value.
 Cells(count,"Q").formula = "=COUNTIF(cells($1,"P"):cells(count-1,"P"),cells(count,"P))=0"

Is this the way? Well, I tried in some ways but it's ending up higlighting the line with the red colour. How do I insert these formulae with a variable?

A:

Try this:
'case 1: if you know the destination range
Range("Q2").Formula = "=COUNTIF(P$1:P1,P2)=0"
Range("Q2").Copy Destination:=range("Q3:Q500")

'case 2: if the destination range is a variable
'minRow is a Long >= 1
Range("Q" & minRow + 1).Formula = "=COUNTIF(P$" & minRow & ":P" & minRow & ",P" & minRow + 1 & ")=0"
Range("Q" & minRow + 1).Copy Destination:=Range("Q" & minRow + 1 & ":Q" & maxRow)

Reference: Issun's answer to Stack Overflow question How do I insert the formula into the cell when the formula keeps changing with increase in row?.


Q:

Liquibase "Could not release lock" error

While running a Liquibase changeset I get the following error:
Could not release lock. The base exception is actually an SQLException: Connection is closed!.
The changeset contains a renameColumn.
<changeSet author="me" id="renameaTob">
    <renameColumn newColumnName="b" oldColumnName="a" columnDataType="BIGINT(19)" tableName="aTable" />
</changeSet>

A:

The problem was the fact that the column to be renamed was part of a foreign key constraint.
The solution was to drop first the constraint and then add it again with the new column name. But if all these operations are done in the same changeset, the result is no different. So it has to be split into two changesets: first, dropping the constraint and renaming the column and second, recreating the foreign key constraint.
<changeSet author="me" id="renameaTob">
    <dropForeignKeyConstraint baseTableName="aTable" constraintName="a_c_fk2"/>
    <renameColumn newColumnName="b" oldColumnName="a" columnDataType="BIGINT(19)" tableName="aTable" />
</changeSet>

<changeSet author="me" id="addFkAgain">
    <addForeignKeyConstraint baseColumnNames="b"
            baseTableName="aTable" constraintName="b_c_fk2"
            deferrable="false" initiallyDeferred="false" onDelete="NO ACTION"
            onUpdate="NO ACTION" referencedColumnNames="c" referencedTableName="refTable" />
</changeSet>

I think it is also possible to use only one changeset and add runInTransaction='false', but this is not a good idea anyway.


Q:

Truncating the data-frame column values in Scala

df is the dataframe, and
df.select($"createdon").show
output is:
|           createdon|
+--------------------+
|2017-05-11 15:29:...|
|2017-05-11 15:29:...|
|2017-05-11 11:02:...|
|2017-05-11 11:02:...|
|2017-05-11 15:29:...|

I need the createdon value to be just the date instead of whole timestamp. How to have the new dataframe containing createdon's value to be just the date instead of whole timestamp?

A:

You can use a map transformation (assuming, that selected values are of the String type)
df.select($"createdon").map(_.getAs[String]("createdon").substring(0, 11)).show()


Q:

Where is the '^]' character on an AZERTY (French) keyboard?

Same question as this one on superuser: where is telnet's escape character, ^] located on an AZERTY (French) keyboard?

A:

Ctrl-$
Mnemonic: the $ key is where ] would be on a QWERTY keyboard.


Q:

Can't display my button at the bottom of a list of layouts

I have spent hours on this problem, I hope somebody can help me.
Sorry in advance if the question is stupid, I am fairly new to android development and also, I am using an app builder which has generated already a lot of code. I am basically trying to tweak this code with what I want...
The question is just about xml layouts, I don't think it involves code. I want to display a simple button at the bottom of this screen.
So I have this screen which builds a group of buttons in a grid. I also display an ad banner at the top. The parameters of these buttons are specified through the web app builder on a web interface. No problem with these buttons. They are displayed correctly in this screen layout below:
    <?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/containerView"
android:background="@android:color/transparent"
android:padding="0dip"
android:layout_margin="0dip"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<com.google.ads.AdView android:id="@+id/adView"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     ads:adUnitId="123"
                     ads:adSize="SMART_BANNER"
                     ads:testDevices="123"
                     ads:loadAdOnCreate="true">
</com.google.ads.AdView>

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/verticalScrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/tableLayout"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        </TableLayout>

    </ScrollView>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/containerViewHorizontal"
            android:background="@android:color/transparent"
            android:padding="0dip"
            android:layout_margin="0dip"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/containerViewHorizontalBottom"
                    android:background="@android:color/transparent"
                    android:padding="0dip"
                    android:layout_margin="0dip"
                    android:orientation="vertical"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/horizontalScrollView"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@+id/containerHorizontalButtons"
                        android:background="@android:color/transparent"
                        android:padding="0dip"
                        android:layout_margin="0dip"
                        android:orientation="horizontal"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                    </LinearLayout>

                </HorizontalScrollView>

            </LinearLayout>

    </RelativeLayout>

Now what I am trying to do, is to add at the bottom of this group of buttons, a button that does not belong to the list generated through the web app builder, but manually created:
<Button
android:id="@+id/bmenu2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

I have already taken care of the code for this button, it works well, but I don't manage to display it at the bottom of my screen.
I guess it has to do with the general layout of the screen. I have to admit I am completely lost in the series of layout nested in one another, I don't understand what is exactly doing what.
If that helps, I have managed to display my button at the top of the screen, even just below my ad banner. But not at the bottom.
Also if that helps, I guess one of the layout takes up the whole heightspace (the scrollview?), living 0 height for the button I want to add...
Thanks a lot for your time and if you can help me!

A:

Juyt implement a Linear layout instead of a relative one for the list and the button.
Then give the list a height of 0dp and a weight of 1
The button will have whatever attributes:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >
</ListView>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button" />

</LinearLayout>


Q:

Eurostile Font support in iOS?

I have a requirement for an iPhone application, where the application font should be in 'Eurostile Font'. I have checked the available fonts provided by iOS, it does not have 'Eurostile Font'. Is it possible to import this font to application? If not, is there any equivalent font for 'Eurostile Font' ?

A:

The short answer is, no.
The Wikipedia-page for Eurostile states that foundries like Linotype and URW have versions of Eurostile. I haven't read their font licenses, but pretty certain they don't allow re-distribution of the font files (without paying them a large amount of money).
If you had a version of Eurostile (or any other font) that you wanted and legally could use, you can do (since iOS version 3.2):

Add the font file to the project in Xcode (in Resources for example).
Add the key UIAppFonts to the info.plist file and make it an array type.
Add the font file name to the array.
Use it by doing, for example, [UIFont fontWithName:@"Eurostile" size:20].

Your options are:

Pay the foundries for a license of Eurostile that can be re-distributed.
If you only need a heading or some text on a button, draw the text you want to use and use the bitmap image in your app.
Find a similar font to Eurostile that is distributed with less restrictions (one such license is the SIL Open Font License). A good place to start looking is the Google Web Fonts site.


Q:

Jquery img src variable to php variable?

How do i get my jquery variable in to a php variable, I've made a php document with jquery in it, after clicking the image the css will change and you will see a bigger image next to it. I need to have the image source of the big image in a php variable to get information about the image from the database.
Codes in the php file:

     <?php
         $con=mysqli_connect("localhost","root","root","database");
         // Check connection
         if (mysqli_connect_errno()) {
             echo "Failed to connect to MySQL: " . mysqli_connect_error();
         }

         $result = mysqli_query($con,"SELECT * FROM image");
         while($row = mysqli_fetch_array($result)) {
             echo "";
         }
         mysqli_close($con);
     ?>

Code in js file:
$(function () {
    "use strict";
    $('.media-image').click(function () {
        $(this).toggleClass('media-image-selected');
    });
    $('.media-image').click(function () {
        var src = $(this).attr('src');
        $('#bigimage').attr('src', src);
    });
});

A:

If I understand your problem is that you want to show information from an image object from database on the fly.
In that case I think you have two option:
First option
In the server-side code when you build the page, you can query every possible information from the database about images. You should save these meta-data in data HTML attributes. In the client-side code in java script you can read and show these meta-data values. To read data attributes you can use .data() jQuery function
In this case your page loading time will increase, due to the big query but the client don't have to wait more to load the information, because every data are on their client side.
Second option
You can do that with AJAX loading. You need php script which build the layout. You have to put some kind of identification for the images ie: ID from the database, doesn't matter, you will search the image by this value. To put these ids I recommend you the previously mentioned data attribute.
After that you'll need a PHP interface which will do the selects from database. This script should read an image ID from GET parameter and based on that select the information about that image. Put the data in PHP array and after the select convert the PHP array into a JSON array and write out. Important: this script mustn't write out anything except the JSON array. In this interface script you should change the header into json data type with this code:
header('Content-type: application/json');

Finally you have to create a client side script on the layout which load the ID from the clicked image and call an AJAX load to the interface php. For the AJAX call I suggest th jQuery ajax function:
http://api.jquery.com/jquery.ajax/
So in that case you have three components:

layout builder (server side)
database select interface (server side)
ajax caller (client side)

The two server side script should definitely separated into two files.
This method, as you can see is more complex then the first one, but sometimes is more efficient.
Summary
The first method maybe will have a little bit longer page loading time, due to the database select. But a good sql code can be well optimized, so the query time can be measured in millisecs. In simple use-cases this is the best method.
The second one should be used when you want load or modify more complex data set on the fly.
I recommend you the first option.
Good luck!


Q:

ui-sref open with new tab

I tried to open ui-sref in new tab, noted that i don't want to call it from controller. How to do from view end?

                <button ui-sref="app.blogs" target="_blank" class="btn btn-black " id="form-submit" type="submit" value="Submit">See all Blogs</button>

A:

If you want to open a ui-sref from the view you can use target="_blank", but note that the button element does not support target. Change your button into an anchor tag.
See all blogs

If you want to continue to use the button element, I believe you need to use the controller.


Q:

Unable to remove spaces between table column (td)

Unable to remove space between td between numeric digit (td) and the background red td

https://jsfiddle.net/297zgLon/
I have tried using suggested css way of doing it i.e.
CSS
border-collapse:collapse;border-spacing:0px;

HTML

                                                   1.

                                                    TEST CASE 1

                                                   2.

                                                   Test case 2 tools

                                                   3.

                                                   Test case 3

There should be no space between 1. and red background td(column)

A:

removed display: inline-block; on first

         1.

          TEST CASE 1

         2.

         Test case 2 tools

         3.

         Test case 3


Q:

extract a word colon space few words

I need to extract two patterns from the text field One is "From: alpha beta" and other is "To: gemma delta" from the following dataframe.
df <- tibble(text=c("From: alpha beta", "To: gemma delta"))

I am using this..
from_pattern <- regex("[From]:\\s[alpha beta]")
to_pattern <- regex("[To]:\\s[gemma delta]")

df <- df%>%
  mutate(to = if_else(str_detect(text, to_pattern), "to", NA_character_),
         from = if_else(str_detect(text, from_pattern), "from", NA_character_))

but I am not getting the desired result. What am I missing here? It would be great if I get the output in one column like the following:
df <- tibble(text=c("From: alpha beta", "To: gemma delta"),
             tofrom = c("from", "to"))

A:

Assume you want to know if a string starts with From: or To::
df %>% mutate(tofrom = tolower(str_extract(text, '(?i)^(from|to)(?=: .*)')))

# A tibble: 2 x 2
#  text              tofrom
#  <chr>             <chr>
#1 From: gemma delta from
#2 To: alpha beta    to

Here use (?i) modifier to ignore case to make the match more generic, and then match the word from or to from the start of the string followed by :.
If you need to match the pattern exactly:
df %>% mutate(tofrom = tolower(str_extract(text, '(?i)^(from(?=: gemma delta$)|to(?=: alpha beta$))')))
# A tibble: 2 x 2
#  text              tofrom
#  <chr>             <chr>
#1 From: gemma delta from
#2 To: alpha beta    to


Q:

Undefined symbol for architecture i386 on linking SWIG C++ Wrapper Object for Ruby compiled with -m32 option

Greetings StackOverflow Community,
I've got a SWIG project that generates a Ruby C API wrapper for a C++ static archive library. I don't have any problems generating and compiling the code under 64-bit Linux (tested under Fedora and Debian). Unfortunately, the OS X version of the archive is 32-bit only. I've built a 32 bit version of Ruby on OS X in order to generate, compile, and link the shared object that will be used as the Ruby C Native Extension:
$ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [i386-darwin11]

All objects are compiled with the -m32 flag:
$ g++ -m32 -Wall -g -c -fPIC -rdynamic ../src/CPPExampleWrapper.cpp ../src/CPPExampleException.cpp ../src/CPPExampleObject.cpp ../src/CPPExampleCallbackFunctor.cpp -I../include/ -I../lib/include/

and linked accordingly:
g++ -m32 -shared -fPIC -o ../lib/cppexample.so ./bin/CPPExampleWrapper.o ../qa_cpp_utils/bin/CPPExampleObject.o ../qa_cpp_utils/bin/CPPExampleCallbackFunctor.o ../qa_cpp_utils/lib/libcppexamplearchive.a -framework CoreFoundation -lpthread

On linking, I receive an error indicating that symbols referenced in CPPExampleWrapper.o are undefined for architecture i386:
Undefined symbols for architecture i386:
  "_rb_big2long", referenced from:
      SWIG_AUX_NUM2LONG(unsigned long*)in CPPExampleWrapper.o
  "_rb_big2ulong", referenced from:
      SWIG_AUX_NUM2ULONG(unsigned long*)in CPPExampleWrapper.o
  "_rb_cFalseClass", referenced from:
      _rb_class_of in CPPExampleWrapper.o
  "_rb_cFixnum", referenced from:
      _rb_class_of in CPPExampleWrapper.o
  "_rb_cNilClass", referenced from:
      _rb_class_of in CPPExampleWrapper.o
  "_rb_cObject", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
      _SWIG_Ruby_SetModule in CPPExampleWrapper.o
      _SWIG_Ruby_define_class in CPPExampleWrapper.o
  "_rb_cSymbol", referenced from:
      _rb_class_of in CPPExampleWrapper.o
  "_rb_cTrueClass", referenced from:
      _rb_class_of in CPPExampleWrapper.o
  "_rb_check_type", referenced from:
      _SWIG_Ruby_GetModule in CPPExampleWrapper.o
      _SWIG_Ruby_ConvertPtrAndOwn in CPPExampleWrapper.o
  "_rb_const_get", referenced from:
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
  "_rb_data_object_alloc", referenced from:
      _SWIG_Ruby_SetModule in CPPExampleWrapper.o
      _SWIG_Ruby_NewClassInstance in CPPExampleWrapper.o
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
  "_rb_define_alloc_func", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_define_class", referenced from:
      getNullReferenceError()      in CPPExampleWrapper.o
      getObjectPreviouslyDeletedError()      in CPPExampleWrapper.o
      _SWIG_Ruby_SetModule in CPPExampleWrapper.o
  "_rb_define_class_under", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
      _SWIG_Ruby_define_class in CPPExampleWrapper.o
  "_rb_define_const", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_define_method", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_define_module", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
      _SWIG_Ruby_InitRuntime in CPPExampleWrapper.o
  "_rb_define_module_function", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_define_readonly_variable", referenced from:
      _SWIG_Ruby_SetModule in CPPExampleWrapper.o
  "_rb_define_singleton_method", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_eArgError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
      _wrap_new_JobOrder(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_src_location_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_src_location_get(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_dst_location_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_dst_location_get(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_xfer_params_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      ...
  "_rb_eFatal", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eIOError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eIndexError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eNoMemError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eRangeError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eRuntimeError", referenced from:
      getNullReferenceError()      in CPPExampleWrapper.o
      getObjectPreviouslyDeletedError()      in CPPExampleWrapper.o
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eSyntaxError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eTypeError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_eZeroDivError", referenced from:
      SWIG_Ruby_ErrorType(int)   in CPPExampleWrapper.o
  "_rb_funcall", referenced from:
      _SWIG_RubyRemoveTracking in CPPExampleWrapper.o
  "_rb_gv_get", referenced from:
      _SWIG_Ruby_GetModule in CPPExampleWrapper.o
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
  "_rb_gv_set", referenced from:
      _SWIG_Ruby_GetModule in CPPExampleWrapper.o
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
  "_rb_hash_aref", referenced from:
      _SWIG_RubyInstanceFor in CPPExampleWrapper.o
  "_rb_hash_aset", referenced from:
      _SWIG_RubyAddTracking in CPPExampleWrapper.o
  "_rb_hash_new", referenced from:
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
  "_rb_inspect", referenced from:
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_int2big", referenced from:
      _SWIG_RubyPtrToReference in CPPExampleWrapper.o
      _SWIG_RubyObjectToReference in CPPExampleWrapper.o
      SWIG_From_int(int)   in CPPExampleWrapper.o
  "_rb_intern", referenced from:
      _SWIG_Ruby_InitRuntime in CPPExampleWrapper.o
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
  "_rb_iv_get", referenced from:
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
      _SWIG_Ruby_MangleStr in CPPExampleWrapper.o
  "_rb_iv_set", referenced from:
      _SWIG_Ruby_NewClassInstance in CPPExampleWrapper.o
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
  "_rb_ivar_get", referenced from:
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
  "_rb_ivar_set", referenced from:
      _SWIG_RubyInitializeTrackings in CPPExampleWrapper.o
  "_rb_num2long", referenced from:
      _SWIG_RubyReferenceToObject in CPPExampleWrapper.o
      SWIG_AUX_NUM2LONG(unsigned long*)in CPPExampleWrapper.o
  "_rb_num2ulong", referenced from:
      SWIG_AUX_NUM2ULONG(unsigned long*)in CPPExampleWrapper.o
  "_rb_obj_classname", referenced from:
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_obj_is_kind_of", referenced from:
      _SWIG_Ruby_ConvertPtrAndOwn in CPPExampleWrapper.o
  "_rb_raise", referenced from:
      _wrap_new_JobOrder(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_src_location_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_src_location_get(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_dst_location_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_dst_location_get(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_xfer_params_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_JobOrder_xfer_params_get(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      ...
  "_rb_rescue", referenced from:
      SWIG_AsVal_unsigned_SS_long(unsigned long, unsigned long*)in CPPExampleWrapper.o
      SWIG_AsVal_long(unsigned long, long*)in CPPExampleWrapper.o
  "_rb_str_append", referenced from:
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_str_cat", referenced from:
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_str_cat2", referenced from:
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_str_new", referenced from:
      SWIG_FromCharPtrAndSize(char const*, unsigned long)in CPPExampleWrapper.o
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_str_new_cstr", referenced from:
      _SWIG_Ruby_NewClassInstance in CPPExampleWrapper.o
      _SWIG_Ruby_NewPointerObj in CPPExampleWrapper.o
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_string_value_ptr", referenced from:
      _wrap_XferParams_exclude_patterns_set(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _wrap_CPPTransfer_SetExcludePattern(int, unsigned long*, unsigned long)in CPPExampleWrapper.o
      _SWIG_Ruby_MangleStr in CPPExampleWrapper.o
      SWIG_AsCharPtrAndSize(unsigned long, char**, unsigned long*, int*)in CPPExampleWrapper.o
      Ruby_Format_TypeError(char const*, char const*, char const*, int, unsigned long)in CPPExampleWrapper.o
  "_rb_uint2big", referenced from:
      SWIG_From_unsigned_SS_long(unsigned long)in CPPExampleWrapper.o
  "_rb_undef_alloc_func", referenced from:
      _Init_CPPExample in CPPExampleWrapper.o
  "_rb_undef_method", referenced from:
      _SWIG_Ruby_define_class in CPPExampleWrapper.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status

Perhaps not so coincidentally, all of the undefined symbols are members of the Ruby C API. Am I missing something at compile- or link-time? Alternately, perhaps there is something wrong with the 32-bit OS X build of Ruby created to facilitate generation of this extension?
Any feedback is greatly appreciated.
Cheers,
James

A:

In this case, it turns out that the problem was that Xcode had installed a 64-bit version of Ruby and put it on the system path. In order to resolve the issue, I had to explicitly specify the path to the 32-bit version of the Ruby binary on the link line:
g++ -arch i386 -shared -fPIC -o ../lib/cppexample.so ./bin/CPPExampleWrapper.o ../qa_cpp_utils/bin/CPPExampleObject.o ../qa_cpp_utils/bin/CPPExampleCallbackFunctor.o ../qa_cpp_utils/lib/libcppexamplearchive.a -L/PATH/TO/32BIT/RUBY -framework CoreFoundation -lpthread

This was not a problem in Linux, because the version of Ruby on the system path was built for the architecture being linked.
James


Q:

Axios (in React-native) not calling server in localhost

I'm building a really easy api and react-native application. The server works well (tested with PostMan) but the application doesn't call the server.  It blocks when axios has to send the post request (see below).
I'm desperate :-( Loosing too mush time in it. Please, if you can help me...
Here is my code LogIn page. It dispatch the action creator (working with redux) giving email and password:
...
const LogIn = React.createClass({
  submitLogin() {
    // log in the server
    if (this.props.email !== '' && this.props.psw !== '') {
      if (this.props.valid === true) {
        this.props.dispatch(logIn(this.props.email, this.props.psw));
      } else {
        this.props.dispatch(errorTyping());
      }
    }
  },
...

email and password are weel retrieved and sent to the action creator:
import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
  return function (dispatch) {
    console.log(email);
    console.log(password);
    console.log(SIGNIN_URL);
    return axios.post(SIGNIN_URL, { email, password })
    .then(
      (response) => {
        console.log(response);
        const { token, userId } = response.data;
        dispatch(authUser(userId));
      }
    )
    .catch(
      (error) => {
        console.log('Could not log in');
      }
    );
  };
};
const authUser = (userId) => {
 return {
 type: 'AUTH_USER',
 userId
 };
};
...

The three console.log() before axios show the data in the correct way. SIGNIN_URL is exactly the same I use in postman. ...but axios doesn't call.
Just to give all the cards, this is my store:
import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
 const store = createStore(reducer, initialState, compose(
 applyMiddleware(thunk),
 autoRehydrate()
 ));
 persistStore(store, { storage: AsyncStorage });
 return store;
};

There's no error message in the debugger (but the one given by the axios call ('Could not log in')
I'm on windows 10, with:
"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"

The call fails even when I prepare a simple GET call and the server is supposed to give back a simple message (tested with postman and browser):
exports.test = () => {
  return function () {
    return axios.get('https://localhost:3000/v1/test')
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

Last, I tryed also to modify the call adding a header as the following, because the api is coded to accept json:
const head = {
  headers: { 'Content-Type': 'application/json' }
};

exports.test = () => {
  return function () {
    return axios.get('https://api.github.com/users/massimopibiri', head)
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

but even this didn't work. hope somebody can help me. Other similar issues didn't.

A:

The solution came from a different source, but I post it here to help others looking for the same issue. Basically I used Android AVD (emulator) to build the application. But the emulator is in fact another machine, and that's why it couldn't call the localhost.
To solve the probleme, I had to send the request in the following way:
https://10.0.2.2:3000/v1/test

instead of:
https://localhost:3000/v1/test

A:

if u are using mac this solution worked for me.
I am using React Native with Android Simulator ADV. Nexus Api 27
            axios.get('http://192.168.1.21:8686/api/v1/test')
            .then(response => console.log(response))
            .catch(err => console.log(err));

where the ip 192.168.1.21 is from system preferences > Network > Advanced > TCP/IP > IPv4 Address
I also tested axios.get('http://10.0.2.2:8686/bec/api/v1/test') where 10.0.2.2 is localhost from virtual machine to the computer but not worked.

A:

Your Emulator is a device on it's own that is not running on the same IP(localhost or 127.0.0.1) as your web browser, postman or your server.
In order to make request to your server from your emulator you need to access your server via your computer IP Address:
On windows get your IP Address by running ipconfig on the command prompt
On Unix terminal (Linux, Mac OS) run ifconfig to get your IP Address
Instead of http://localhost:port you should use http://your_ip_address:port
I didn't test it on Linux, Mac OS but its working perfectly on windows!


Q:

Getting started with cocoa drawing

I want to do some custom drawing in a NSView subclass where should I get started?

A:

Apple's Introduction to Cocoa Drawing Guide is the best place to start. Lots of examples there.

A:

As Jarret mentioned the Apple docs are a great place to start. However, some things to bear in mind:
The default coordinate system used with views is the Cartesian coordinate system where the origin is in the bottom left corner of the view. Most often you want the origin to be in the top left corner of the view so this is where you override the isFlipped: method (the default implementation which returns NO), returning YES:
- (BOOL)isFlipped
{
    return YES;
}

This "flips" the coordinate system so that the origin becomes in the top left corner, after a vertical flip has taken place. This can make some drawing position calculations easier.
The main things you'll probably want to get started with are things such as:

Filling basic rectangles (using the NSBezierPath class method fillRect:, along with the NSColor class for setting and using colours).
Working with images (using the NSImage class and the drawing methods it provides).
Paths, where you can draw lines and other shapes (with the NSBezierPath class).

You'll also want to take a look into Graphics Contexts at some point, and working with setting attributes (such as the current colour, a shadow etc) on them, used for subsequent drawing operations.
Probably not of immediate concern, but just a side note, that at some point you should take a look at the Optimizing View Drawing section of the View Programming Guide for Cocoa. Drawing operations should be fast, and it amazes me sometimes how little consideration people put into the performance aspects of drawing, when there are some basic things you can do to make your drawing – and therefore application – more efficient, such as only redrawing parts of the view that have actually changed, rather than the entire thing.


Q:

How to keep organized Web Sites for Inspiration

I usually find inspiration from many CSS Galleries, But I don't have an idea of how I can keep organized all those nice creations for inspiration. I've tried to make some bookmarks in Chrome but I don't like this idea much. I'd prefer to have atleast a small thumbnail for a fast preview.
Do you have any idea?
Thanks.

A:

You could try a social bookmarking site like delicious.com. You don't get the thumbnails (which would go out of date anyway) but you can tag your bookmarks with keywords, making it quite a powerful, searchable resource.


Q:

A non well formed numeric value encountered laravel time calculate

hello i'm try to calculate the duration but it don't work
this is my controller function :
public function store(Request $request)
{
    $pan = New Pan();
    $pan->startime = $request->input('startime');
    $pan->endtime = $request->input('endtime');
    $pan->duration = ($request->input('endtime') - $request->input('startime'));
    $pan->save();
    return redirect()->route('pan.index');
}

A:

This may mean that your endtime and startime values are strings, which cannot be subtracted. If they are well-formed date/time strings, you should be able to do this:
$pan->duration = strtotime($request->input('endtime')) - strtotime($request->input('startime'));

The function strtotime will convert your strings into integer timestamps, and the resulting duration will be in units of seconds.


Q:

Receiver MainVIewController has no segue iOS

Question was solved! See the code at the bottom.
I'd like to pass some data between 2 controllers. I have MainViewController class where GoogleMap is loaded. On click at custom info window for each GMap's marker I want to open new window with place details.
My storyboard is:

Segue was named: showPlaceDetails:

Several methods was written:
- (void) mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    [self performSegueWithIdentifier:@"showPlaceDetails" sender: nil];
}

(I also tried to use sender: [marker snippet]).
My prepareForSegue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showPlaceDetails"]) {
        //[[segue destinationViewController] setDelegate:self];
        PlaceDetailsViewController *destViewController = segue.destinationViewController;
        //Pass some data
    }
}

But I got the message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (RelaxInKZViewController) has no segue with identifier 'showPlaceDetails''
I did these steps:

Add New View Controller on storyboard.
Add Objective-C Class called PlaceDetailsViewController.
Change custom class of newly added VC to "PlaceDetailsViewController"
Add that code
Clear Simulator's data and clean project

And nothing. I hope you can help me :)
Thx, Artem.

Mr_bem has adviced me to refuse segues and use pushViewController method. It's good!
UIStoryboard *iPhoneStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    PlaceDetailsViewController *destViewController = [iPhoneStoryboard instantiateViewControllerWithIdentifier:@"PlaceDetailsViewController"];
    destViewController.placeData = marker.placeData;
    [self.navigationController pushViewController:destViewController animated:NO];

A:

You are using a Push segue, this can only be performed with a navigationController, like:
[self.navigationController performSegueWithIdentifier:@"showPlaceDetails" sender: nil];

Note you should have a navigation controller before your ViewController, the one that pushes.
Or if you want, you can change its type to Modal, everything should work great for you (Y)
UPDATE
Okay, here's what I propose, remove the segue, make the storyboardID of your PlaceDetailsViewController to PlaceDetailsViewController from the IB, and add this code instead
    - (void) mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
        PlaceDetailsViewController *destViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PlaceDetailsViewController"];
[self.navigationController pushViewController:destViewController animated:YES]
se
    }

THIS MUST WORK! LOL!


Q:

Finding the largest 16:9 rectangle within another rectangle

I am working on this Lua script and I need to be able to find the largest 16:9 rectangle within another rectangle that doesn't have a specific aspect ratio. So can you tell me how I can do that? You don't have to write Lua - pseudocode works too.
Thanks!
This I have tried and can confirm that won't work on lower ratio outer rects.
if wOut > hOut then
wIn = wOut
hIn = (wIn / 16) *9
else
hIn = hOut
wIn = (hIn / 9) * 16
end

A:

heightCount = originalHeight / 9;
widthCount = originalWidth / 16;

if (heightCount == 0 || widthCount == 0)
    throw "No 16/9 rectangle";

recCount = min(heightCount, widthCount);

targetHeight = recCount * 9;
targetWidth = recCount * 16;

So far, any rectangle with left = 0..(originalWidth - targetWidth) and top = 0..(originalHeight - targetHeight) and width = targetWidth and height = targetHeight should satisfy your requirements.


Q:

Unexpected Html.EditorFor behavior in ASP.NET MVC 2

I am getting some unexpected behavior from Html.EditorFor().
I have this controller:
[HandleError]
public class HomeController : Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Lister()
    {
        string[] values = { "Hello", "world", "!!!" };

        return View(values);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Lister(string[] values)
    {
        string[] newValues = { "Some", "other", "values" };

        return View(newValues);
    }
}

And this is my view which is intended to work for both of these:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<string[]>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Lister
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Lister

    <% using (Html.BeginForm()) { %>
        <% foreach (string value in Model) { %>
            <%= value %>

        <% } %>
        <%= Html.EditorForModel() %>
        <input type="submit" value="Append Dashes" />
    <% } %>

</asp:Content>

And the problem is that when the post back is made from the view, it hits the correct action, but the text boxes still show the original hello world data while the foreach loop outputs the new values.  It feels like something in ASP.NET is overriding my model values from updating the text boxes and they are just displaying the same old values.
I found this issue while trying to learn EditorFor with an IEnumerable.

A:

This is not a problem, it is the normal behavior. All helpers work that way. They first look at posted values and then the model in order to perform the binding. That is to say even if you modify the model in your controller action, they will use the initial posted values.
Related questions:

Second dropdown list selected item does not change in ASP.NET MVC
Possible bug in ASP.NET MVC with form values being replaced


Q:

How can I get text from txt URL ? How can I use Filereader from Angular 7?

“Iwant to get text data from txt url, and fetch it in angular web. How can I get text from txt URL ? How can I use Filereader from Angular 7 ???”
“This is for Angular 7 .”
<a (click)="getTextFile()">Check</a>

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {
  HttpClient,
  HttpRequest,
  HttpResponse,
  HttpParams,
  HttpHeaders
} from '@angular/common/http';

@Component({
  selector: 'autocomplete-overview-example',
  templateUrl: 'autocomplete-overview-example.html',
  styleUrls: ['autocomplete-overview-example.css'],
})
export class AutocompleteOverviewExample {
 text:any;

  constructor(
     private http: HttpClient,
  ) {

  }

  getTextFile():void{
  this.http.get('https://creamson-intelli.slack.com/files/UFL3QQFP0/FL4N4SNFJ/young_ruskin_bond.txt').subscribe((data) => {
    this.text=data;
    console.log(this.text);
})
}
}

A:

check this

Working Example

service.ts
  getRawData(): Observable<any> {
    const api = 'https://www.w3.org/TR/PNG/iso_8859-1.txt';
    return this.httpClient.get(api,{ responseType: 'text' });
  }

component.ts
import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular 5';
  rawlist: any;

  constructor(private appService: AppService) {}

  ngOnInit() {}

  getRawData() {
    this.appService
      .getRawData()
      .subscribe(
        data => this.rawlist=data,
        error => console.log(error)
      );
  }

}

.html
<button (click)="getRawData()">get raw data </button>

 {{rawlist }}


Q:

slack doesn't recognize github webhook payload format

I'm trying to create a slack app that uses incoming webhooks. I want my github repository to post to slack whenever the wiki is updated. I believe I've set up the webhook on github just fine, because I can see that it is attempting a delivery whenever I update the wiki. However, there's always the error, "no_text". I think this error means slack is expecting an item named "text," but the payload from github provides none. I verified this by trying two curl commands from the command prompt (I'm on windows):
curl -X POST -H "Content-type: application/json" --data "{\"text\":\"Hello, World!\"}" [MY_WEBHOOK_URL]
curl -X POST -H "Content-type: application/json" --data "{\"foobar\":\"Hello, World!\"}" [MY_WEBHOOK_URL]
This first one works as expected; the message "Hello, World!" gets posted to the slack channel I wanted, and I got back the "ok" message from curl. The second one did not work; the message was not posted, and I got back the message "no_text" from curl.
I can think of two possible solutions to this problem:

Change the format of the payload coming from github to include an item called "text" and other properties slack actually recognizes.
Get slack to recognize the format the payload is already in, perhaps by telling it to post the contents of a property other than "text."

I don't know how to accomplish either of these, or if they're even possible. Or perhaps there's another solution I haven't thought of?
Note: I already tried to use the github slack app, but couldn't figure out how to get it to post updates to the wiki. (See my other question if you'd like: slack github integration doesn't find wiki repository)

A:

I'm actually looking to do the same thing as you right now. Because the github and slack hooks are fundamentally different, you will need to have something in the middle to process the github webhooks into a Slack message to be posted via an incoming webhook.
You're going to need to do a couple different things (in no particular order):

Set up Github to send out hooks for the specific events you wish to be notified of.
Configure a middle man (I am currently using AWS SNS and Lambda)
Set up slack for the webhook.

For the github webhooks, you will need to leverage the more powerful github API to create the hook. You could do this with curl, but that's kind of a pain so I am using a JS script to take care of it. You will need to npm install github bluebird in the same directory before running something like this:
var GitHubApi = require("github");

var github = new GitHubApi({
    // optional
    debug: true,
    protocol: "https",
    host: "api.github.com", // should be api.github.com for GitHub
    pathPrefix: "", // for some GHEs; none for GitHub
    headers: {
        "user-agent": "ocelotsloth-conf" // GitHub is happy with a unique user agent
    },
    Promise: require('bluebird'),
    followRedirects: false, // default: true; there's currently an issue with non-get redirects, so allow ability to disable follow-redirects
    timeout: 5000
});

// user token
github.authenticate({
    type: "token",
    token: "GITHUB_TOKEN_HERE",
});

// https://mikedeboer.github.io/node-github/#api-repos-createHook
github.repos.createHook({
  owner: "ocelotsloth",
  repo: "lib-ical",
  name: "amazonsns",
  events: [
    //"commit_comment",
    //"create",
    //"delete",
    //"gollum",
    //"issue_comment",
    "issues"
    //"label",
    //"milestone",
    //"pull_request",
    //"pull_request_review",
    //"pull_request_review_comment",
    //"push",
    //"release"
  ],
  config: {
    aws_key: "AWS_KEY",
    aws_secret: "AWS_SECRET",
    sns_region: "us-east-1",
    sns_topic: "SNS_TOPIC_ARN"
  },

}, function(err, res) {
    console.log(JSON.stringify(res, null, '\t'));
});

I remember following a blog post a while ago about setting up the SNS topic to work properly, but I don't remember exactly where it is anymore. Some googling should help. Also, you should be able to set up your own server for github to send these to and avoid having to set up AWS at all if you want to avoid the complexity. See https://mikedeboer.github.io/node-github/#api-repos-createHook for specific instructions on that method. You will need to use editHook after you create the hook, so either get it right the first time or use edit it. You just need to change the method call to editHook and add the id to the call as well.
Something important to see, you can define all of the different Events that you want github to send to you. For all of these, along with their formats, look at https://developer.github.com/v3/activity/events/types/.
To actually post these events to slack, I have a lambda script that currently looks like this (I literally just started writing this today, and haven't implemented more than just posting issue events, but it should do well as a starting point). For this script, you will need to npm install identify-github-event slack-webhook and have your incoming webhook set up as well.
var identifyGithubEvent = require('identify-github-event');
var SlackWebhook = require('slack-webhook')

// slack's link syntax
function link(url, txt) {
return "<" + url + "|" + txt + ">";
}

exports.handler = function(event, context) {
// 1. extract GitHub event from SNS message
var ghEvent = JSON.parse(event.Records[0].Sns.Message);
var eventType, eventName, numb;
console.log(ghEvent);

var ghEventType = identifyGithubEvent(ghEvent);

if (!ghEventType) {
  return;
}

var text = "Event!  " + ghEventType;

if (ghEventType === 'IssueCommentEvent') {
  var who = link(ghEvent.comment.user.html_url, ghEvent.comment.user.login);
  var what = link(ghEvent.issue.html_url, "Issue " + ghEvent.issue.number + ": \"" + ghEvent.issue.title + "\"");
  text = who + " commented on " + what;
}
else if (ghEventType === 'IssuesEvent') {
    var who = link(ghEvent.sender.html_url, ghEvent.sender.login);
    var action = ghEvent.action;
    var issueNumber = ghEvent.issue.number;
    var issueName = link(ghEvent.issue.html_url, ghEvent.issue.title + "\"");

    if (action === "opened" | action === "closed") {
        text = {
            attachments: [{
              "fallback": who + " opened Issue" + issueNumber + ": " + issueName,
              "color": "#36a64f",
              "pretext": "New issue " + action + ":",
              "author_name": ghEvent.sender.login,
              "author_link": ghEvent.sender.html_url,
              "thumb_url": ghEvent.sender.avatar_url,
              "title": "#" + issueNumber + ": " + ghEvent.issue.title,
              "title_link": ghEvent.issue.html_url,
              "text": ghEvent.issue.body,
              "fields": [
                {
                  "title": "Status",
                  "value": ghEvent.issue.state,
                  "short": true
                },
                {
                  "title": "Labels",
                  "value": ghEvent.issue.labels.map(label => label.name).join("\n"),
                  "short": true
                }
              ],
              "footer": "lib-ical",
              "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
              "mrkdwn_in": ["text"]
            }]
        };
    } else return;
}

  // 'commit_comment':
  // 'create':
  // 'delete':
  // 'issues':
  // 'label':
  // 'member':
  // 'milestone':
  // 'pull_request':
  // 'pull_request_review':
  // 'pull_request_review_comment':
  // 'push':
  // 'release':

var slack = new SlackWebhook('https://hooks.slack.com/services/SLACK-WEBHOOK-URL', {
  defaults: {
    username: 'GitHub -- user/project',
    channel: '#CHANNEL-NAME',
    icon_emoji: ':github:'
  }
})

slack.send(text);

};

It's far from perfect, but it gives a really nice result:

For that specific example it's an issue close, but currently that script will also work on open. The script also does limited markdown processing, so if the issue contains any source blocks, it will be rendered properly inside of slack.
I hope this helps you with your approach, feel free to ask me to elaborate on anything else.