vendredi 29 mai 2015

Submitting post between ajax and php

I'm a newbie in the world of php and I was trying to learn it with a simple page. I've created an html form and I want to send data using ajax but it still POST http://localhost/Home.php 500 (Internal Server Error)

In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)

This is my form (Home.php)

<div id="displayForm">

<form method="post" id="selectForm">
        <?php
        include ("Database.php");

        $Database = new Database( "localhost", "root", "1234");
        $Database->connectToServer();
        $Database->connectToDatabase("test");
        $Tables = $Database->countTable();
        foreach($Tables as $column) {
            echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " .  $column;
        }
        ?>
    <input type="submit" class="submit" name="createSelect">
</form> </div>

The php in the form is only for create the button with the name of the tables.

In the same file (Home.php)

<?php
 include 'ChromePhp.php';
 ChromePhp::log("corretto");
echo "ok";
?>

In the file Home.php, in the head section I've included all jquery library and the js file

<script src='jquery-1.10.2.min.js'></script>
<script src='Script.js'></script>

And this is my ajax file

$(document).ready(
    function() {
        $("#createTable").click(goCreate);
        $("#displayTable").click(goDisplay);
        $('#selectForm').submit(goSelect);
        $("#createForm").hide();
        $("#displayForm").hide();
    }
);

function goCreate(data) {
    $("#createForm").show();
    $("#functions").hide();
}

function goDisplay(data) {
    $("#displayForm").show();
    $("#functions").hide();
}

function goSelect() {
    var selectedTable = $("#selectQuery:checked").val();
    console.log($("#selectQuery:checked").val());


    $.ajax({
        url: "Home.php",
        type: "POST",
        dataType: "html",
        data: {
            'select': 'display',
            'table': selectedTable
        },
        success: function(msg) {
            console.log(msg);
        },
        error: function(xhr, desc, err) {
            console.log("error");
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }

    }); // end ajax call
    return false;
};

How do I update the location field when I chnge the latitude, longitude coordinates manually?

I am using jquery location picker plugin to take the entry of user's location through a map.

The problem that I 'm facing is that when I change the lat, long coodinates manually, the location field does not shift accordingly to the correct position however the marker does.

What is the solution?

Here is the map that I'm using http://ift.tt/1HAeglQ

extract vimeo video id from the url

Though this question is available on SO, I am facing a little problem.I failed to extract the vimeo id using vimeo regex used here: Vimeo Regex

My codes I,m using now:

function vimeoProcess(url){
   var vimeoReg = /https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
   var match = url.match(vimeoReg);
   if (match){
      console.log(match[3]);
   }else{
      return "<span class='error'>error</span>";
   }
}

It does not consoles any thing. Can any one help?

JQgrid file upload with form edit

I have JQgrid with form edit.

 jQuery("#tblPriceListUpload").jqGrid({
        url: $('#tblPriceListUpload').attr("RequestUrl"),
        postData: { PriceListType: SelectedPriceListType },
        datatype: "json",
        mtype: "Get",
        hoverrows: false,
        ajaxGridOptions: { timeout: 30000 },
        colNames: PriceListColName,
        colModel: PriceListColModel,
        cmTemplate: { editable: true },
        rowNum: 10,
        hidegrid: false,
        rownumbers: true,
        pager: '#PriceListGridPager',
        viewrecords: true,
        caption: "Price List ",
        height: 'auto',
        scrollOffset: 0,
        gridview: true,
        shrinkToFit: true,
        autoencode: true,
        loadonce: true,
        ignoreCase: true,
        enableClear: true,
        width: '1000',
        beforeRequest: function () {

            //responsive_jqgrid($(".jqGrid"));
        }
    });

    $('#tblPriceListUpload').jqGrid('filterToolbar', { searchOnEnter: false, enableClear: false, defaultSearch: "cn", stringResult: true });

For Form Add

  $("#tblPriceListUpload").jqGrid('navGrid', '#PriceListGridPager',
           { edit: true, add: true, del: true, refresh: true, view: false, search: false },
           { //Edit Code here
               }, {

               caption: "",
               title: "Add Attachment",
               id: "add_Attachment",
               buttonicon: "ui-icon-plus",
               position: "first",
               url: 'AddPriceList',
               recreateForm: true,
               onclickSubmit: function (response, postdata) {
                   debugger;
                   if (jqXHRData) {
                       //jqXHRData.submit();
                       $("#Form").submit();
                       $("#FormError").remove();

                   }
               },
               beforeShowForm: function (form) {
                   $("#PriceListType").val(SelectedPriceListType);
                   $("#tr_PriceListType").hide();
                   $('#FileName').fileupload({
                       replaceFileInput: false,
                       dataType: 'json',
                       url: 'AddPriceList',
                       change: function (e, data) { },
                       add: function (e, data) {
                           jqXHRData = data
                       },
                       done: function (event, data) {

                           alert(data.result.message)
                           $("#cData").trigger('click');
                           $("#tblPriceListUpload").setGridParam({ datatype: 'json', page: 1 }).trigger("reloadGrid");
                           jqXHRData = null;
                       },
                       fail: function (event, data) {

                           if (data.files[0].error) {
                               alert(data.files[0].error);
                           }
                       }
                   });
               }

           }, {});

And Col Model Below

     var PriceListColModel = [{ name: 'DisplayDescription', index: 'DisplayDescription', align: 'center', editable: true, },
           {
               name: 'Header', index: 'Header', width: 95, align: 'center', formatter: 'select', editable: true,
               edittype: 'select', editoptions: { value: HeaderList, defaultValue: 'HP Oct 12 - GOs' },
               stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + HeaderList }
           },

    {
        name: 'OneSeriesPerPage', index: 'OneSeriesPerPage', align: 'center', formatter: 'checkbox', edittype: 'checkbox',
        editoptions: { value: "true:false", defaultValue: "true" }, editable: true
    },
{
    name: 'EnvironmentCode', index: 'EnvironmentCode', search: true, editable: true,
    edittype: 'select', editoptions: { value: EnvList, defaultValue: 'AFI' },
    stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + EnvList }
},
{
    name: 'FileName', index: 'FileName', edittype: 'file', editable: true,
    edittype: 'file',
    editoptions: {
        enctype: "multipart/form-data"
    }, search: true
},
    {
        name: 'PriceListType', index: 'PriceListType', align: 'center', hidden: true, editrules: {
            required: true,
            edithidden: true
        }
    }];

In "OnclickSubmit" event of "AddPriceList" if i am posting jqXHRData.submit(); If Check Box column is false it is not sending the data to controller. If true, it is sending the data to controller.

If i am posting the form $("#Form").submit(); I am not getting the file in Controller.

Please help on this issue.

Chomsky Normal Form using JavaScript : Stuck

I have been trying to implement a web application that converts the given context free grammar into its Chomsky Normal Form (CNF). The CodePen link to the same is http://ift.tt/1HAeeud

The only region where I am stuck is breaking down the rules of form S -> aAb into further nonterminals and terminals. Can anyone help me with an implementation algorithm regarding the same?

Track JS CSS Asset Errors on page load

Is it possible to track the number of errors and warning thrown by a browser on page load using javascript?

For example CSS Assets missing or images missing or js script errors? I don't need a detailed log but maybe a count of each type of error.

Like a count of CSS, Assets missing and JS Errors?

This needs to be tracked using JS.

Testing functionality based on HTML5 DOM-methods

I'm wondering how to test functionality based on HTML5 DOM-methods. Like the new dialog-API for example.

Consider the following function;

function show(dialog)
{
    if(typeof(dialog.showModal) !== "function")
        throw new Error("Update your browser");
    dialog.showModal();
}

I want to make sure that

  1. an error is thrown when the method is not available
  2. dialog.showModal is called if available

I'm currently running karma + jasmine with the firefox and chrome launchers but none of them seems to support the dialog-API.

Can I shim this in some kind of way? Can I create a function on all dialog DOM nodes?

I could do the following

var modal = document.createElement("dialog");
Object.defineProperty(modal, "showModal", {
    value: function()
    {
        console.log("hello world!");
    }
});

however, that isn't carried over to other instances of a dialog.

This is a very simplified example of what I'm trying to achieve.

Creating and returning object from function: can this avoid garbage collection?

If I have a function that creates an object, do some stuff and than returns it. If it's true that objects are passed by reference, does this mean that the function that creates the object (or the function's scope chain) will not be available for garbage collection?

Example code:

function convertArrayToObj(array){
   var newObj = {};
   array.forEach(function(item, index){
      newObj[index] = item;
   });
   return newObj;
}

I hope I made my doubt clear

Selecting all check boxes when only clicking one

enter image description here

How can I select all the check boxes on single click, while every check box has unique name using JavaScript? Please provide code.

 </div><!-- /.box-header -->
 <div class="box-body">
 <form name="permissionfrm" method="post" id="permissionfrm">
 <input type="hidden" name="permission" id="permission" value="assignpermission" />
  <table id="example1" class="table table-bordered table-striped">
    <thead>
     <tr>
      <th>Give All Permissions
      </th><td><input type="checkbox" name="addadmin" id="addadmin" value="Check All" onClick="this.value=check(this.form.list)"/></td>
      </tr>
      <tr>
        <th>Add</th>
        <th>Edit</th>
        <th>View</th>
        <th>Delete</th>
      </tr>
     </thead>
    <tbody>

Can Bower give conflict in my code?

If Bower update my code automatically, Can I get conflicts? It's possible my code was decrepitated. I think so. Maybe Bower Could be a problem in a proyect. How manage this problem?

Cheers!

Timing and speed of multiple sliding divs

Please see this fiddle I have set up.

You are first confronted by three links. Each link triggers divs to slide out.

  1. The link 'john smith' slides out and in at the speed we want. When it slides out the first line slides out then when that is completed the second line slides down as though coming from the first. When it slides back it does the same motion at the same speed but reverse i.e.. the second line slide back up first and then when that is completed the first line slides back to the left.

  2. When you click on the work link and menu slides out in the same manner as the bio. Also there is a sub menu that slides out when on clicks on item 2.

  3. When the user clicks on the contact link one line slides out.

What we need to achieve is this; when any div is open and another link is clicked on, the visible div slides back in reverse to how they slid in. We have almost achieve this, however, the code is not quite right as the divs are not sliding back in at the same speed and in the right order, they simply slide back fast. For example, if one has clicked on 'work' and the 'item 2' link, and then you select 'contact' the opened div slide back very quickly. What I need to achieve is that they slide back in reverse to how they slid out.

I know this sounds very complicated and if I can answer any questions to make it clearer I will.

Thanks

$('#bio-line-1').animate({width: 'hide'});
$('#contact-info').animate({right: 'hide'});
$('#bio-line-2').slideUp("fast");
$('#black-div, #black-credits, #igna-1-div, #igna-1-credits, #igna-2- div, #igna-2-credits, #fatal-div, #fatal-credits').fadeOut('100');

});

Sum Array push values, before a 0 javascript

I'm trying to take the value of an input and keep it in an array. I want to detect when the user text 0, and I want to sum all the values in the array before the 0.

Here is my code:

<form id="demo">
    <input type="number" id="lala">
    <button onclick='funsuma(this.form.lala.value)' > NO <button/>
</form> 

<script>
    var global = [];
    var suma = 0;

    function funsuma(valor) {
        global.push(valor);
        for (i = 0; i < global.length; i++) {
            if (global[i] == 0) {
                suma += parseInt(global[i], 10);
                alert("Es 0, tu suma es: " + suma);
                return false;
            } else {
                //alert(global[i]);
                document.getElementById("demo").innerHTML = "<input type='number' id='lala'> <button value='Envia' onclick='funsuma(this.form.lala.value)'> NO <button/>";
                return false;
            }   
        }

        //console.log("global");
    }
</script>

I need to popup different html pages for different url in chrome extension

For example if someone is on google.com I need to popup a different page and if someone is on xyz.com I need to pop a different page. Is that possible?

Javascript sort() array of mixed data type

If I have an array like:

["23", "765", "sfasf", "2.3E-3", "2.3cE-3"]

How can I order it so numbers(decimals, floats or scientific notation) are ordered ascending and after those strings that aren't numbers(for example "sfasf" or "2.3cE-3")?

Expected order of the example array:

["2.3E-3", "23", "765", "2.3cE-3", "sfasf"]

slick slider not initializing in Internet Explorer 8

This is the code I have, any reason why this might be? It's just not initalising.

<div class="slider-banner slick-slider">
    <div class="slide1 slide slick-slide">
        ...
    </div> 
    <div class="slide2 slide slick-slide"></div> 
    ...

    <script src="http://ift.tt/1h847p1"></script>
    <script src="../scripts/slick.min.js"></script>

$('.slider-banner').slick({ 
    dots: false,
    infinite: true,
    speed: 600,
    mobileFirst: true,
    slidesToShow: 3,
    slidesToScroll: 3,        
    onInit: function() {
        $('.slider-banner').addClass("loaded");
    },
    responsive: [{
        breakpoint: 1280,
        settings: {
            slidesToShow: 5,
            slidesToScroll: 1,
        }
    }, {
        breakpoint: 1600,
        settings: {
            slidesToShow: 7,
            slidesToScroll: 1,
        }
    }]
});

Using javascript's date.toISOString and ignore timezone

I want to use the javascript's toISOString() function and ignore the timezone.

var someDate; // contains "Tue May 26 2015 14:00:00 GMT+0100 (Hora de Verão de GMT)"
dateIWant = someDate.toISOString(); // turns out "2015-05-26T13:00:00.000Z"

The date to convert is Tue May 26 2015 14:00:00 GMT+0100 (Hora de Verão de GMT) but the converted date is 2015-05-26T13:00:00.000Z.

So, I need the date in the yyyy-MM-ddTHH:mm:ss:msZ but as you can see above it applies the timezone and changes the hour from 14 to 13.

How to achieve this?

How to improve Gulp task performance with gulp-sass plugin?

I have a sass file with long loop (generate about 800 lines of CSS) that compiles about 25 seconds. It's too long.

How can I minimize compile time?

Thanks!

How to check if changes to innerHTML have completely loaded

I'm changing the content of a div via javascript using myDiv.innerHTML = xmlHttp.responseText. xmlHttp.responseText might contain a few images which will be loaded after the div's innerHTML has been changed.

Is there any event which is fired on the div, document or window after those images have completed loading ie after innerHTML of an element has completely loaded?

Collapse row on mouse click

I found one very good example of Collapsible Content on Internet but it's unfinished.

<div class="container faq_wrapper">
    <div class="row">
        <div class="span10 offset1">
            <p>
                &nbsp;</p>
            <div class="faq-all-actions">
                <a class="faq-expand" onclick="jQuery('.answer-wrapper').css('display','block');">Expand All</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class="faq-collapse" onclick="jQuery('.answer-wrapper').css('display','none');">Collapse All</a></div>
        </div>
    </div>
    <div class="row">
        <div class="span10 offset1">
            <div class="question-wrapper">
                <div class="arrow">
                    &nbsp;</div>
                <div class="big-q">
                    Q</div>
                <div class="question">
                    <h6>Can I try the software before I buy it?</div></h6>
                <div class="answer-wrapper">
                    <div class="big-a">
                        A</div>
                    <div class="answer">
                        Yes! Simply <a href="/trial">download a free trial</a> and you&#39;ll have instant access to all features for 30 days, absolutely free. We don&#39;t require your credit card details or any commitment.</div>
                </div>
            </div>    
        </div>
    </div>
</div>

How I can expand or hide the answer from the example when I click on the row?

Finding text within Javascript

I'm creating some functions to highlight words on a page.

The way the code works is to take the innerHTML when the page loads, and store this in memory.

I then take a copy of innerHTML - I then find the search words on the copy of innerHTML page, and wrap them with <span id="find-iteration"> tags and replace the contents of the page with the copy of innerHTML. Then, when the user re-hits the search button, I revert the page back to the original innerHTML

How to do I find text (website copy) only words and note words used as values in HTML elements/attributes.

Example, Consider the following code

 <div class="search">This is the search box</div>

Now, I want to perform a search for the word "search". The issue is, it will find it twice.

Without using regular expressions, and only using JavaScript (no jQuery please), how can I detect if the string is part of the HTML tag or not?

Cordova - (Phonegap) get Device DPI and Density Pixels

I am developing a phonegap (cordova) project and I want to get the DPI of the device. Is this possible?

In Android native JAVA API there is a Class named DisplayMetrics which provides getDisplayMetrics().xdpi/ydpi method to get device DPI.

Is there any method to get device DPI in Cordova or Phonegap ?

How to Write Controller Time Variables for Angular Timer ?

Iam Using http://ift.tt/1jw86ZJ which is working good with Some Constant Formatting like

<timer interval="1000">{{hours}} hour{{hoursS}}, {{minutes}} minute{{minutesS}}, {{seconds}} second{{secondsS}}.</timer> 

But when trying to load hour and minutes ,seconds from Controller it is not happening

Code Follows

My Controller :-

 Mymodule.controller('timingcontroller'),[],

    function($scope,$rootScope,moment){
       $scope.timings = function () {

            $scope.timeZone='America/Denver';
            var TimeZoneHrs=moment().tz($scope.timeZone).format('HH');//Returns HH:mm 24 Hour Format
            var TimeZoneMinutes=moment().tz($scope.timeZone).format('mm');
            var TimeZoneSeconds=moment().tz($scope.timeZone).format('ss');

             $scope.TimeZoneHrs=TimeZoneHrs;
            $scope.TimeZoneMinutes=TimeZoneMinutes;
            $scope.TimeZoneSeconds=TimeZoneSeconds;

        };
      }

Angular View :-

<section  data-ng-controller="timingcontroller"  data-ng-init ="timings()">
        <timer >{{TimeZoneHrs}} hour{{TimeZoneHrsS}}, {{TimeZoneMinutes}}  minute{{TimeZoneMinutesS}}, {{TimeZoneSeconds}} seconds{{TimeZoneSecondsS}}</timer>

    </section>

Output:- hour, minute, seconds . But not the Scope related data as Timer

Iam Pretty New to this Timer Concept Could You Please Let me Know How can I achieve that ?

Thanks in Advance

AngularJS: avoid using $timeout to wait for image loading completion

I'm trying to create my own image carousel as an angularjs directive; I want to keep it as lightweight and unopinionated as possibile, so I thought I'd just create a <carousel></carousel> wrapper for a set of <img> elements, like so:

<carousel>
   <img ng-repeat="image in images" ng-src="{{image.src}}" alt=""/>
</carousel>

What the directive does is to simply create a <div class="carousel"> element into which the images are transcluded. Now, I still haven't coded the part where images slide or fade in/out cause there's one issues I'd like to get out of the way first: I want to assign the carousel and all the images therein the same height (computed as the height of the shortest image) so as to avoid the carousel from changing height when a taller image gets displayed, or avoid cropping the image in case the carousel had a fixed height.

So I jotted down this JSFiddle to demonstrate, but so far the best solution I found to compute the heights of the transcluded images relies on two nested $timeouts with a 100-ms delay. It looks to me more like a hack than anything.
So I was wondering if there's a "proper" way to accomplish it in angularjs. Cheers.

P.S. On a side note, I also dislike fetching the root element of the directive's template, the <div class="carousel"> in my case, using element.children()... is there no easy way to reference it in angularjs? Looked around but no dice.

Try { ... } catch { ... } on addEventListener

How can I add an try catch in a addEventListener? Is there any way?

    document.addEventListener("DOMContentLoaded", function (event) {
 X();
    });


    document.attachEvent("onreadystatechange", function () {
        if (document.readyState === "complete") {
            X();
        }
    });

How to add attribute and remove from an element in Angular JS

<input name="name" type="text" ng-model="numbers" mandatory>

How to remove and add class of mandatory dinamically in Angular JS?

Note : "mandatory" is custom class which is implemented by me.

Thanks.

Undefined property in array of arrays

I am working on an array of array, and I want to test each first value but all what I get is Uncaught TypeError: Cannot read property '0' of undefined. Help please!

 function getManualDesactivation(data){

var tab=[];
var l=data.length ; 
var listeService= getCategorie(data);
var resultat=[];

for(var i=0; i<l;i++){
        if (data[i][1] == "DESACTIVATION") {
            var subtab=[];
            subtab.push(data[i][0]);
            subtab.push(data[i][2]);
        tab.push(subtab);


        }       
}

if (tab.length > 1) {
    var j = 0;
    for (var i = 0; i < listeService.length; i++) {

        if (listeService[i] == tab[j][0]) {<---- here is the exception
            resultat.push(tab[j][1]);

            j++;
        } else {

            resultat.push(0);
            j++;
        }

    }
}

Build PHP array with string and result 2 dimensional arrays

I have a smart problem in PHP, I build an array with a string, and at the same time I cut some images. buildProject.php is include in index.php (session_start(); for _session is on the top of it).

buildProject.php

<?php
  $list_projet = array(
    0 => 'img0_pres',
    1 => 'img1_pres',
    2 => 'img2_pres',
  );
  $height_decoup = 500;
  $projet = array();

  foreach ($list_projet as $key => $value) {
    $name_source = $value;
    $img_source_file = 'images/projet/'.$name_source.'.jpg';
    $img_source = imagecreatefromjpeg($img_source_file);

    $width = imagesx($img_source);
    $height = imagesy($img_source);
    $ratio = ceil($height/$height_decoup);
    $img_dest_height = $height_decoup;

    $nb_img_decoup = 1;
    $img_source_y = 0;

    while ($nb_img_decoup <= $ratio) {
      if ($nb_img_decoup == $ratio) {
        $img_dest_height = $height - $height_decoup*($ratio-1);
      }
      $img_dest = imagecreatetruecolor($width,$img_dest_height);
      imagecopy($img_dest, $img_source, 0, 0, 0, $img_source_y, $width, $img_dest_height);
      $img_dest_file = 'images/projet/'.$name_source.'_'.$nb_img_decoup.'.jpg';
      imagejpeg($img_dest, $img_dest_file);

      $projet[$key][$nb_img_decoup] = $img_dest_file; // I SUPPOSE AN ERROR HERE
      $img_source_y += $height_decoup;
      $nb_img_decoup++;
    }
    imagedestroy($img_source);
    imagedestroy($img_dest);
  }
  echo $img_dest_file[0]; // give me an 'i' and suppose give me an error
  echo $projet[0][1][0]; // idem...

  $_SESSION['txt'] = $projet;
?>

After build it, I send it to getProjet.php to find it on main.js with getJSON. My Probleme is, when the array arrived in main.js, projet[0][0] return an ([object, object]).

I thinks the problem is on my first php but I put the other files maybe there are an other error can do that.

getProject.php

<?php
session_start();
$projet = $_SESSION['txt'];

if(isset($_GET['list']) && $_GET['list']>=0){
    echo json_encode($projet[$_GET['list']]);
} ?>

main.js

$.getJSON('php/getProject.php?list=' + index, function(data) {
    length = data.length;
    console.log(data+' //// '+length); // [object object] //// undefined
    console.log(data[1].length); // 29 (total of caracteres...)
    console.log(data[1]); // images/projet/img0_pres_1.jpg
    console.log(data[1][0]); // i
}

So in main.js data=([object object]) and I need data=([object]). I think it's because when i build my array $img_dest_file transform alone in array and it's normaly just a string not an array.

If someone has an idea why $img_dest_file transform alone in array? And I don't want that.

Thanks for reading. If you have question I can specify more.

Fullcalendar returning epoch time values to the database

I am using fullcalendar jquery plugin for my page.When i'm inserting new events using the fullcalendar plugin.., its returning me epoch time values instead of UTC timedate values.

Below is the code that inserts new data into the database on clicking a date.

    calendar.fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar
        drop: function() {
            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },

        eventSources: [

            {

                url: '/v1/calendar/',
                type: 'GET',
                dataType:'json',


            },
           calendar.fullCalendar( 'addEventSource', response )
        ],

        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay) {

            bootbox.prompt("New Event Title:", function(title) {
                var people_id=1;
                //var title=event.title;
                //var start=event.start;
                //var end=event.end;

                if (title !== null) {
                    calendar.fullCalendar('renderEvent',
                            {
                                people_id:people_id,
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },

                    true // make the event "stick"


                            );






                            $.ajax({
                                 url: '/v1/calendar',
                                 data: 'people_id='+people_id+'&title='+title+'&start='+start+'&end='+end,

                                 type: 'POST',
                                 dataType: 'json',
                                 success: function(response){
                                     bootbox.alert("Event Created!");

                                   console.log(response);
                                 },
                                 error: function(e){
                                   console.log(e.responseText);
                                 }
                               });  

                }
            });

The event is successfully added into the database...but the time is in epoch format.

the console response I'm getting is given below:

     {people_id: "1", evt_description: "testing", date1: "1431388800000", date2: "1431475200000", event_id: 4}

I'm using laravel framework at the backend I'm attaching my CalendarController below:

    <?php

class CalendarController extends \BaseController {

/**
 * Display a listing of calendar
 *
 * @return Response
 */
public function index()
{
    $event = DB::table('events')

    ->leftJoin('people','people.people_id','=','events.people_id')  
    ->leftJoin('people_roles','people_roles.people_id','=','events.people_id')      
    ->get(array('events.people_id','events.event_id','events.evt_description','events.date1','events.date2','events.time'));    
    //return View::make('people.show', compact('address'));
    //return Response::json($event);
    $id=array();
    $title=array();
    $start=array();
    $end=array();
    $i=0;
    foreach ($event as $events)
        {

            $id[$i]=$events->event_id;
            $title[$i]=$events->evt_description;
            $start[$i]=$events->date1;
            $end[$i]=$events->date2;
            $i++;           
        }
    return Response::json(array('id'=>$id,'title'=>$title,'start'=>$start,'end'=>$end));
}

/**
 * Show the form for creating a new calendar
 *
 * @return Response
 */
public function create()
{
    return View::make('calendar.create');
}

/**
 * Store a newly created calendar in storage.
 *
 * @return Response
 */
public function store()
{
    $events= Input::get('type');
    $events= new Events;
    $events->people_id = Input::get('people_id');
    $events->evt_description =Input::get('title');
    $events->date1 =Input::get('start');
    $events->date2 =Input::get('end');
    //$events->time =Input::get('time');

    $events->save();


    return Response::json($events);
    //return Redirect::route('calendar.index');
}

/**
 * Display the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $calendar = Calendar::findOrFail($id);

    return View::make('calendar.show', compact('calendar'));
}

/**
 * Show the form for editing the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $calendar = Calendar::find($id);

    return View::make('calendar.edit', compact('calendar'));
}

/**
 * Update the specified calendar in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    //$type=Input::get('type');
    $event_id= Input::get('event_id');
    $title= Input::get('title');
    $roles = DB::table('events')
                ->where('event_id','=',$event_id )
                ->update(array('evt_description' => $title));
    return Response::json(array('id'=>$event_id,'title'=>$title));



}

/**
 * Remove the specified calendar from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy()
{
//  Calendar::destroy($id);
$event_id= Input::get('eventid');
DB::table('events')->where('event_id','=',$event_id)->delete();

return Response::json($event_id);

//  return Redirect::route('calendar.index');
}

}

How to add another statement in IF with JQUERY [duplicate]

This question already has an answer here:

I combine primefaces with SVG and onclick. If I write just the first part "if($(window).width()>800){PF('dlg_p').show();}" there is no problem, but if I want to add another restriction don't work.

<svg width="200" height="210" onclick="if($(window).width()>600)&&($(window).height()>600){PF('dlg_s').show();}">

But the console gives me an error I can't solve:

Error Traced [line 313] The entity name must appear immediately after '&' in the entity reference.

jQuery - Help to define invalid date in age gate

I'm setting up an age gate for a clients page that contains alcohol. The visitor must fill in day, month and birthyear and also country. The form is connected to minimum purchase ages in different countries.

I've managed to get the form to redirect to startpage if they are old enough or display "Sorry, you're not old enough to enter this site" if they are too young. So far so good.

But I also need the form to display "Please enter a valid date of birth" if they put in something that isn't an actual date.

Is there a way to define var invalidDate =

invalidDate could be if they enter letters instead of numbers, but also much appreciated would be if invalid for Day is anything that isn't between number 1-31, for month anything that isn't number 1-12 and for year anything that doesn't start with 19XX or 20XX.

Sorry if I'm being unclear...

The form as it is right now (most countries removed because the list was so long):

<script type="text/javascript">

var 
$ = $||jQuery;
countries = {
    "Sweden": 20,
    "Denmark": 18,
    "Other": 21,
}

$(document).ready(function() {
    $("form").submit(function(e) {
        e.preventDefault();
        var day = parseInt($("input[name=day-796]").val());
        var month = parseInt($("input[name=month-664]").val() - 1);
        var year = parseInt($("input[name=year-262]").val());
        var dateOfBirth = new Date(year, month, day, 0, 0, 0, 0);
        var ageDifMs = Date.now() - dateOfBirth.getTime();
        var ageDate = new Date(ageDifMs); 
        var age = Math.abs(ageDate.getUTCFullYear() - 1970);
        var country = $("select").val();
        var hasAccess = age >= countries[country];
        var noAccess = age <= countries[country];
        if (hasAccess) {
            window.location.href = "www.startpageURL.com";
        } else if (noAccess) {
            document.getElementById("warning_output").innerHTML = "Sorry, you're not old enough to enter this site.";
        }
    })
})
</script>

Any suggestions would be much appreciated!

Javascript Hover and Toggle

My navigation is hidden and hover is showing but disappearing immediately, I want the navigation to show on hover and display: none on mouse out of the element

$(document).ready(function(){
    $("#nav-holder").hover(function () {
        $("nav").animate({height: 'toggle'});
    });
});

Emscripten, Embind, Error: no instance of constructor

I am trying to convert classes (and structs) from C++ to Javascript using Emscripten. For this I want to use Embind. I am trying to convert a very simple example but even with this example I am getting an error. My Code:

#include "C:\\Emscripten\\emscripten\\1.30.0\\system\\include\\emscripten\\bind.h"

using namespace emscripten;

class AddTest
{
public:
    static unsigned int addTest(unsigned int stepCount);

};

EMSCRIPTEN_BINDINGS(AddTest)
{
    class_<AddTest>("AddTest")
        .constructor<>()
        .class_function("addTest", &AddTest::addTest)
        ;
}

With this code, it gets me an error:

"Error: no instance of constructor "class_BaseSpecifier::class_[with ClassType=AddTest, >BaseSpecifier=internal::NoBaseClass]" matches the argument list

An example for using Embind is given here: http://ift.tt/1JYHsrD

I am just not able to spot the difference between the example and my code.

Can somebody help me?

how to dynamically enabled and disabled button when checkbox is checked and unchecked in semantic UI

how to dynamically enabled and disabled button when checkbox is checked and unchecked in semantic UI, ive spend so many times to do this small creepy codes

here is the html

<div class="ui fitted checkbox">
<input type="checkbox" > <label></label>
</div>
<div class="ui small positive disabled button" id="edit">
<i class="edit icon"></i> Edit
</div>

here is my javascript

<script>
    $(document).ready(function () {
                    if (
                    $('#cek').checkbox({
                        onChecked: function () {
                        }
                    })) {
                        $('#edit').removeClass('disabled');
                    } else {
                        $('#edit').addClass('disabled');       
                    }
                });
</script>

please help,thats make me crazy

how to copy upload input data to another upload input data in html page for firefox

i am trying to upload a file and the uploaded data is copied to anothed upload input button

<input type="file" id="myFile">
<input type="file" id="myFile1">
<script>
var control = document.getElementById("myFile");
control.addEventListener("change", function(event) {  var i = 0,        files = control.files;
    console.log("Filename: " + files[i].name);
    console.log("Type: " + files[i].type);
    console.log("Size: " + files[i].size + " bytes");
var control1 = document.getElementById("myFile1");
var i = 0;
control1.files = control.files;     
alert(document.getElementById("myFile1").files[0].name);

}, false);

</script>

the aboove scenario is working fine chrome and not working in firefox and ie

angularjs - not able to invalidate input (Object doesn't support property or method '$setValidity')

I try to do the following

if ($scope.RetypePassword != $scope.resource.Password) {
     $scope.resource.Password.$setValidity("missmatch", false);
} else {
     $scope.resource.Password.$setValidity("missmatch", false);
}

but fail with this error

TypeError: Object doesn't support property or method '$setValidity'

What can the reason be?

resource.Password is databound to an input like this

<input type="password" ng-model="resource.Password" name="Password" />

Cordova Mms Plugin Error : mms_config.xml missing uaProfUrl setting

I want to send the MMS to some "anyemail@gmail.com", I tried my device mms service (using device sms app) and it worked. So now I'am tring to do the same using myapp. So, I landed up to cordova-MMS-Plugin.

But it gave some error MmsConfig.loadMmsSettings mms_config.xml missing uaProfUrl setting. So I looked in res/xml there was no mms_config.xml. So I downloaded it from git repo here, and put it in res/xml folder. But still the same error.

Here is My Code, this code contains only javascript I used to call send() for sending MMS with some arguments.

sendSMS = function (phoneNo, data) {
  var that = this;
  window.module.exports.send(phoneNo,data,undefined,undefined,function () { 
    that.smsSent();
  },function (e) {
    that.failed(e); 
  });
}

Here is MMS-PLUGIN js File sms.js

var sms = {
   send: function(phone, message, imageFile, method, success, failure) {
    phone = sms.convertPhoneToArray(phone);

    cordova.exec(
        success,
        failure,
        'Sms',
        'send',
        [phone, message, imageFile, method]
    );
},

convertPhoneToArray: function(phone) {
    if(typeof phone === 'string' && phone.indexOf(',') !== -1) {
        phone = phone.split(',');
    }
    if(Object.prototype.toString.call(phone) !== '[object Array]') {
        phone = [phone];
    }
    return phone;
  }
};
sms.install = function () {
  window.module.exports = sms;
}
cordova.addConstructor(sms.install);

Any body have any idea what I'm missing here. One more thing it works when I send to a mobileNo instead of email.

Wait until gobalEval has finished

I need to execute a callback after the following has finished:

jQuery.globalEval(myUnknownContent);

However, myUnknownContent might have some Ajax calls in it. So far, I'm using a timeout of 100ms, but this is not an elegant and reliable solution.

Thank you for any help!

javascript tree - recursion

var arr= [{id: "1", state: "1", ndi: "1558.3045298", children: "null"},
          {id: "2", state: "1", ndi: "1684.0732025", children: "null"},
          {id: "3", state: "1", ndi: "1809.8418752", children: "null"},
          {id: "4", state: "2", ndi: "1915.1603572", children: "null"},
          {id: "5", state: "2", ndi: "2023.5463678", children: "null"}]

How to create a tree recursively with above data keeping state as the root element

Method is returning undefined

I have a piece of JS code in for loop:

window.gamesParse = {
    days: days,
    dates: dates,
    times: times,
    series: series,
    homes: homes,
    aways: aways,
    channels: channels
}

var image = $.get("assets/images/" + gamesParse.aways[i] + ".png");
if (image.status !== 404) {
    console.dir(image);
} else {
    console.dir(image);
}

Now, it returns the right Objects which have status property. But if I change image to image.status (or any other property or method), it returns undefined.

CSV parser not getting rows from file

Iam parsing a CSV and have the following line that gets the csv lines by splitting the whole file using a newline character.

csvLines = e.target.result.split("\n");

I generated a CSV from excel on a Mac and tried to read it, but iam getting everything in one line as if there is no newline character.

I opened the csv in my text editor and i can see everything is in a separate line.But in my code i just get one row with all the data.

Something wrong with API request inside a loop

I'm in big trouble,I can't understand why this thing does not work.I need to make an API request for each value of an array,and if I look in my console javascript,the request are served but I need latitude and longitude value inside the request.The problem is that outside the API request I have 4 values (2 lat and long for each element of the array),and inside the API request I find only the last two lat and long,why?It seems really no sense and I don't know where the problem may be.Here is the code

var luoghi = {"city":[
                    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" },
                    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" }
            ]}; 
var arr=[];
for(var i in luoghi.city){  
lat = luoghi.city[i].lat;
lng= luoghi.city[i].lng;

console.log("Before API request "+lat+" "+lng);//here i have the right 4 values

var wUnderAPI = "http://ift.tt/1eU3pXU"+API_WU+"/forecast/q/"+lat+","+lng+".json?callback=?";
$.getJSON( wUnderAPI, {format: "json"}).done(function( data ) {
    if(typeof data['forecast']['simpleforecast']['forecastday'] != 'undefined'){  // controllo esito richiesta json
            console.log(" Inside the request "+lat+" "+lng); //here just the bari lat & lng 
    }
});
}

The API_WU is my private API KEY,but since it is for a not commercial use,anyone can get one from the site.Hope my question was clear,because is a problem that it's hard even to explain :) thanks in advance.

Get url of the active tab in a chrome extension and display using $scope using angularjs

I am trying to get the current url of any active tab, so when a user clicks the icon then popup.html pops which is angular's home page. Then the angular controller is trying to get the url and then forwarding to html page using $scope.

manifest.json:

{
"browser_action": {
      "default_popup": "popup.html",
      "default_title": "__MSG_manifest_iconTitle__"
   },
   "background": {
      "page": "main.html"
   },

   "manifest_version": 2,
   "minimum_chrome_version": "18.0.0",
   "name": "description",
   "permissions": ["tabs", "\u003Call_urls>", "http://*/*", "https://*/*", "ftp://*/*" ],
   "update_url": "http://ift.tt/1cKeJ90",
   "version": "1.0.0"
}

popup.html:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <div ng-view></div>

  <script src="assets/js/angular.min.js"></script>
  <script src="assets/js/angular-route.min.js"></script>
  <script src="assets/js/app.js"></script>
  <script src="assets/js/controllers.js"></script>
</body>
</html>

app.js:

var myApp =  angular.module('myApp', [
    'ngRoute',
    'myAppControllers'
]);

myApp.config(['$routeProvider', function($routeProvider) {
  "use strict";

  $routeProvider
    .when('/home', {
      templateUrl: 'assets/partials/home.html',
      controller: 'HomeCtrl'
    })
    // Set defualt view of our app to home
    .otherwise({
      redirectTo: '/home'
    });
  }
]);

controllers.js:

//to get current url
function get_current_url() {
  chrome.tabs.query({ active: true }, function(tabs) {
    var tabUrl = tabs[0].url;
    return tabUrl;
  });
}

var myAppControllers = angular.module('myAppControllers', []);

// Home controller
myAppControllers.controller('HomeCtrl', [
    "$scope",
    function($scope) {
        "use strict";

     //$scope.url = "tablink";
     $scope.url = get_current_url();

   }
]);

and home.html:

URL : {{ url }}

So, please how to achieve this, as I am getting only blank value after URL in the popup.

How to make a word a link if the user has input # before it?

I am using this code:

<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>

I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.

This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php. Thanks

Get a random number focused on center

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be mainly within that range.. Is it possible with Javascript/jQuery?

Right now I'm just using the basic Math.random() * 100) + 1

How to compare two arrays to see how many same elements they have?

I have two arrays, one is answers, and second one is correctAnswers and i need to see how many elements in answers are the same as in array of correctAnswers and to get percent how many "answers" are "correct". How do i do that? The arrays are something like this:

 answers = ["Hrtkovci","Lepenica","Dec"]

 correctAnswers = ["Lepenica","Dec","Leskovac"]

And i dont know if it matters but everything is with angular.

How to filter   in textarea with regex?

btw: i know that using regex is not the best idea in the world...

For example i have such input variants:

<p>&nbsp; &nbsp; &nbsp;</p>

or

<p>&nbsp; &nbsp;</p>

or

<p>&nbsp;</p>

and i want to check my input like: all except <p> with &nbsp; in every amount of them (0, 1 or 50)...

i wrote such expression:

/[^<p>(\s*&nbsp;\s*)*<\/p>]/ig

and seems that it works, but!

for example i have such input:

<p>&nbsp; &nbsp;t&nbsp;</p>

or

<p>&nbsp; &nbsp;tttt&nbsp;tttt</p>

and it is thinking, that it is equal to my regex...

not a good idea...

what i do wrong in my regex? or maybe there are some better ways of solving this?

Passing undefined to Nashorn Javascript in Scala/Java

I need to evaluate this function in Javascript from Scala/Java

function hello(a, b) {
    return a+b;
}

I did this basic code:

val factory = new ScriptEngineManager(null)
val engine = factory.getEngineByName("JavaScript")

val body =
  """
    |function hello(a, b) {
    |    return a+b;
    |}
  """.stripMargin
engine match {
  case engine: Invocable =>
    engine.eval(body)
    println(engine.invokeFunction("hello", null, 1: java.lang.Double))
}

For the parameter a I'm passing a null and I get a 1.0 as a result. If I hack my javascript (I DON'T WONT TO DO THIS) and I make it:

function hello(a, b) {
    if (a === null) {
        a = undefined;
    }
    return a+b;
}

I get the expected NaN.

The correct solution would be passing an undefined to the invokeFunction: How do I do this?

I have been trying to give a site tour using introJs()

my first element is a fixed div. when i scroll, highlight box is not coming down and is somewhere else

Need is that highlight box should always be with the fixed div . I m nt able to figure out how to use onchange or onbeforechange because that is the first step in my tour. I tried to set scrollToElement True but still i m not getting the desired effect. Somebody please tell me how to make the highlight box always point the fixed div which always stays on the left.

THis is the code snippet:

<script type="text/javascript">
    $(document).ready(function () {
        if (mq.matches) {
            var intro = introJs();
            intro.setOptions({
                steps: [
                  {
                      element: '#sidebar',
                      intro: "Hi {{ username }}! Check and edit your shop settings from here.",
                      position: 'right',
                      highlightClass: 'posFix'
                  },
                  {
                      element: '#card_orders',
                      intro: "Checkout your daily orders and revenue",
                      position: 'left'
                  },
                  {
                      element: '#card_visitors',
                      intro: "Check your daily traffic of your shop.",
                      position: 'left'
                  },
                  {
                      element: '#card_customers',
                      intro: "Know your customers and follow them",
                      position: 'left'
                  },
                  {
                      element: '#card_marketing',
                      intro: "Run campaigns, send mass sms and emails to your customers",
                      position: 'left'
                  },
                  {
                      element: '#apps_cards_wrap',
                      intro: "Find and add more and more friendly apps to your store",
                      position: 'left'
                  },
                  {
                      element: '#card_inventory',
                      intro: "Manage your Inventory from here.",
                      position: 'left'
                  },
                  {
                      element: '#card_store_customise',
                      intro: "Customise your store from here.",
                      position: 'left'
                  },
                  {
                      element: '#card_accounts_settings',
                      intro: "Change your Account settings from here.",
                      position: 'left'
                  },
                  {
                      element: '#sidebar_toggle',
                      intro: "Click to hide the sidebar menu",
                      position: 'left'
                  },
                  {
                      element: '#store_logo',
                      intro: "Click here to view this tour anytime",
                      position: 'right'
                  }
                ]
            });
            intro.setOptions("scrollToElement", true).start();
        }
        {# Removing first_login cookie hack. #}
        createCookie('first_login', '', 7);
    });
</script>

please see this link to understand the issue

How to hide a table row which have TD containing certain values

I am working on a SharePoint web site , and I need using CSS (Preferred) or JavaScript, to hide a table row that have two main TDs:-

  1. TD with a text named Item Number.
  2. TD with an input titled Item number.

Here is how the mark-up is constructed:-

enter image description here

Can anyone advice on this please?

i tried the following script , but did not hide the Item Number or the customer initial , baring in mind that all the TR are inside a table which have .ms-formtable class:-

    <script>
$(function() {

  $('.ms-formtable tr').each(function() {
    var frstVal = $(this).find('td').eq(0).text();
    if (frstVal.match(/Item Number|customer Initials/i)) {
      $(frstVal).remove()
    }
  });

});

    </script>

here is the related markup :-

<table width="100%" class="ms-formtable" style="margin-top: 8px;" border="0" cellspacing="0" cellpadding="0">
<tbody>

<td width="113" class="ms-formlabel" nowrap="true" valign="top">
<h3 class="ms-standardheader">

<nobr>Item Number</nobr>

</h3></td>


<td width="350" class="ms-formbody" valign="top">

<span dir="none"><input title="Item Number" class="ms-long ms-spellcheck-true" id="_x0049_D1_806a702b-1716-47f5-a93c-16067f502daf_$TextField" type="text" maxlength="255" value=""><br></span>

<span class="ms-metadata">Do not customize at the list level</span>


</td>

How can I correctly close this JQuery dialog?

I am absolutly new in JavaScript and JQuery and I have the following problem.

Into a page I have this dialog:

<div id="dialogReject" title="">
    <table style="visibility: hidden;" id="rifiutaTable" border="0" class="standard-table-cls" style="width: 100%!important">
        <tbody style="background-color: #ffffff;">
            <tr>
                <td style="font: 16px Verdana,Geneva,Arial,Helvetica,sans-serif !important">Inserire note di rifiuto</td>
            </tr>
            <tr>
                <td>
                    <textarea style="visibility: hidden;" rows="5" cols="70" id="myRejectNote"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input class="bottone" readonly="readonly" type="text" value="Rifiuta" onclick="rifiuta()"/>
                </td>
            </tr>
        </tbody>
    </table>
</div>

that I think is created by this JQuery script:

$(document).ready(function() {
    larghezza = '950px';
    lunghezza = '470px';
    lunghezza2 = '530px';
    $("#dialogReject").dialog({
         autoOpen: false,
         //width:'335px',
         width:'600px',
         modal: true,
         show: {        
             effect: "blind",
             duration: 500      
         },
         hide: { 
             effect: "blind",   
             duration: 500    
         }
     });
});

As you can see this dialog contains 2 buttons implemented by 2 input tag, these:

<td style="text-align: right">
    <input class="bottone" readonly="readonly" type="text" value="Annulla" onclick="javascript:window.close()"/>

    <input class="bottone" readonly="readonly" type="text" value="Rifiuta" onclick="rifiuta()"/>
</td>

When the user click on the Annulla button I want that the dialog is closed.

Actually I tryied to use the window.close() function but it can't work.

I think that to cloe this dialog I have to use the same event that is performed when the user use the ESC keyboard button that close the dialog with a simple animation.

But I really have no idea about how do it. Can you help me to do it?

Tnx

mercredi 6 mai 2015

changing AVPlayer orientation

I need change my AVPlayer orientation when device orientation is changed. I set _playerLayer.frame = perentView.bounds but it doesn't helped _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_videoPlayer]; _playerLayer.frame = perentView.bounds; _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [perentView.layer insertSublayer:_playerLayer atIndex:0];

How to implement 2 SearchBar and Search Display controller in iOS app?

According to my need I have to use 2 SearchBar and Search Display controller (Same as in google navigation 1. Source 2. Destination), So when I am using these 2 UISearchBar iOS is giving a single Display controller i.e self.searchDisplayController.

in the following method I have to make a web api call and before getting response from web server it is updating table showing no results :

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

Hence in - (void)connection:(NSURLConnection *)connection didReceiveData:
I am doing [self.searchDisplayController.searchResultsTableView reloadData];

For the 1st search bar it is working fine but for the 2nd SearchBar its only calling -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section and not calling - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath and hence 2nd seachbar's table is not updating.

Please help me in solving this and one more thing I observed that whichever Search and Display controller I draged first is working fine and 2nd one always giving this problem.

Replace only single occurrence of \n or \r in NSSTring

I am reading text from a PDF to NSString. I replace all the spaces using the code below

NSString *pdfString = convertPDF(path);
    pdfString=[pdfString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pdfString=[pdfString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    pdfString=[pdfString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

But this also eliminates paragraph spaces and multiple lines. I want to replace only a single occurrence of \n or \r and retain the paragraph spaces or multiple tabs and next lines.

Error saying the viewController does not exist.iOS Xcode

In my app, It is showing some error like :

 "unknown type name 'purchasedViewController'; DId you mean 'UIPageViewController'?

But actually there is a VC named purchasedViewController and i have imported it in the current VC.

But when i create an object of purchasedViewController in the current VC like:

@property(strong, nonatomic) purchasedViewController *purchasedController;

im getting an error message saying :

"unknown type name 'purchasedViewController'; DId you mean 'UIPageViewController'?

Why is it happening?Any idea?

How to store Whole index path, previous,before previous and current selected index path value to the NSArray within didSelectRowAtIndexPath: methods

Problem :

I developing Quiz apps.In apps there are likes 5 questions in one tableview Questions get from plist.whenever,i have selecting the questions choice in tableview it showing,current selected index_path value.

But i wants whole questions choices likes from 1 to 5 selected index_path in the array.

My Code :

  • (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // what is that code,....?

}

i wants :

NSLog(@"whole index_path : %@",array name);

output:

whole index_path : 0 1 0 2 1

Can Any One help me??? :-) Thanks Advance

Apple watch scene Background scrolls

I am developing an app for Apple's new iWatch.

As its iWatch appilcation we must use storyboard with limited controls.

Our graphics team is asking to set Background in all the scenes in the storyboard.

We have successfully set Background property of scene but problem is when screen scrolls the background image also scrolls.

So my problem is simple i just want groups on my scene to scroll not the Background i set to scene.

I have tried many solution like used groups and image but still no luck.

Thanks is advance.

How do I write to data in the TableView from a custom UITableViewCell

I have a TableView that populates “Characteristic” data from HomeKit. The TableView uses a custom UITableViewCell. The cell has a label and a switch. The cell @IBOutlet and @IBAction work properly allowing me to view the label and toggle/animate the switch in all cells. However, I need the switch to write to the Data Source in the TableView and I do not know how to reference/access the data from the TableView in the custom cell. I have determined how to get the indexPath of the selected cell.

I know there is a simple answer here ….. please help this iOS/XCode/Swift beginner.

import UIKit import HomeKit

class CellServicesCharacteristics: UITableViewCell {

@IBOutlet weak var label2: UILabel!
@IBOutlet weak var switch1: UISwitch!

@IBAction func switch1Act(sender: UISwitch) {

    var cell = sender.superview?.superview as! CellServicesCharacteristics
    var tableView = cell.superview?.superview as! UITableView
    let indexPath = tableView.indexPathForCell(cell) as NSIndexPath!

    // How do I reference the Data Source from the TableView
    // so I can write to the Data Source?

    if switch1.on {
        label2.text = "On"
        // write to data source in tableview
    } else {
        label2.text = "Off"
        // write to data source in tableview
    }

}

override func awakeFromNib() {
super.awakeFromNib()

//Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}

Custom UITableViewCell width issue

I have a custom UITableViewCell with and .xib. In the xib I have set the cell width to 320.

I want to position a UIlabel inside the cell relative to the cell width. However, in the code during runtime the Bounds.width of the cell is always 320, as set in the xib, and not the actual width of the screen/UITableView which I need to position the UILabel correctly.

The width should be different for iphone 5, 6 and 6+ obviously, at least during runtime, but it's always set to 320 on all devices. What am I missing?

Thanks!

EDIT

Here is a tiny bit of code.

var newFrame = _lblDetail.Frame;
newFrame.X = Bounds.Width - 55; //get current width of cell, and subtract 55 and set that as the X value of the frame for the label
_lblDetail.Frame = newFrame; //set new frame on label

Table has no (public) columns only on real device

I have the simplest of apps that I thought I would try on my device before I got too engrossed. However, I am getting the strangest error message when I run it on my iPhone (as apposed to the the emulator on my macbook).

Table has no (public) columns .

I am using the SQLite.Net PCL and I have built it from git hub as I had some problems with it not having the platform dlls for IOS otherwise.

Relevant code.

In my models I have this:

public class Setting
{
    [PrimaryKey, AutoIncrement]
    public long Id { get; set; }

    [Indexed]
    public string Key { get; set; }

    public string Value { get; set; }

}

The code that throws this error message is the simple:

using (SQLiteConnection db = GetCon ()) {

            db.CreateTable<Setting> ();
}

but in my opinion the strangest thing is that this code works fine on the emulator but crashes the application on the iphone itself.

If anyone has some ideas that would be great.

EDIT: This error is thrown on the SQLite.Net-PCL library on this file line 380 but only on the device and not on the emulator.

iOS Facebook SDK v4.0 not showing Title and Description while sharing a Post containing (Image ,Title ,Desc)

FBSDKShareOpenGraphObject *object = [[FBSDKShareOpenGraphObject alloc]init];
[object setString:@"digital:milestone" forKey:@"og:type"];
[object setString:@"Title" forKey:@"og:title"];
[object setString:@"Description" forKey:@"og:description"];



if (self.photo) {
    [object setPhoto:self.photo forKey:@"og:image"];
}

FBSDKShareOpenGraphAction *action = [[FBSDKShareOpenGraphAction alloc] init];
action.actionType = @"digital:celebrate";

[action setObject:object forKey:@"digital:milestone"];

FBSDKShareOpenGraphContent *content = [[FBSDKShareOpenGraphContent alloc] init];
content.action = action;
content.previewPropertyName = @"digital:milestone";

FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init];
shareDialog.delegate=self;
shareDialog.fromViewController = self;
shareDialog.shareContent = content;
[shareDialog show];

While using the above piece of code ,It take you to the Facebook app and shows the Share utility which shows only the Image.(The Title and Desc is not seen ),

Although when i press the post button ,the post is properly shared with image,title,desc.The issue is while sharing user is having no clue what he/she is sharingenter image description here

Cocos2dx, porting 32bit to 64bit

I have an old source code that I want to publish. Apparently the code is using 32 bit, and now I want to port it to 64 bit. I get this following errors:

ld: warning: directory not found for option '-L/Users/hammyliem/Dropbox/projects-cocos2dx/ZombieSmasher/projects/ZombieSmasher/http://ift.tt/1Ega6NN'
ld: warning: ld: warning: ld: warning: ld: warning: ld: warning: ignoring file /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libchipmunk iOS.a, file was built for archive which is not the architecture being linked (arm64): /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libchipmunk iOS.aignoring file /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libCocosDenshion iOS.a, file was built for archive which is not the architecture being linked (arm64): /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libCocosDenshion iOS.aignoring file /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libbox2d iOS.a, file was built for archive which is not the architecture being linked (arm64): /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libbox2d iOS.aignoring file /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libcocos2dx-extensions iOS.a, file was built for archive which is not the architecture being linked (arm64): /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libcocos2dx-extensions iOS.aignoring file /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libcocos2dx iOS.a, file was built for archive which is not the architecture being linked (arm64): /Users/hammyliem/Library/Developer/Xcode/DerivedData/ZombieSmasher-blkanqhhfgudylfmtnqaeimarsin/Build/Intermediates/ArchiveIntermediates/ZombieSmasher/BuildProductsPath/Release-iphoneos/libcocos2dx iOS.a




Undefined symbols for architecture arm64:
  "cocos2d::Array::createWithCapacity(unsigned int)", referenced from:
      ChooseLevelScene::init() in ChooseLevelScene.o
  "cocos2d::Director::popScene()", referenced from:
      MoreBrain::keyBackClicked()::$_7::operator()() const in MoreBrain.o
  "tinyxml2::XMLAttribute::QueryIntValue(int*) const", referenced from:
      tinyxml2::XMLElement::QueryIntAttribute(char const*, int*) const in XMLAnimation.o
  "tinyxml2::XMLAttribute::QueryFloatValue(float*) const", referenced from:
      tinyxml2::XMLElement::QueryFloatAttribute(char const*, float*) const in XMLAnimation.o
  "cocos2d::Array::containsObject(cocos2d::Object*) const", referenced from:
      XMLAnimation::Layer::Update(float) in XMLAnimation.o
      XMLAnimation::Layer::Restart() in XMLAnimation.o

PLEASE HELP... stuck here for long time... my biggest guess is to change libbox2d iOS.a, and similar files like that, but I also do not know to change them. Thanks.

Determine tilt and orientation in app

I am supposed to build iPhone and android app. The part of application should determine a tilt and orientation of the phone itself.

What stack of technologies should I use in order to build best experience. Is it possible to go with something similar to Ionic with Angular?

Sync iPhone AddressBook with a Backend Server

There are lots of applications doing AddressBook synchronization with their Backend servers to cross check which contacts in your AddressBook are using their application and which users needs to be invited to their application.

For the first time it may do a full sync, but after that it shouldn't be a full sync.

My first question is, What is the best way to sync the full AddressBook with a Backend Server?

Second question is, How to sync ONLY the contacts which has modified recently?

If there's any sample application or a tutorial please share with me.

Thanks in advance.

Activate Apple Pay in Passbook

I have added a pass to passbook, which includes payment information.

Is it possible to pay from inside the passbook using Apple pay without creating an external payment application?

I mean, is it possible to display the Apple pay button programmatically inside the passbook/pass for payments?

What I have done:

  • The server generates the passbook file and send the link to the iPhone
  • The user clicks the link, automatically opens the passbook application and prompt user to add the pass to passbook application
  • After adding the pass to passbook, users can see the payment link in pass
  • Clicking on this link shall launch a payment application to show the payment details with an apple pay button to pay the bill.

My goal is to avoid these steps and get rid of payment application to pay the bill.

Any help on this is appreciated.

What are the basic steps to get XMPP for chat for ios

I want to make chat application for iOS but I don't know where to buy XMPP for chat. And also how to setup it in server. Please help.

How can I set boundaries for the iOS camera?

I am trying to get a region of the iOS camera demarcated for a picture (as in the image below). I want only the marked area to appear in the picture.

  1. How can I take a picture only of the marked area?

  2. How can I mark the region when I open the camera (within my app)?

enter image description here

Reactivecocoa send new value

I'm new to reactivecocoa and I need help. I was searching and I couldn't figure it out. Let assume that I have UIPickerView. In that pickerView there are 4 options, for each language one for example german, english, spanish, french. On selected language I need to send back abbreviation english - en, french - fr... I'm using MVVM architecture and this is my method in my ViewController. In that method I bind ViewModel and selected properties.

- (void)bindeViewModel
{
  RAC(self, selectedLanguageAbbreviation) = self.languageViewModel.observeSelectedLanguage;
}

"observeSelectedLanguage" is my signal and its implementation is:

-(RACSignal *) observeSelectedLanguage
{
    @weakify(self);
    return [RACObserve(self, selectedLanguage) filter:^BOOL(NSString *value){
    @strongify(self);

    if (value == LocalizedString(myValueString(English)))
    {
        self.selectedLanguageAbbreviation = @"en";
        return self.selectedLanguageAbbreviation;
    }
    else if (value == LocalizedString(myValueString(German)))
    {
        self.selectedLanguageAbbreviation = @"ge";
        return self.selectedLanguageAbbreviation;
    }
    else if (value == LocalizedString(myValueString(French)))
    {
        self.selectedLanguageAbbreviation = @"fr";
        return self.selectedLanguageAbbreviation;

    }
    else if (value == LocalizedString(myValueString(Spanish)))
    {
        self.selectedLanguageAbbreviation = @"sp";
        return self.selectedLanguageAbbreviation;
    }
    else
    {
        self.selectedLanguageAbbreviation = @"en";
        return self.selectedLanguageAbbreviation;
    }
 }];
}

"myValueString" is macro for returning string from enum, so English, French etc are part of enum. Can you help me and explain how to send abbreviation for selected language? Thank you

Don't see App Extension option in Xcode?

I'm working on creating app which has Todays Widget. When i go to Xcode and start new project i don't see the option of "Application Extension" Please check the below screenshots.

Xcode screen shot of new project

Im using Xcode version 6.3 enter image description here

Please help me how to enable Application Extension option

For tutorial I'm referring to the following link

Save and segue UIImageView after moving with UIPanGestureRecognizer. Swift

Good day. This is my last option — to ask here. The problem is: I am building multiply view app. On the first screen I have UIImageView that I can move with UIPanGestureRecognizer function:

@IBAction func movement(recognizer: UIPanGestureRecognizer) {

    let translation = recognizer.translationInView(self.view)

    if let view = recognizer.view {

        view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y)

    }


    recognizer.setTranslation(CGPointZero, inView: self.view)

}

It's a usual code to move things around, I took at raywenderlich.com

So what I want is to save position of the UIImageView element after interaction with it and after segue.

I believe that I need to return CGPoint from this function and segue it like so:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showPlaylistDetail" {
            let playlistDetailController = segue.destinationViewController as! PlaylistDetailViewController

playlistDetailController.image2.center = image1.center

        }
    }

So my question(s) is(are):

  1. Do I use right code to move an object with Pan Gesture Recognizer?

  2. How would you return CGPoint from this function and how would you read it?

  3. How would I save UIImageView's position in process of segue and after?

huh... This little bug is killing me. I bet, it is easy to solve, but as far as I am beginner I have no idea how :(

Passe data beetwen view controller in UITableView

I try to pass an PFObject with the current ViewController to another ViewController when the user select a cell from the UITableView, this is my code :

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"boxCell";
NSInteger row = [indexPath row];
boxTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil){
    cell = [[boxTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}

PFObject *boxe = [PFObject objectWithClassName:@"Boxe"];
boxe = [self.arrayBox objectAtIndex:row];


PFQuery *query = [PFQuery queryWithClassName:@"Boxe"];
[query whereKey:@"objectId" equalTo:boxe.objectId];

[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    if(object){
        // I instanciate the PFObject
        box = object;
        cell.nomBoxe.text = object[@"contenu"];
        cell.qteBoxe.text = [NSString stringWithFormat:@"%@ boxes disponbiles",object[@"quantite"]];
        cell.prixBoxe.text = [NSString stringWithFormat:@"%@€",object[@"prix"]];
        cell.descriptionBoxe.text = object[@"description"];
    } else {
        NSLog(@"Erreur lors de chargement, erreur : %@",error.description);
    }
}];
return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:@"segueToBoxDetail" sender:self];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:@"segueToBoxDetail"]) {
    boxDetailViewController *boxDetailVC = [segue destinationViewController];
    boxDetailVC.box = box;
    }
}

I declare the PFObject :

@implementation RestauCardViewController{
PFObject *box;
}

In the other ViewController, I have a property for the object box :

@property(nonatomic) PFObject *box;

I got this error :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setBox:]: unrecognized selector sent to instance 0x12aad9100'

Any help please

Battery and wifi indicators on normal view

I am using a simple view in application instead of navigation bar. Is their any way to show wifi, battery indicator on the view without using default navigation bar?

Can not update my pod library

I have published my component HDTableDataSource on Cocoapods. I have now updated the version of the code by adding some code.

While trying to compile it using command "pod spec lint", it gives me following error.

[!] /usr/local/bin/git clone http://ift.tt/1IfW1Y5 /private/var/folders/fm/vxq9zgy52zq28lvcq0qwzpj80000gn/T/CocoaPods/Lint/Pods/HDTableDataSource --single-branch --depth 1 --branch 0.1.0

Cloning into '/private/var/folders/fm/vxq9zgy52zq28lvcq0qwzpj80000gn/T/CocoaPods/Lint/Pods/HDTableDataSource'...

fatal: unable to access 'http://ift.tt/1KLt7Nv': The requested URL returned error: 400

Kindly help me to update my library.

How to generate xcode project through terminal?

I am trying generate xcode project through terminal. I have a idea of making a command line utility similar to the rails setup application. When we create xcode project and the hierarchy that is generated automatically. I want the same hierarchy to be created through command line. I find some way like cmake command. This command is used for creating xcode project but when i fired that command on my terminal, it won't work.

iOS backend server for background jobs to do calculations on the data from users?

I am using Parse already for some other apps. And I have an app in mind where i would need to get data from users and periodically run a background job (scheduled) on a backend server to do some manipulations to this data. in general some simple calculations.

I was looking through Parse's documentation and it does feel a bit complicated to what I actually need. Though maybe I did' dig enough in the "cloud code" and jobs.

In my mind - if I had a server with Oracle\MySql where users send the data from the app - I can have a python script for example running every 5 minutes to do all the calculations needed...

Does anyone have an example of which platform to use for such tasks?

Uber Authentication failed "HTTP Status 401: Unauthorized, Response: {"error": "invalid_client"}"

i am using this library for Uber Authetication

http://ift.tt/1zakXLA

I have done like this

func doOAuthUber(){

let oauthswift = OAuth2Swift(
    consumerKey:    "fXfXXXXXXXUo9vtKzobXXXXXUDO",
    consumerSecret: "e5XXXXXXXq2w63qz9szEx7uXXXXXXo03W",
    authorizeUrl:   "http://ift.tt/1HP3zzA",
    accessTokenUrl: "http://ift.tt/1q8M4Bk",
    responseType:   "code"
)

var originalString = "jamesappv2://oauth/callback"
var encodedCallBackUrl = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

println("encodedCallBackUrl: \(encodedCallBackUrl)")


let state: String = ""
oauthswift.authorizeWithCallbackURL( NSURL(string: encodedCallBackUrl!)!, scope: "request%20history", state: state, success: {
    credential, response in

    println(credential.oauth_token)
    self.personalDriverLoader.stopAnimating()



    }, failure: {(error:NSError!) -> Void in

        self.personalDriverLoader.stopAnimating()
        println(error.localizedDescription)
})

}

but getting this response HTTP Status 401: Unauthorized, Response: {"error": "invalid_client"}

I have triple checked that my client_id (consumerKey) and secret (consumerSecret) are correct. What I have done wrong here

Please help

IOS & objective C development - how to make the login page appear to the user?

I am in my first days of IOS app development, I am trying to build an authentication system for an already existent iOS App using Objective C.

The app's rootviewcontroller is a tabsview followed by navigationControllers.

What i've done so far:

1- creating the loginviewController class & designing it's UI in the storyboard

2- the same thing for the "registration" & "recover my password" classes

3- linking the root viewcontroller with the login page with a segue of type modal.

4- linking the login page with the registration & recover my password pages with segues of type push.

Now i don't know the steps that i should follow to make the login page appear to the user when he first enters the app & eventually store his state so he can access the app later without having to enter his credentials every time (unless he logs out).

Any help is greatly appreciated, thank you

I am available for any clarifications or eventually some screenshots/source code if needed.

How to lock keyboard to Simplified Chinese Handwriting?

I want to lock my keyboard to just simplified chinese handwriting. How do I do this?

The problem is that I am trying to create a Chinese quiz app in Xcode 6 using swift and I want the quiz-takers to write in the character to match the English word using a chinese handwriting keyboard. I do not know how to program this and other questions asked like this do not seem to yield a useful result for me.

Help would be much appreciated.

iOS 8 Suggested App icon lock screen

iOS Suggested App feature will show app icon on left bottom corner in iPhone lock screen, if i click on that icon which delegate method will be called in the code ?

How do i connect UITabBar items to view controllers in IB

I want to connect UITab bar items to different view controllers. I dont want to use UITabBarController.I have a UITabBar in a ViewController. I am aware of the delegate methods also. Just wanted to know if there is a way to do this through the interface builder(Ctrl+Drag way).Ctrl+Drag only works for elements in UITabBarController and not for UITabbar.

PS: Same question has been asked before but re-posting because there is no satisfactory answer for this. How do I connect UITabBar items from a UITabBar (not a UITabBarController) to different views in the IB?

AppIcon not Set

I want to set my appIcon.I am drag an image in app-icon. They show on target everywhere on app. but not set on appicon. Ans my appicon source is appicon.

![enter code here][1]

enter image description here this is my app icon image![][1]

How to resize UITableView width to fit its content?

Is there possible way to adjust table view width by width of biggest text that should be set in the cellTitle label?

iOS 8 , SWIFT

sharing an image with WhatsApp without using documentationInteractionController

i am using UIActivityViewController to share images,videos and links all across the app. In it i have a subclass activity for WhatsApp. while i'm sharing urls everything's fine . i use url scheme for that.

i am having some problems with sharing an image using WhatsApp.

Custom Transistion animation shows viewController with a blink

I am working with a custom transition, animation like that of a push. But when i use this code after my viewcontroller loaded after after animation it just blinks.

Here is the method i used to present my view controller

+(void)leftpresentFrom:(UIViewController *)fromviewcontroller
                To:(UIViewController *)toviewcontroller
{

CGPoint newcenter       = CGPointMake(480, toviewcontroller.view.center.y);


toviewcontroller.view.center           =newcenter;


toviewcontroller.view.clipsToBounds=YES;


[fromviewcontroller.view addSubview:toviewcontroller.view];


[UIView animateWithDuration:.5
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     toviewcontroller.view.center = CGPointMake(160 ,toviewcontroller.view.center.y);
                 }
                 completion:^(BOOL finished){
                     [toviewcontroller.view removeFromSuperview];
                     [fromviewcontroller presentViewController:toviewcontroller animated:NO completion:^{

                     }];

                 }];
}

How to reserve an app name with the new iTunes Connect UI?

There was before a solution to reserve an app name on iTunes Connect using its "waiting for upload" and "prepare for upload" status. However since the last year change in iTunes Connect, I was wondering if it is still possible to do so, considering that I have not finished my app yet (I think it will be available in September)

Currently my app is in the "Prepare for submission" state, is it enough to reserve the name I used or do I have to process forward and upload a binary?

I want to remove gesture when i click on object of a classsssss

From my side I will try bellow code ,but it is not working . Please help me - (void) handleTouch:(UITapGestureRecognizer *) gesture { CGPoint touchPoint = [gesture locationInView:self.view];

   NSArray *viewsAtPoint = [self viewsAtPoint:touchPoint];

   for(TheifView * aView in viewsAtPoint)
   {
     [aView removeFromSuperview];
   }
}

Need help in publish my iOS app to the app store

Could somebody tell me how can I publish my app to the app store? I have an account on developers.apple.com, but its my first app and I don't know how to do this... The app was developed in Apache Cordova, but it makes an *.app file, how can I make an *.ipa file? So I need to make *.ipa and publish it, but I don't know how to do this...

how to integate paypal payment gateway in ios?

I am developing one application for iOS. In that user can Order/Purchase restaurants Menu Item. I don't have any idea about payment gateways. So, please how to integrate PayPal payment gateway method and how to implement that in my iOS app.Please Suggest any tutorial or links. ( I am from Gujarat,India), i heard payment gateway methods depends upon the country.

mardi 5 mai 2015

connectivity between IOS and Android over Bluetooth for somemtime

I've been researching on connectivity between IOS and Android over Bluetooth fro sometime. Does anybody have any latest update on this. I know most of the previous threads point that this is not possible due to shortcomings on the Android side, but do we know if there are any updates since then that can help resolve this.

Any help is greatly appreciated.

Show contact (data) in mail (iPhone for example) (example attached)

how can i attach the contact data to an mail like in the screenshot below?

And is it possible to do that automatically via Outlook/Exchange?

Thanks in Advance!

Example what i mean

All devices targets on xcode become "unavailble"

I have tried to install xcode 4.6 together with my existing xcode 6.3. I have face issues during installation. one of the solutions was to run this command:

/Developer/Library/uninstall-devtools --mode=all

after that i could not run under devices , for all devices that i have it gives me this error : enter image description here

did any one face this before ?

UPDATE :

itunes also can not see my devices. I have reinstalled xcode but no changes.

ios objective c, iphone app works fine in iphone(all model), but crashes only in ipad device and ipad simulator

2015-05-06 11:36:18.414 Myproject[165:60b] *** -[UIViewAnimationState release]: message sent to deallocated instance 0x196b0820

And

EXC_BREAKPOINT(code=EXC_ARM_BREAKPOINT,subcode=Oxdefe)

This crash does not come in iphone(works fine in all iphone model), comes only in ipad, Please help me. Thank you.

How to merge two images in iOS and Save into Photo Library?

In my iOS app I have one image named "back.png"

Now, I want to pick any one image from photo library

Now, I want to crop (Only Head) picked image from Photos and merge on "back.png" (on blank area) and then save merged image in one .png image.

fileExistsAtPath gets filename with just a path?

I'm working with Dropbox API and I'm loading images into the app's Documents directory using the API delegate method loadFile:intoPath:. Dropbox's completion callback method, restClient:loadedFile:, fires ok with (NSString*) destPath as the second param. Each destPath that is returned for each file is the same, something like:

/Users/<myID>/Library/Developer/CoreSimulator/Devices/<Device #>/data/Containers/Data/Application/<App #>/Documents

But when I call this:

UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(xPos, 0, 500, 500)];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
imageView.image =  [UIImage destPath];
[self.view addSubview:imageView];

... I get four distinct images! How is this happening? How is Dropbox able to get the distinct images with the same exact path?

IOS distribution certificate is grayout

My app is completed and now i want to distribute in apple app store but ios distribution option is grayout , if i delete a previous distribution certificate then is there any problem in my app which is on appstore

Does Cocos2d-x 3.5 support ARC for iOS development

I wonder if the lastest Cocos2d-x 3.5 support ARC in iOS development?

If not, how can i convert the project to support ARC?

Thanks.

iPhone 5 and 5S Media Query cascading to Samsung Galaxy S4

I have the following media query for iPhone 5 and 5S:

@media only screen and (min-device-width: 320px) and (max-device-width: 568px) and (-webkit-min-device-pixel-ratio: 2)

A style in this media query is "cascading" or "leaking" on a Samsung Galaxy S4.

I am not using an actual Samsung Galaxy S4 for testing, instead, I am using Chrome F12 tools Device Mode. Device Mode "spoofs" the user agent string and view port for testing different devices.

So perhaps Chrome F12 tools Device Mode has not properly "spoofed" the user agent string and view port so that I can truly test my media queries.

I would think that the -webkit-min-device-pixel-ratio: 2 "condition" of my iPhone 5 & 5S media query would eliminate the chance that the iPhone 5 and 5s media query CSS would "leak" to a Samsung Galaxy S4, native or spoofed user agent screen and view port.

How do you use MBProgressHUD CustomView/Determinate Loader in Swift?

I am trying to run MBProgressHUD in Swift. I have found I am able to run a spinner that is very similar UIAlert spinner, but that I am having trouble with the other functions. According the MBProgress docs, you can also user a determinate loader as well as other functions including a CustomView which could be loaded as a success. I am trying to figure out how to load and access these other functions in Swift.

This is the current code for the indeterminate spinner (the only function I can get working):

let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "Loading"

To dismiss the ProgressHUD:

MBProgressHUD.hideAllHUDsForView(self.view, animated: true)

Please excuse such a simple question. I am brand new to programming. Thank you so much for all of your help!

UIPageControl problems, Objective-C

I have been working on implementing UIPageViewController for some time now. I have went through many problems that i managed to solve by myself and with some extra help. Now i am stuck with the last part and that is the UIPageControl.

I got two problems that i would like some help with:

Problem 1: Is there any simple way to resize the dots for the pageControl?

Problem 2: This is how it is built:

enter image description here

I know it is hard to see but i will explain them starting from the upper left corner and going to right. First VC is simply a Navigation Controller pointing to a UITableViewController.

in the second row the first VC is the datasource delegate for the UIPageVIewController. The one next to it is the PageViewController, The two UITableView's next to it is the "pages" that are in the UIPageViewController. And the last one is the PageContentViewController.

So i added this code in viewDidLoad to the datasource VC meaning the first VC in the second row:

self.navigationController.delegate = self;
CGSize navBarSize = self.navigationController.navigationBar.bounds.size;
CGPoint origin = CGPointMake( navBarSize.width/2, navBarSize.height/2 );
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(origin.x, origin.y+16,
                                                                   0, 0)]; //Here added 45 to Y and it did the trick



self.pageControl.pageIndicatorTintColor = navbarColor;
self.pageControl.currentPageIndicatorTintColor = [UIColor lightGrayColor];

[self.pageControl setNumberOfPages:2];

and

- (void)navigationController:(UINavigationController *)navigationController     willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    int index = [self.navigationController.viewControllers indexOfObject:viewController];
    self.pageControl.currentPage = index;  }

Which gives me this result:

enter image description here

Which is perfect, I can swipe right and left and the PageControl shows the right indicator etc. However when i leave the "UIPageViewController" meaning when i click back. The PageController still appears in the first VC in the first picture. Why does it tag along and not get removed and how can i solve this?

If you need extra codes / pictures that would make it easier to understand just tell me. Thank you!

Content of the UIViewController doesn't show up even though the UINavigation bar is there

So I'm trying to switch from one UIViewController to another using the navigation controller. I know for sure that the new controller goes successfully through the custom init method and creates two UIBarButtons. However, the content of the screen (4 labels, 3 textfields, 1 UIImageView) doesn't show up. Instead, I just see a grey screen.

Passing the NSLog message through the ViewDidLoad,ViewWillLoad and ViewWillAppear showed that all these were successfully executed.

Here is the gitHub repo if you want to take a look: http://ift.tt/1cjGCZv

Here is the code that I use to pass a new controller:

// Create a new student and add it to the store
  Student* newStudent = [[StudentStore sharedStore] createStudent];

StudentDetailViewController *detailViewController = [[StudentDetailViewController alloc] initForNewStudent:YES];

detailViewController.student = newStudent;

detailViewController.dismissBlock = ^{
    [self.tableView reloadData];
};

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

navController.modalPresentationStyle = UIModalPresentationFormSheet;

[self presentViewController:navController animated:YES completion:NULL];