lundi 31 août 2015

Losing material when prefab is created

I have a game object with these properties:

So when I create the prefab, right after the creation, on the prefab the material is lost. The mesh renderer doesn't contain any material.

What is the problem? The other properties are set as default.



via Chebli Mohamed

Order by long Distance from Google Distance Matrix

Google Distance Matrix API for long distance between the origin and destination respond with a blank space when it's > 1000km: "1 865"

When I try to order the result using LINQ:

.OrderBy(g => Double.Parse(g.Distance, CultureInfo.GetCultureInfo("pt-PT")))

I get the error:

System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)

I tried to remove the blank space using g.Distance.replace(" ","") but it's not working.



via Chebli Mohamed

Find distinct values based upon multiple columns

I have a spreadsheet of sales with (to keep the example simple) 3 columns

NAME -- STATE -- COUNTRY 

It's easy to find how many sales. (sum all the lines) I can find out how many customers I have but how about finding out how many customers from a particular state (and country)

NAME -- STATE -- COUNTRY
p1----- CA------ USA
p2----- CA------ USA
p1----- CA------ USA
p1----- CA------ USA
p3----- NY------ USA
p3----- NY------ USA

The above example would give 2 unique customers from CA and 1 unique customer from NY and 3 from the USA

EDIT:

The desired result from the above table would be

STATE - UNIQUE CUSTOMERS 
CA ----  2
NY ----  1

COUNTRY - UNIQUE CUSTOMERS
USA ---- 3



via Chebli Mohamed

how to trim incoming values in a stored procedure in mysql?

I have my stored procedure defined as following:

CREATE PROCEDURE `customers`(
IN `in_customer_name` VARCHAR(255),
IN `in_primary_contact` VARCHAR(255), 
IN `in_phone` VARCHAR(255),
IN `in_email` VARCHAR(255), 
IN `in_address` VARCHAR(255),
IN `in_city` VARCHAR(255), 
IN `in_state` VARCHAR(255),
IN `in_zip` VARCHAR(255),
IN `in_tenant_id` INT(11),
IN `cus_id` INT(11),
IN `con_id` INT(11),
IN `loc_id` INT(11),
IN `usr_id` INT(11))


BEGIN

    DECLARE cont_name, cont_phone, cont_email, loc_address, loc_city, loc_state, loc_zip, cont_id VARCHAR(255);

the problem is that sometimes the incoming values have trailing spaces in left or right. I've heard of LTRIM and RTRIM, but I'm not sure if I can use them in incoming values and not just values selected from the database, and if so I can use them I don't know exactly how I can use them. Any ideas?



via Chebli Mohamed

Node.js - Log in to LinkedIn as an application vs client?

I'm trying to build an application that will read job postings from a LinkedIn site and load them into a database for future use - all back end.

Does anyone know where I can find a current working node.js example of signing in to LinkedIn as an "application", rather than as a "client/user"? Is there a difference?

I followed the tutorial here (http://ift.tt/1wF0QPo). I had to use passport-linkedin-oauth2 in order to retrieve an authorization token. After doing this, my passport.authentication fails - without any useful messages.

Here's all I get on the console before the app is routed back to the login screen:

c:\_Todd\_Projects\node-passport\aaa>node server
The magic happens on port 3000
GET / 304 26ms
GET /auth/linkedin 302 13ms - 264b
GET /auth/linkedin/callback?code=AQQe8cSBUaP8A_YRoB5FEncATOOvyMdsAoEsF_v_yYAvG0j2v3Q8ypE28ls5Yqqow6dkDtS16KQBrmhAYxvn9i4s36D6I4iQKSU
SBkaenuGhR7kIZSc&state=true 302 4ms - 35b
GET / 200 6ms - 1.13kb
GET /favicon.ico 404 1ms

My team lead said it looks like I'm trying to log in as a client (because I'm using the sign-in screen), and that I should log in as an application. Is there a difference??? I found some old tutorials that show "Consumer Key / API Key", but the current developer apps only have "Client ID".

Can someone please help?



via Chebli Mohamed

Async database creation with php

I am building a system where every account has its own databases. Creating these databases when the user is actually creating the account results in a long wait before the page is refreshed. Logically, since php is still busy, so the page cannot finish.

Therefore my idea is to 'buffer' up a few, like 5 of these packages, all named $DBNAME$number, where number is 1 to 5. So I just rename the databases at account creation time, thereby minimizing the wait. I think this will work pretty well, but off course, I need to replenish my buffer.

That's where I figured I'd need a method to just replenish the database buffer in the background, which could even run while the accounts database is prepared, and the user is already logging in. The thing is, I haven't found a solution to this, while looking aroung a lot. I tried pthread, which runs exactly as if I would run the code inline. I even gave ajax a shot, hoping the .php file will run async, but it will not.

Does anyone have a recommendation on how to achieve this goal I have? PS: if xy problem, you may notify me :)



via Chebli Mohamed

Determine Spring Version at runtime

Is there a way to determine my Spring Version at runtime? eg

log.info("I'm running spring version '{}'", SpringWhatever.getVersion());

Debug-level logging is not showing me anything.

Full background is that I can compile but am getting java.lang.NoSuchMethodError: org.springframework.context.support.PropertySourcesPlaceholderConfigurer.getAppliedPropertySources() at runtime.



via Chebli Mohamed

Is it possible to incorporate Ruby code into a lpsolve file?

I would like to know if it is possible for a file that is read by gem lpsolve in a rails app to read ruby code. If lpsolve can read ruby code then how can it do it?

Can gem lpsolve understand ruby code?

Just like how an html file can read ruby code when the file's name extension is "html.erb".



via Chebli Mohamed

tinymce setcontent getcontent, what is difference of default usage and format raw?

What is the difference

tinymce.activeEditor.setContent(foo);
tinymce.activeEditor.setContent(foo, {format:'raw'});

I know the documentation of tinymce.setContent/getContent but it does not explain too much. And i could not any detailed explanations or examples in stackoverflow or google. When should we use one and the other? Which drawbacks has each one? Can anyone give some more details? What I found so far is, i am using TinyMCE embedded in a java application and use it as mail reader and mail editor. When we receive an email written by outlook which contains numbered lists, the HTML of the mail contains mso tags. If we set the content which contains mso tags with default usage, setContent(foo), we can not see the numbered lists elements properly, they are left aligned. And other font problems occur. But if we use setContent(foo, {format:raw}) we can see the document properly. Why this difference occurs?



via Chebli Mohamed

Empty list bigger in size than corpus object in nltk

If some works with nltk and does a

from nltk.book import *

she will discover that text1 has object size of 64 bytes doing an

import sys
sys.getsizeof(text1)

If now she does a

text1 = []

the size of text1 increases to 72 ! Why is that? Why an empty list occupies more memory than its previous object form in my machine?

Does anyone know something about this? Thank you



via Chebli Mohamed

Do we still need to use `[...]` in Bash?

If don't care about compatibility, do we still need to use [...] in Bash? Many tutorial/book tell that [[...]] is more better/flexible than [...] e.g. [[...]] is support glob/regex, But today I still see many people prefer to use [...] as standard form, what is a reason behind this? What [[...]] can not do but [...] can do?



via Chebli Mohamed

dynamic task execution in java

I'd like to hear some advice on which technologies to use to solve this problem.

I would like a task executor based on events. These tasks are created by the user (in this moment I am thinking that a task would be a java class that implements the interface task, but I'm open to suggestions). Then the user could load a "jar" or "ear" in the application and using java reflection could execute new tasks.

Another approach I can think of would be that the user creates these tasks in a ejb, deploy the ear and make the ejb loockup to run tasks.

I appreciate any advice. sorry for my english



via Chebli Mohamed

Getting Specific Values from string

If i have a string that is

string Text="@Time:08:30PM,@Date:08/30/2015,@Duration:4,"

How would one go about extracting each of those starting with "@" and ending with the ",". I've searched and I've seen people get one pair with substring, but not how I need it. I want to say:

string Time = "08:30PM" //However i can extract it from that string
string Date = "08/30/2015" //etc...

Could it be done with Regex?

Thanks!



via Chebli Mohamed

Why am I not getting any data using these HQL queries?

I use this query to pull the highest encounter from the highest chapter a user has reached:

SELECT COUNT(hc.s) as users, highest_chapter, highest_encounter
FROM
(SELECT s, MAX(l) as highest_chapter
FROM appl9_evt
WHERE month = "201508" AND st1 = "player" AND st2 = "level_progression" AND n = "level_start"
GROUP BY s
ORDER BY highest_chapter) hc
INNER JOIN
(
SELECT s, l, MAX(get_json_object(json_data, '$.CurrentEncounter')) as highest_encounter 
FROM appl9_evt
WHERE month = "201508" AND st1 = "player" AND st2 = "level_progression" AND n = "level_start"
GROUP BY s, l
ORDER BY highest_encounter
) he
ON hc.s = he.s AND hc.highest_chapter = he.l 
GROUP BY highest_chapter, highest_encounter

Then I save it as a table and try to get only version 2.2.1 (or whatever version, a self-join I think it's called) with this:

SELECT COUNT(DISTINCT highest.s) as users, highest_chapter, highest_encounter FROM
(SELECT users as s, highest_chapter, highest_encounter 
FROM augusers221 ) highest
JOIN
(SELECT s 
FROM appl9_cpu
WHERE v_maj = '2.2.1') ver
ON highest.s = ver.s
GROUP BY highest_chapter, highest_encounter
ORDER BY highest_chapter, highest_encounter

But there's something wrong with this second stage, because I can't pull any data... Thank you in advance for looking at this wall of text.



via Chebli Mohamed

Sending to Multiple Emails in PHP

There is something off in this php, after the Reply-To email address in an email - I am getting a Cc afterward and it's not getting send to both the CC & BCC. This tells me I am making an error somewhere in this code and it's probably really obvious.

// Create email 
$email_subject = "Subject";
$email_body = "You have received interest. \n\n".
              "Name: $name \nEmail: $email \n";
$headers = "From: 1-email@email.com\n";
$headers .= "Reply-To: $email";
$headers .= "Cc: 2-email@email.com\r\n";
$headers .= "Bcc: 3-email@email.com\r\n";

mail($to,$email_subject,$email_body,$headers); // Post message



via Chebli Mohamed

bootstrap datepicker won't load from javascript

When I load the datepicker through the data-provide="datepicker", it will show up but not in safari. I also need to block out dates, such as the weekend. I was thinking both problems could be solved loading it through javascript and throwing in some config variables but I'm getting an error:

ReferenceError: $ is not defined

I'm thinking it's because maybe the jquery is being loaded in the wrong order, but other functionality is working.

Test site is here: http://ift.tt/1IAc7WZ

Field for datepicker is under "Select your prefered day & time"

Any help would be greatly appreciated!



via Chebli Mohamed

Select mismatch column values from database

I want to select and fetch all mismatch value of two table having same Column Name But Id, Name and City are different. I am Using Sql Server Management Studio

Table A:

id   Name   City

1    John   karachi

2    smith  Capetown

3     liza   Washington        

Table B:

id   Name   City

7    Grey   Dubai

8    Clarke  Texas

9     liza   Washington

OUTPUT:

7    Grey   Dubai

8    Clarke  Texas



via Chebli Mohamed

Can't Match Dates in VBA

My code is:

Application.Match(DateValue(x),dat,0)

and it's returning Error 2042

In the Watches I can see that:

The value of x is 02/01/2015 and it is a Variant/Date

The values ox DateValue(x) is 02/01/2015 and it is a Variant/Date

The value of dat(0) is #02/01/2015# and it is of the type Date

Any insights on why I'm getting th #N/A error ?

Thanks !

enter image description here



via Chebli Mohamed

Firebase Angularfire and Angular-nvD3

please visit this link. I used firebase as a backend data store. the front end is Angular. I try to draw chart by Angular-nvD3.js. when I try to read the data from firebase it is take time. So, the array come empty Array[]. then the data come but no update to the chart.

can someone help PlZ



via Chebli Mohamed

How to update a table with values coming from another table?

I found similar ones at here, but not exactly the same.

Here is what I need:

I have two tables a and b, with the following structures:

Table a:

id  b_id    b_col2 b_col3 col5
1   NULL    NULL   NULL   NULL
2   XXX     XXX    XXX    XXX

Table b:

id    col2 col3
101   ABC  DEF
102   XXX  XXX

UPDATE: The goal is that with three given inputs (id, b_id, col5), one row of table a should be updated accordingly. Specifically, b_col2 and b_col3 are extracted from table b with that b.id = b_id. For example, I want to update the first item of a with b_id=101 and col5 = ZZZ. Notice that b_col2 = ABC and b_col3 = DEF in this case, the updated row should be:

id  b_id    b_col2 b_col3 col5
1   101     ABC    DEF    ZZZ

I know there is at least a not-so-effective way which I don't like:

update a set 
    a.b_id = some-id, 
    a.b_col2 = (SELECT col2 FROM b WHERE b.id = some-id),
    a.b_col3 = (SELECT col3 FROM b WHERE b.id = some-id),
    ...
    where a.`id` = xxx

As I said, this is not a very good method, and I am just wondering if there is any better method?



via Chebli Mohamed

CakePHP dynamic form inputs

I'm using CakePHP 2.3.8 and I'm trying to create a form with dynamically added inputs from this tutorial but I'm having some issues. The adding and removing of inputs works just fine, but when I submit the form I get a black hole error message. Upon inspecting the inputs, it doesn't appear as if the key value isn't properly set and causing some issues with the id's of the inputs.

For example, with this code in an element

//Elements/users.ctp
$key = isset($key) ? $key : '<%= key %>';

<tr>
    <td><?php echo $this->Form->input("Role.{$key}.user_id", array('options' => $users, 'label' => false)); ?></td>
    <td class="actions">
        <a href="#" class="remove">Remove User</a>
    </td>
</tr>

this is the select that is generated

<select name="data[Role][0][user_id]" id="Role<%=Key%>UserId">

Edit

The value of $key is being set correctly on /Elements/users.ctp. I can create a row and echo the output of $key, and a number for the row appears correctly. As you can see above, the name of the element is set correctly, but the id is still being set strangely.

The name of the select element is being set properly, but not the id. What is causing the select id to be Role<%=Key%>UserId rather than Role0UserId?



via Chebli Mohamed

Django TemplateDoesNotExist at (but file exists)

I have an issue with template rendering.

Indeed django finds my templates files but each of them uses {% extends "base.html" %} and django does not find "base.html"

Django tried this path :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/base.html (File does not exist)

and my template file is in :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/inscription/home.html, error at line 2

It is real weird as the file "base.html" does exist at the first path. I don't know where the problem is.

I look forward to hearing from you soon



via Chebli Mohamed

Memory Leak - Socket or String related?

I have a simple function that allows me to get contents of a file on a server. It works just the way I want but "Visual Leak Detector" points out there is a memory leak on line closeSocket(...).

Code below:

string executeUrl(const char *url)
{
    SOCKET sConnection;
    char szHeader[500];

    sprintf(szHeader, "GET %s HTTP/1.0\r\n"
    "Host: %s\r\n"
    "User-Agent: Agent\r\n"
    "\r\n", url, HTTPSERVER);

    sConnection = HTTPConnectToServer(HTTPSERVER);
    if (sConnection == 0)
    {
        return "";
    }
    send(sConnection, szHeader, strlen(szHeader), 0);
    char reply[1024];
    ZeroMemory(reply, 1024);
    if (recv(sConnection, reply, 1024, 0) == SOCKET_ERROR)
    {
        return "";
    }
    string returnString(reply);
    closesocket(sConnection);
    WSACleanup();
    return returnString;
}

The data leaked is the string returnString. So it's either string related or something with closesocket().

I did some reading and I can't figure it out. Apparently strings should take care of themselves and not cause memory leaks, should they?



via Chebli Mohamed

NODEJS [electron io.js] send input to spawned process child.stdin.write();

I have a set of scripts in PowerShell. I built a GUI with a .HTA, but I am migrating over to a NODE.js like approach.

I have a working script, but I had to make a modification to work around the lost functionality to get input from the command line. I used to have the CMD prompt window appear where I would see all output and, if there was a prompt (Read-Host), the user could interact with it. To work around that, I am now using [Microsoft.VisualBasic.Interaction]::InputBox() to get input from the user when needed.

I have had issues trying to use child.stdin.write(); because my PowerShell process just hangs. It will not respond to my input.

I have tried every answer I have found on the net, with no success. The script that is called in production is a long running process, depending on the task selected it will take from 20 min to 3 hours.

So, issue is I cannot get the child.spawned process to send the input, or maybe PowerShell does not accept input from sdin.

Thanks for your help in advance.

CODE:

HTML:

<button type="button" id="btn_ExecuteReport">Run Report</button>
<button type="button" id="btn_StopReport" >Stop Report</button>
<button type="button" id="btn_SendInput" >Send this...</button>
<h2>Results:</h2>
<p id="result_id">...</p>
<br/>

JS (using Electron v 0.31.0, io.js v 3.1.0, jQuery v 1.7.2):

$(document).ready(function () {
    $("#btn_ExecuteReport").click(function (event) {
        event.stopPropagation();
        global.$ = $;

        var remote = require('remote');
        // to get some paths depending on OS
        var app = remote.require('app');
        //clipboard
        var clipboard = require('clipboard');
        var shell = require('shell');
        // for choosing a folder
        var dialog = remote.require('dialog');
        var spawn = require('child_process').spawn;
        sCmd = "powershell.exe ";
        sCmdArg = '&' + "'" + __dirname + "/app.ps1' " ;
        // omit parameters for the purpose of this example
        //    + "-ODir '" + sOutputDirectory 
        //    + "' -WDir '" + sWorkingDirectory + "'" 
        //    + " -Report " + sReport 
        //    + " -pSendEmail " + sSendEmail 
        //    + " -pSendEmailHTMLBody " + sSendEmailHTMLBody 
        //    + " -pCreateReport " + sCreateReport 
        //    + " -pCheckReport " + sCheckReport 
        //    + " -pEmailAction " + sEmailAction
        //    ;
        $("#result_id").html("<p><font color='magenta'>Command: </font>" 
                                          + sCmdConcat + "</p>");
        // try again with spawn and event handlers
        var psSpawn = spawn(sCmd, [sCmdArg]);
        // add a 'data' event listener for the spawn instance
        psSpawn.stdout.on('data', function(data) { 
            console.log('stdout: ' + data); 
        });
        // add an 'end' event listener to close the writeable stream
        psSpawn.stdout.on('end', function(data) {
            console.log('Done with psSpawn...' );
        });
        psSpawn.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
        });
        // when the spawn child process exits, check if there were any errors and close the writeable stream
        psSpawn.on('exit', function(code) {
            if (code != 0) {
                console.log('[EXIT] Failed: ' + code);
            }
            //Collect result from PowerShell (via clipboard)
            sResultData = clipboard.readText("Text");
        });

        psSpawn.on('close', function(code) {
            if (code != 0) {
                console.log('[ISSUE] code: ' + code);
            }
            console.log('[CLOSE]');
        });
        //sending the input with button #btn_sendInput
        $("#btn_SendInput").click(function (event) {
            psSpawn.stdin.setEncoding('utf8');
            psSpawn.stdin.write('ok');
            psSpawn.stdin.write('\n');
            psSpawn.stdin.write(os.EOL);
            //uncomment following line to end stdin on first button press
            //psSpawn.stdin.end();
        });

        // killing process
        $("#btn_StopReport").click(function (event) {
            event.stopPropagation();
            psSpawn.kill('SIGTERM');
            console.log('killed ' + psSpawn.pid);
        });
    });
});

PowerShell:

#work around to lack of Read-Host functionality
Write-Host "waiting"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$computer = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a computer name", "Computer", "$env:computername") 
#
Write-Host "[Done] waiting"
#workaround END works 
Write-Host "Computer: [$computer]"
# START omit ----------------
#if we remove the following lines, all works but we lose the functionality to ask for input from the command line
Write-Host "Propmt for OK" 
$ok = Read-Host 
#
Write-Host "Prompt. Value of 'ok': [$ok]"
# END omit ----------------
#Copy new message to clipboard
"we want to see this maessage on the browser. $computer" | clip

#Exit script returning the appropriate value
[Environment]::Exit(0)
exit

My console output is:

stdout: waiting
daily_deviation.js:103 stdout: 

daily_deviation.js:103 stdout: [Done] waiting
Computer: [0199HR10A]
Propmt for OK

The script hands no matter how many times I press Send this.... The console output is (after pressing the #buton_StopReport):

killed 2548
daily_deviation.js:107 Done with psSpawn...
daily_deviation.js:115 [EXIT] Failed: null
daily_deviation.js:140 [ISSUE] code: null
daily_deviation.js:142 [CLOSE]



via Chebli Mohamed

Stop Loading Nodes in Ajax Loading / Lazy Loading in JSTree

I am using JSTree with Ajax Loading / Lazy Loading functionality in my application.

Now I am trying to Open All nodes. So in Loaded event i write open_all method to open all nodes.

$('#DIVTree').jstree({
        'core': {
            'multiple': false,
            'data': {
                'url': appRootDir + 'Tree/GetFilterList',
                'data': function (node) {
                    return { 'ID': node.id};
                }
            }
        },
        'plugins': ['state'],
}).on('loaded.jstree', function (node) {
    $('#DIVTree').jstree(true).open_all();
});

Now this starts opening all node which i actually wanted.

But now i am having one more button Cancel.

I want to allow user to stop loading nodes when the cancel button is pressed.

I tried lots of ways. I tried to implement recursion with "after_open" event and "load_node" event.

$('#DIVTree').jstree({
        'core': {
            'multiple': false,
            'data': {
                'url': appRootDir + 'Tree/GetFilterList',
                'data': function (node) {
                    return { 'ID': node.id };
                }
            }
        },
        'plugins': ['state'],
}).on('loaded.jstree', function (node) {
        if (recrusiveStop == false) {
            OpenNodes();
        }
}).on('after_open.jstree', function (node) {
        if (recrusiveStop == false) {
            OpenNodes();
        }
});

var OpenNodes = function () {
    var nodeID = '';

    $('#DIVTree .jstree-closed').each(function () {
        if ($('#DIVTree').jstree(true).is_loaded(this.id) == false) {
            nodeID = this.id;
            return false;
        }
    });

    if (nodeID != '') {
        $('#DIVTree').jstree(true).open_node(nodeID);
    }
}

But still unable to implement.

In "after_open" event is fired only once. So only one node is expanded (not having sub-node) so not staying in loop. while i still want to expand siblings.

Is there any clear way to implement this?

I want to Open all nodes and also stop loading when user hits cancel button.



via Chebli Mohamed

Does New Macbook 12inch is able to run php with mysql?

I have a database class, and it needs to run php , mysql, tomcat. I just want to know does the new Macbook 12inch should be able to do that ?

I might need to do some programing exercise for fun... just want to know if this new mac can handle it....



via Chebli Mohamed

Swift - check if JSON is valid

let data = NSData(contentsOfFile: "myfile")
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonData: NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var validJson = false

if (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) != nil) {
    validJson = true
}

I want the code above to only set validJson true when the contents of jsonData is actually valid JSON. At the moment if I pump anything into the "myfile" file which can be seen in the code, validJson is always true.

How can I fix this so validJson is only true when it's actually valid JSON?



via Chebli Mohamed

Firefox is blocking insecure content

I am running a UI automation script on a https site. I get 'Firefox is blocking insecure content" warning every-time on a particular page. for now i am manually disabling protection from options but, how to set protection disabled permanently so that my scripts won't break when i run them for regression?

enter image description here



via Chebli Mohamed

SQL query to make distinct lines with case being used

Here is what my data looks like on the table I am querying

Table 1

ITEM     SEQUENCE     CODE
Item1       1            A 
Item1       2            B
Item2       1            B
Item2       2            C
Item2       3            D

My current Query looks like

  Select Distinct Table1.ITEM, 
  case when Table1.SEQUENCE = '1' Then Table2.DSC end As FirstDSC,
  Case When Table1.SEQUENCE = '2' then Table2.DSC End As SecondDSC,
  Case When Table1.SEQUENCE = '3' Then Table2.DSC End As ThirdDSC
    From Table1
    Join Table2 on Table2.Code = Table1.Code
    Where Table1.Item In (Subquery here to find distinct values that Item can be)

It currently returns the data looking like

ITEM  FIRSTDSC SECONDDSC THIRDDSC
Item1   DSC-A     NULL      NULL
Item1   NULL     DSC-B      NULL 

I was wondering how to make the data return looking like

ITEM FIRSTDSC  SECONDDSC  THIRDDSC
Item1  DSC-A      DSC-B       NULL
Item2  DSC-B      DSC-C       DSC-D

Is there a good way to do this or am I going in the completely wrong direction with my query currently?



via Chebli Mohamed

On mouseout animate line to disappear

Right now, I've got it to draw a line when you mouseon but I want it so that when you mouseout the line disappears left to right.

http://ift.tt/1IA9dl9

$( "#name" ).mouseover(function() { 

$('.slider').animate({
    width: $('#name').width()
}, 1000);

});



via Chebli Mohamed

Access to GitHub only possible with

I can successfully add files to a local repository and push it to github using github desktop. When I try to commit to github using the git commandline or GitExtensions I get an error

"C:\Program Files\Git\bin\git.exe" push --recurse-submodules=check --progress "origin" refs/heads/master:refs/heads/master
remote: Invalid username or password.
fatal: Authentication failed for 'http://ift.tt/1EtNNuM'
Done

I dont have 2fa enabled. What is github desktop doing different that it can login?



via Chebli Mohamed

Are there Powershell cmdlets that install and remove Windows drivers?

Note: For this question, when I refer to "Windows drivers" I mean .inf and associated files which can otherwise be installed by right-clicking the .inf and clicking "Install" in Windows Explorer. I do not mean any kind of setup.exe-style executable which might install a driver.


There exists the following:

I have not, however, found a corresponding Powershell Cmdlet that supports installing and uninstalling drivers on the running system. I'm sure I could wrap dpinst.exe in some powershell, but I'd like to avoid mapping command line parameters and parsing output if a more Powershell-native method exists.

Do Powershell Cmdlets exist that install and uninstall Windows drivers on the running system? Is there some other way to install and uninstall Windows drivers using Powershell that does not involve dpinst.exe?



via Chebli Mohamed

Accessing audio input while loading a project from file://

I wonder to know if it is possible to somehow prevent Chrome from blocking my project audio input because I'm not loading it from a local host but from file://... a.k.a. my HDD. I'm asking about this because I've understood that when the script is non-server but loaded from file:// Chrome automatically blocks it and it can't reach the asking for mic usage permission step. I'm playing around with annyang, so yeah, if someone knows how to enable the described above, please share, as I still have no idea of php, mysqul and others for establishing a local host environment.



via Chebli Mohamed

Which index is needed for a Mongoid order_by and find_by query?

To find the most recently created user named "Jeff",

User.order_by(created_at: :desc)
    .find_by(name: "Jeff")

Which indexes should be created for this query? Would it be 2 indexes, on created_at and name?

Or a compound index on both?



via Chebli Mohamed

Dynamically resize columns based on how many there are in a row

I'm trying to make a responsive column layout that resizes depending on the number of columns.

Link to JsFiddle

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter">1/4</div>
<div class="box quarter">1/4</div>
</div>

<div class="row">
<div class="box half">1/2</div>
<div class="box quarter hidden">1/4</div>
<div class="box quarter">1/4</div>
</div>

So, what I'm trying to do is if I add the class "hidden" to one of the boxes, the other boxes will resize and fill up the row. For example, in the first row we have one column 50% and two columns 25%; If I hide one 25% column, the first column will have 66% and the 2nd one will have 33%.

I have to do this without adding any other classes to html and work in IE8+.



via Chebli Mohamed

Subtraction/dfference between bytes in Java

I'm trying to subtract one byte from another while making sure no overflow happens, but get unexpected results.

In the following code, I expect data2 array to be subtracted from data1 array. However I get low values when I am sure there should be high ones.

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] - data2[i]);
        } else {
            dest[i] = 0;
        }
    }

I figured I should make sure data2 byte isn't negative and being added to data1. So I came to:

    for (int i = 0; i < data1.length; i++) {
        if (data1[i] > data2[i]) {
            dest[i] = (byte) (data1[i] & 0xff - data2[i] & 0xff);
        } else {
            dest[i] = 0;
        }
    }

However this also doesn't give the right results.

I hope I'm doing something stupidly wrong here, or my problem resides somewhere else of which I can't figure out where.



via Chebli Mohamed

Check if pointer object created is less than today Parse.com

hey guys i have a table A which has a pointer to Table B. I am trying to query Table A where Table B created At is less than today

Table A (columns)

Name, Table B pointer, ....

Table B CreatedAt

So far I have this

    let query = PFQuery(className:Globals.ParseObjects.ProLeagueWinnings)
    query.fromLocalDatastore()
    query.fromPinWithName("XXX")

    query.includeKey("TableB")

    query.whereKeyExists("TableB")
    query.whereKey("TableB.CreatedAt", lessThanOrEqualTo: NSDate())
    query.findObjectsInBackground().continueWithSuccessBlock {
        (task: BFTask!) -> AnyObject! in

        let leagues = task.result as? [ProLeagueWinnings]
        if (completion != nil){
            if leagues != nil{
                completion!(leagues!)
            }else{
                completion!([])
            }
        }

        return task
    }

But it returns everything.



via Chebli Mohamed

Implementation of method accepting lambda

I'm interested to understand how are implemented LabelFor, EditorFor... methods that accept lambda expressions in MVC.

Lets say I have a class Person and I want to print the name and the value of a property. How must be implemented Label() and Editor() methods?

  class Person
  {
     public int Id { get; set; }
  }

  void Label(Expression<Func<Person, int>> expression)
  {
     //...
  }

  void Editor(Expression<Func<Person, int>> expression)
  {
     //...
  }

  public void Test()
  {
     Person p = new Person
     {
        Id = 42
     };

     Label(x => x.Id );  // print "Id"
     Editor(x => x.Id); // print "42"

  }



via Chebli Mohamed

Panel sliding from the bottom

I want to implement panel, that by default appears from the bottom only by 1/4. And when i tap on this part, or swipe it, it should roll out on full screen.

exactly what i want was implemented in this app

So what i tried already: Making UIView and trying to apply tap and swipe gestures. UIView didn't catch it. But it caught touchesMoved, touchesEnded etc. UITableView. Same. Making UIViewController. Ended without any idea how to handle it to right way.

So any ideas or links are appreciated. Thanks in advance.



via Chebli Mohamed

Finding and replacing strings with certain character patterns in array

I have a pretty large database with some data listed in this format, mixed up with another bunch of words in the keywords column.

BA 093, RJ 342, ES 324, etc.

The characters themselves always vary but the structure remains the same. I would like to change all of the strings that obey this character structure : 2 characters A-Z, space, 3 characters 0-9 to the following:

BA-093, RJ-342, ES-324, etc.

Be mindful that these strings are mixed up with a bunch of other strings, so I need to isolate them before replacing the empty space.

I have written the beginning of the script that picks up all the data and shows it on the browser to find a solution, but I'm unsure on what to do with my if statement to isolate the strings and replace them. And since I'm using explode it is probably turning the data above into two separate arrays each, which further complicates things.

<?php

require 'includes/connect.php';

$pullkeywords = $db->query("SELECT keywords FROM main");

while ($result = $pullkeywords->fetch_object()) {

    $separatekeywords = explode(" ", $result->keywords);
    print_r ($separatekeywords);
    echo "<br />";
}

Any help is appreciated. Thank you in advance.



via Chebli Mohamed

Autocomplete: from pure JS to ReactJS

I am working on an auto-complete, right now I have it in pure JS

here I have this example in JSFiddle

<input type="text" onkeyup="changeInput(this.value)">

<div id="result"></div>

the js part

var people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

function matchPeople(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return people.filter(function(person) {
    if (person.match(reg)) {
      return person;
    }
  });
}

function changeInput(val) {
  var autoCompleteResult = matchPeople(val);
  document.getElementById("result").innerHTML = autoCompleteResult;
}

but I need to translate it to ReactJS, and I am not getting good results

let people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];

class Login extends Component {

  render () {
    return (
      <Grid>
          <input type="text" onkeyup={this._changeInput(this.value)} />
          <div id="result"></div>
      </Grid>
    );
  }

  _matchPeople = (input) => {
    var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
    return people.filter(function(person) {
      if (person.match(reg)) {
        return person;
      }
    });
  }

  _changeInput = (val) => {
    var autoCompleteResult = this._matchPeople(val);
    document.getElementById("result").innerHTML = autoCompleteResult;
  }  

}

Error in the console:

Uncaught TypeError: Cannot read property 'split' of undefined

what am I missing ?



via Chebli Mohamed

Matching values from different columns, GOOGLE SHEETS

Google sheets,

I have columns a with 5000 rows and column b with 3000 rows.

How to check if value from A1,A2,A3 ETC is in B1:B3000 so I would see 5000 rows in column C with either True or False?



via Chebli Mohamed

Send a bitmap image in an email

I looked over similar questions and tried to write this simple code. This code takes an bitmap image of the view then allows the user to attach it to email. for some reason I get the message "can't attach an empty file" in the email application. I'm fairly new to this and I read a few examples and tried different things but non worked. I suspect that something might be wrong with my path.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.example.asamater.myapplication" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"   android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/linearLayout">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:text="Q1" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton2" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:text="Q2" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton3" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton4" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:text="Q3" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton5" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton6" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4"
            android:text="Q3" />


        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton7" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton8" />
        </RadioGroup>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5"
            android:text="Q4" />

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton10" />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New RadioButton"
                android:id="@+id/radioButton9" />
        </RadioGroup>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email"
            android:id="@+id/button"
            android:layout_alignTop="@id/radioButton9"
            android:onClick="email" />

    </LinearLayout>



</ScrollView>

</RelativeLayout>

.

 package com.example.asamater.myapplication;

 import android.app.Activity;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.BitSet;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void email(View view){
    ScrollView z = (ScrollView) findViewById(R.id.scrollView);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();
    Bitmap bitmap = getBitmapFromView(z,totalHeight,totalWidth);
    String path = saveImageToStorage(bitmap);

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "ammar5001@gmail.com");
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "report");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, " ");

    emailIntent.setType("image/jpeg");
    File bitmapFile = new File(Environment.getExternalStorageDirectory()+
            "/"+ path);
    Uri myUri = Uri.fromFile(bitmapFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);


    startActivity(Intent.createChooser(emailIntent, "Send your email in:"));

}


private String saveImageToStorage(Bitmap bitmap) {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/req_images");
    myDir.mkdirs();
    String fname = "Image-Report.jpg";
    File file = new File(myDir, fname);
    Log.i("myActivity", "" + file);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        return root + "/req_images" + fname;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

}



via Chebli Mohamed

How to convert Multilevel numbering list from Word document into text value in HTML

I am reviewing multiple Rich Text Editors to find the right one for a VB.NET web application which has IE11 incompatible Rich Text Editor.

With the IE11 compatibility, the most important requirement from clients is a functionality that copies contents from Word documents over into text editor without losing it Word formatting. (The content will be saved into database and be read by MS Word again)

However, all the Rich Text Editors that I have reviewed do not support the multilevel list formatting correctly. They change the multi-level numbers into single level numbers when coping the multi-level list from Word into them. - Rad Editor, CKEditor, tiny-mce and Rich Text Editor and so on.

Example,

1. A
  1.1. B
  1.2. B
    1.2.1. C
2. A
  2.1. B
  2.2. B

becomes

1. A
  1. B
  2. B
    1. C
2. A
  1. B
  2. B

I found a CSS trick to display <li> tag as multilevel numbers in the browser, but the numbers are not actual text values that can be saved into database. So, I need another solution that can save numbers and their format into the database like the current Rich Text Editor in my VB.Net web application. (It is a DLL, but not JavaScript library)

Can I get some helps/advices how to resolve this problem when copying over multi-level numbering list from Word into the RichTextEditor?

Thanks for answering in advance.



via Chebli Mohamed

Bootstrap column reordering on at least three screen sizes

I have problem with Bootstrap column rendering when I try to specify column reordering for three different screen sizes.

XS devices:

  • A
  • B
  • C
  • D

SM and MD devices:

  • B A
  • D C

LG devices:

  • D C B A

I can achieve XS and LG pattern or XS and MD pattern, but unfortunately not all three options at the same time. Is this possible with Bootstrap's classes?

Solution for XS and LG:

<div class="container">
    <div class="row">
        <div class="col-xs-12 col-lg-3 col-lg-push-9">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
             </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-push-3">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-3">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-lg-3 col-lg-pull-9">
            <div class="form-group">
                <label>Label4</label>
                <input type="text" class="form-control" />
            </div>
        </div>
    </div>
</div>

Now when I add middle view classes all get messed up. Is there an option to fix this?

<div class="container" style="background-color: pink">
    <div class="row">
        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-push-9 col-lg-pull-0">
            <div class="form-group">
                <label>Label1</label>
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-pull-6  col-lg-3 col-lg-push-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label2</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6 col-md-push-6 col-lg-3 col-lg-pull-3 col-lg-pull-0">
            <div class="form-group">
                <label>Label3</label>
                <input type="text" class="form-control" />
            </div>
        </div>

        <div class="col-xs-12 col-md-6  col-md-pull-6 col-lg-3 col-lg-pull-9 col-lg-push-0">
            <p>empty</p>
        </div>
    </div>
</div>

The following code is my best try but it simply does not work... Any ideas?



via Chebli Mohamed

Why does my OneToOne mapping through a JoinTable not work?

I've searched but cannot seem to find the answer.

I have two tables:

select ts_id, tsjoin_id, workdate from TimeSheets
select e_id, lastname from Employees

I also have a join table:

TSJoin
tsjoin_id, employee_id

There is only one Employee to a TimeSheet. So with any given TimeSheet entity, I'd expect to be able to:

TimeSheet ts = tsService.getTimeSheet(123);
String lastName = ts.getEmployee().getLastName();

In SQL, to get the employee of a TimeSheet:

select e.lastname from TimeSheets t
    join TSJoin x on (x.tsjoin_id = t.tsjoin_id)
    join Employees e on (e.e_id = x.employee_id)
where t.ts_id = 123

In my Hibernate mapping, I have:

@OneToOne
@JoinTable(
        name = "TSJoin",
        joinColumns = {
                @JoinColumn(name = "tsjoin_id", nullable = false)
        },
        inverseJoinColumns = {
                @JoinColumn(name = "e_id", nullable = false)
        }
)

However, the SQL it's generating is:

select * from TimeSheet t
    left outer join TSJoin x on (t.ts_id = x.tsjoin_id)

Which returns null for the Employee.

It's taking the primary key of the TimeSheet and trying to match the primary key of the join table.

What am I doing wrong?

EDIT

I also want to state that I have only setup one direction at this point. Which is a TimeSheet -> Employee (OneToOne) and that Employee is not mapped to TimeSheet yet. Not sure if this makes a difference but I wanted to mention it.

EDIT 2 I also want to state that I believe the error might be because my join table does not contain a reference to the TimeSheet. And Hibernate is assuming that a join table is going to contain the primary keys of each entity involved (legacy database). I could probably create a mapping of TimeSheet -> JoinTable -> Employee and access it as: ts.getJoin().getEmployee() but that's pretty ugly.



via Chebli Mohamed

Odd Errors Displayed Only in Console When Trying to Run Program

So I'm watching a tutorial to learn how to program in Java using Eclipse. So I got a few episodes in and I had to clear out all out the errors. I looked around and found no more errors so I tried to run the program and I got errors in that were only displayed in the console, and was being displayed next to the lines it was referencing. I have completely no idea how to solve these errors I haven't seen anything like them before. Also my program is fairly simple it is just the code to display and window and then have pixels of a random colour fill that window. I really would appreciate any help I can get, because I have no clue how to fix this error.

Thanks, Nova

Tutorial

Error:

`Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar` 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 65536 
at cpm.mime.GameP1.graphics.Screen.<init>(Screen.java:14) 
at com.mime.GameP1.Display.<init>(Display.java:29) 
at com.mime.GameP1.Display.main(Display.java:92)`



via Chebli Mohamed

Linq Expression in Case Statement

I'm using LINQ with Expression trees and a case Statement in my Select. I'm doing this because the Where Condition is build dynamically and in my Result, I need to know, which part of the where was true.

This works fine:

ParameterExpression peTbl = Expression.Parameter(typeof(MyTbl), "mytbl");

Expression left = Expression.Property(peTbl, "Col1");
Expression right = Expression.Constant((ulong)3344, typeof(ulong));
Expression e1 = Expression.Equal(left, right);

left = Expression.Property(peTbl, "Col2");
right = Expression.Constant((ulong)27, typeof(ulong));
Expression e2 = Expression.Equal(left, right);

Expression predicateBody = Expression.Or(e1, e2);

Expression<Func<MyTbl, bool>> whereCondition = Expression.Lambda<Func<MyTbl, bool>>(predicateBody, new ParameterExpression[] { peTbl });

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (s.Col1 == 3344 ? 1 : 0) });

But now, I want to use the Expression e1 in my case Statement.

Something like this:

var query = myTbl.Where(whereCondition)
            .Select(s => new { mytbl = s, mycase = (e1 == true ? 1 : 0) });

Any idea how to do this?



via Chebli Mohamed

Python One-Liner: Sorting by multiple, interdepending keys

Disclaimer: This question is about me and hopefully others understanding Python better. My problem can be solved easily in more than one line, I know that.

Suppose I have two functions f(x), g(x,y) so that I can compute the tuple ( f(x), g(x,f(x)) ) as a function of x. I want to sort a list X by these two keys but computing f(x) is expensive so I want to do it only once per x. My current solution is:

X_s = sorted( X , key =  lambda x: (lambda y: ( y , g(x,y) ) )( f(x) ) )

Can I achieve the same without using two lambda functions?



via Chebli Mohamed

Database for user Accounts ionic framework

I need to incorporate a simple user profile for each person who uses my ionic android app. That way they can login and access or edit personal information unique to their personal accounts.

I've been browsing all over the net for a day, and especially the ionic documentation for any info on how to make such a feature on my app. I can do that using php and mysql but don't know about ionic's approach. Please advice.



via Chebli Mohamed

vendredi 8 mai 2015

jquery post call not working with slash at end of the url

example url:
Target is not to show .php extension, but content stop working when page/url is open with a slash at the end.
http://ift.tt/1F9Oyt6 - form is working with this url
http://ift.tt/1EnOLSI - form is not working with this url

Folder & files:
|
| /js/custom.js
| /manager/create.php
| /manager/creategetpostdata.php
| /manager/.htaccess

Content on custom.js

$(window).load(function() {
    // get post code data
    $('.contentfinder').on('keyup', function(e){
        var xyz = $(this).closest('.contentRow');
        //alert( "success" );
        $.post("../manager/creategetpostdata.php", xyz.find('.contentfinder').serialize(),  function(response) {
            //alert( "success" );
            xyz.children('.showPostData').html(response);
            xyz.children('.showPostData').show();
        });

    });

});

input form on create.php file:

                    <div class="contentRow">
                        <input type="text" name="inputdata" class="form-control contentfinder" placeholder="" />
                        <div class="showPostData"></div>
                    </div>

content on creategetpostdata.php

<?php echo 'hello, what the hell wrong with you. just show content now!'; ?>

content on .htaccess file

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\?([^=]+)=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/%3? [R=302,L,NE]

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\s [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

any help? thanks in advance.

Section will be overlapped by header when come from another page

I have the following problem. What I want is when the user clicks in the navigation bar on "Contact" it will link to the contact page. This is a single page. When you are on contact and then clicking at the bottom of the page on, for example "Over ons" it should be redirect to the homepage (single page) and stop at that section. This works, but when you come from another page, the current section is overlapped by the header.

The jQuery code will not use the offset of the header, only when you are navigation inside the index.html.

Is there a way to fix the issue, so the section will not be overlapped by the header?

Live example:

http://ift.tt/1KRmFou

Wiki hosted on Pbworks and jQuery?

I added jquery and another script at the bottom of my wiki page. However, if I can get node contents with regular javascript (getElementBy…), it doesn't work with jQuery ($("selector") where it always return null. Any idea why ?

You can see the console log here : http://ift.tt/1KRmFoq

And here is my code :

<script src="http://ift.tt/1yCEpkO"></script>

<script>
$(window).load(function(){
console.log(document.getElementById("wikicontent").innerHTML);
console.log($("#wikicontent").html());
});
</script>

Remove the Vimeo placeholder from Iframe

Are there any tricks to remove the placeholder/poster from an Iframe when embedding a video from Vimeo?

I have tried unwrapping the ".flideo" div to remove it's parent div, which is the ".cover" div which contains the placeholder image as a background image. I also tried to empty the "background-image" value, but that didn't work either.

Here is the generated source code:

<div class="video cover" data-thumb="http://ift.tt/1KRmE3R" style="background-image: url(http://ift.tt/1KRmE3R);">
<div class="flideo cloaked" style="-webkit-transform: scale(1.00023496240602); transform: scale(1.00023496240602);">
        <video x-webkit-airplay="allow" preload="metadata" src="http://ift.tt/1zR83Vk"></video> 
</div>
</div>

Jquery simple accordian

I have simple Jquery accordian, but i have problem of changing header color when tab is opened

Here is my code

HTML

<dl class="accordion-modal">

    <dt><a href=""><header>FIRST</header></a></dt>
            <dd class="active-accordian">FIRST CONTENT</dd>

<dt><a href=""><header>SECOND</header></a></dt>
<dd>SECOND CONTENT</dd>

</dl>

JS

(function($) {

  var allPanels = $('.accordion-modal > dd').hide();
  $('.accordion-modal > .active-accordian').show();

  $('.accordion-modal > dt > a').click(function() {
      $this = $(this);
      $target =  $this.parent().next();

      if(!$target.hasClass('active')){
         allPanels.removeClass('active').slideUp();
         $target.addClass('active').slideDown();
      }

    return false;
  });

})(jQuery);

CSS

header{
    background-color:green;
}

.active{
    background-color:red;
}

.active-header-color{
    background-color:blue;
}

What i need when some content is show to add class to that header? Here is working fiddle http://ift.tt/1zR82QY

how can I get the date picker to start select from at least 8 previous days back from this days date?

I try to make a date picker where you can only choose dates from 8 days left. If we have the date 09 / 05-2015 you can not select (8,7,6,5,4,3,2) but you can choose the 01 / 05-2015 and go down. How can i make that?

$(document).ready(function() {

$(".date-picker").datepicker({       
    todayHighlight: true,   
});

$(".date-picker").datepicker().datepicker("setDate", new Date()); //sets the todays date in the input field
$(".date-picker").on("change", function () {
var id = $(this).attr("id");
var val = $("label[for='" + id + "']").text();
$("#msg").text(val + " changed");
});

}); // end of document ready

Ajax in .NET for form editing

I have a form where user can create a complex object. When click on "Add action", then an Ajax call is made in JS, and I use a partialview as return, then I show it as accordion in the form and all is OK for that creation form.

Now, I want to make the same form but for editing, so I have my basic form that works well, but I'm like blocked for the edit form, especially for the partiaviews called by pressing the "Add action" button ...

In the Edit Form, I have a List that contains all the data of each "add action", How can I handle/load/show this in the view?

Can I make one include of the partialView (and passing data) by only using C#?

here is what I've did:

Finally, this is my ajax call from Create JS:

    var x = 0; // problem count
    // method called when user click on add problem
    $(".add_action_button").click(function (event) {
        event.preventDefault();

        // ajax call to partial with prefix
        var prefix = "actionList[" + x + "]";
        $.ajax({
            url: "@Url.Action("AddAction", "Home")",
            cache: false,
            type: "GET",
            dataType: "html",
            traditional: true,
            data: { prefix: prefix, accordioncounter: x + 1 },
            success: function (result) {
                // lot of stuff
            }
        });
    });

AddAction Controller:

public ActionResult AddAction(string prefix, int accordioncounter)
        {
            ViewBag.Prefix = prefix;
            ViewBag.accordioncounter = accordioncounter;

            return PartialView("_AddAction", new ActionViewModel());
        }

_AddAction View:

@model MyModel.ActionViewModel

@{
    if (!string.IsNullOrEmpty(ViewBag.Prefix))
    {
        ViewData.TemplateInfo.HtmlFieldPrefix = ViewBag.Prefix;
    }
}
...

And I have this object in my model from my Edit view:

public List<ActionViewModel> actionList { get; set; }

Thanks in advance for your help :-)

Stop or destroy a jQuery plugin

I have a push menu and it has an animated gradient but I only want it to animated/play when the menu is open, obviously for performance reasons.

My gradient plugin code is as follows:

// Animated Gradient
var colors = new Array(
   [62,35,255],
   [60,255,60],
   [255,35,98],
   [45,175,230],
   [255,0,255],
   [255,128,0]);

var step = 0;
var colorIndices = [0,1,2,3];

var gradientSpeed = 0.001;

function updateGradient()
{

if ( $===undefined ) return;

  var c0_0 = colors[colorIndices[0]];
  var c0_1 = colors[colorIndices[1]];
  var c1_0 = colors[colorIndices[2]];
  var c1_1 = colors[colorIndices[3]];

  var istep = 1 - step;
  var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
  var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
  var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
  var color1 = "rgb("+r1+","+g1+","+b1+")";

  var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
  var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
  var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
  var color2 = "rgb("+r2+","+g2+","+b2+")";

  $('#primary-menu').css({
    background: "-webkit-gradient(linear, left top, right bottom, from("+color1+"), to("+color2+"))"}).css({
    background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

step += gradientSpeed;
if ( step >= 1 )
{
    step %= 1;
    colorIndices[0] = colorIndices[1];
    colorIndices[2] = colorIndices[3];

    colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
    colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;

}
}

I have managed to only play the animated gradient when I open the menu but I'm having trouble stopping it when I close the menu, how can I do this?:

showmenu.onclick = function() {

    if ($('nav').hasClass('visible')) {

        // Closed menu code here

    } else {

        // Opened menu code here 

        // Initialise plugin when menu is open
        setInterval(updateGradient,10);

    }

};

How to add a "random" button that applies to two drop down menus

I have created a page with two drop-down menus containing various values. Now I would like to add a "randomize" button. When clicked, this button would select any of the values at random in both fields. (the values are also copied on a box above each menu).

Project idea for drop down menus

So far I've coded the menus and the words display in the boxes above them when the user selects them. But now I'm trying to add a randomise button that would put any of the values in the drop down as selected and of course displayed in the above text box. Ideally, more values in the drop-down menus would be added every once in a while without making the script dysfunctional... and ideally it would all be contained in a HTML file (calling for JQuery or javascript is ok).

I've looked at this but it doesn't apply.

I also looked at this but it's not really a feature that the user activates.

Very grateful if anyone can help! Thanks

Dropdown not sticking when navigating back

Not sure what I am doing wrong but the info that I select does not stick anymore when I navigate to another page and then go back.

This is code that works. It's for a a regular attendee:

 <div class="linegroup">
                                                <label class="notrequired" id="dietaryNeed_g1">Meal Preferences</label>
                                                <select name="dietaryNeedValue_g1" id="dietaryNeedValue_g1" class="lbl-col-right" onclick="mealPrefs();" >                              
                                                    <optgroup label="Please Select Your Meal Preferences" >  
                                                        <%--<%=cache.getValueListHTML("ALL_MEALCODE", addSelect, d)%>--%>
                                                        <option value=""></option>
                                                        <option value="DAIRY" <%if(formFields.getDisplayValue("dietaryConsiderationsOther_g1").equalsIgnoreCase("Dairy-Free")){ %> selected <%}%> >Dairy Free</option>
                                                        <option value="FOODALLE" <%=formFields.getSelectValue("dietaryNeedValue_g1", "FOODALLE")%> >Food Allergy</option>
                                                        <option value="KOSHER" <%=formFields.getSelectValue("dietaryNeedValue_g1", "KOSHER")%>>Kosher</option>
                                                        <option value="HALAL" <%=formFields.getSelectValue("dietaryNeedValue_g1", "HALAL")%>>Halal</option>
                                                        <option value="VEGAN" <%=formFields.getSelectValue("dietaryNeedValue_g1", "VEGAN")%>>Vegan</option>
                                                        <option value="VEGTRIAN" <%=formFields.getSelectValue("dietaryNeedValue_g1", "VEGTRIAN")%>>Vegetarian</option>
                                                        <option value="GLUTFREE" <%=formFields.getSelectValue("dietaryNeedValue_g1", "GLUTFREE")%>>Gluten-Free</option>
                                                        <option value="OTHER" <%=formFields.getSelectValue("dietaryNeedValue_g1", "OTHER")%>>Other</option> 
                                                    </optgroup>
                                                </select>

                                            </div>

This is the code for a guest. For some reason this drop down disappears whenever I go to the next page and then navigate back.

<div class="linegroup">
                        <label class="required" id="dietaryNeed_g<%=i%>">Meal Preferences</label>
                        <select name="dietaryNeedValue_g<%=i%>" id="dietaryNeedValue_g<%=i%>" data-parsley-trigger="focusout" class="firstselect lbl-col-right"  onchange="mealPrefs();" novalidate >
                            <optgroup label="Please Select Your Meal Preferences" >  
                                <%--<%=cache.getValueListHTML("ALL_MEALCODE", addSelect, d)%>--%>
                                <option value=""></option>
                                <option value="DAIRY" <%if(formFields.getDisplayValue("dietaryConsiderationsOther_g"+ i).equalsIgnoreCase("Dairy-Free")){ %> selected <%}%> >Dairy Free</option>
                                <option value="FOODALLE" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "FOODALLE")%> >Food Allergy</option>
                                <option value="KOSHER" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "KOSHER")%>>Kosher</option>
                                <option value="HALAL" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "HALAL")%>>Halal</option>
                                <option value="VEGAN" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "VEGAN")%>>Vegan</option>
                                <option value="VEGTRIAN" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "VEGTRIAN")%>>Vegetarian</option>
                                <option value="GLUTFREE" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "GLUTFREE")%>>Gluten-Free</option>
                                <option value="OTHER" <%=formFields.getSelectValue("dietaryNeedValue_g" + i, "OTHER")%>>Other</option> 
                            </optgroup>                                         
                        </select>
                    </div>

Any ideas on how to make the Guest dropdown stick?

ajax uploading multiple images not showing multiple filenames

I have this code I'm using to upload multiple images via ajax call. In console I can see the combined data being sent but not the multiple file names. Im not sure when sending multiple images what I should see in the network-paramaters view in console.

This is what I'm seeing in console

-----------------------------82392211927416 Content-Disposition: form-data; name="action"

add_photo -----------------------------82392211927416 Content-Disposition: form-data; name="image"; filename="about-vimeo.png" Content-Type: image/png

PNG

My jquery

<script>
function _(el){
    return document.getElementById(el);
}
function uploadFile(){
    var checked_box = $('input:checkbox:checked').val();
    var file = _("image").files[0];
    var imageFile =$("#image").val();
//       alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append( 'action','add_photo');
    formdata.append("image", file);
    jQuery.each($("input[name^='image']")[0].files, function(i, file) {
    formdata.append('photo['+i+']', file);
    }); 
//  formdata.append("video", vidName);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "includes/add_photo.inc.php?checked_box="+checked_box);
    ajax.send(formdata);
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}
</script>

The html form

<div id="photos">

    <form enctype="multipart/form-data" name="add_photo"  class="add_photo">
     <?php 
            while($row = mysqli_fetch_array($result4)){ ?>  

      <div class="photoAlbum_list">     

      <div id="#photoAlbumId" class="albumPhoto"><?php echo $row['album_name'];?></div>

      <img src="image/mandinga_folder.png" class="folder"/>

      <input type="checkbox" class="photoAlbumId" id="photoAlbumList" value="<?php echo $row['albumid'];?>"/>

      </div>

      <?php } ?>

    </form>

<div id="addPhotoInstruction" style="display:block">Please choose an Album to Upload Photo's to</div>

<input name="image[]" id="image" type="file" multiple style="display:none" value=""/>

<input onClick="uploadFile()" type="button" id="add_photo_but" class="add_photo_but" name="add_photo_but" value="Add Photo" form="add_photo" style="display:none"/> 

<progress id="progressBar" value="0" max="100" style="display:none"></progress>

<h3 id="status" style="display:none"></h3>

<p id="loaded_n_total" style="display:none"></p>

</div>

Can anyone confirm if this is what would be seen in multiple image upload and if not correct how I can show in the formdata the different file names I expected to see

How to make an accept condition for droppable td to accept only the class within the same row?

I have this droppable td.

$('#ScrumTable td').droppable({
    hoverClass: 'ondrop',
    accept: '.card',
    drop: function(event, ui){
        $(this).append($(ui.draggable));
        ui.draggable.css("top",$(this).css("top"))
        ui.draggable.css("left",$(this).css("left"))
        if(  parseInt( $(this).index() ) + 1 == 1){
            ui.draggable.addClass('backlog-card');
            ui.draggable.removeClass('inprogress-card');
            ui.draggable.removeClass('tovalidate-card');
        }
        else if(  parseInt( $(this).index() ) + 1 == 2){
            ui.draggable.addClass('inprogress-card');
            ui.draggable.removeClass('backlog-card');
            ui.draggable.removeClass('tovalidate-card');
        }
        else if(  parseInt( $(this).index() ) + 1 == 3){
            ui.draggable.addClass('tovalidate-card');
            ui.draggable.removeClass('inprogress-card');
            ui.draggable.removeClass('backlog-card');
        }
    }
});

The droppable td above must only accept the class that is within the same row. What condition can I put to the accept attribute of the droppable td?

Uncaught ReferenceError: RSVP is not defined , error while using require.js with rsvp

I am working on a demo showing the error handling in promises using rsvp.js. Everything seemed fine, till I used the CDN url for rsvp.js in a tag. Now since I have require.js for module loading in my application, I tried loading the rsvp.js module via require js syntax. In the Chrome network tab, I see the rsvp.js module getting loaded properly as well, but I get the below error in console,

Uncaught ReferenceError: RSVP is not defined.

require(["bootstrap","js/rsvp"], function(bootstrap,rsvp) { 
$(document).ready(function () {
    function getEmployeeDetails() {
        var radioValue1 = $("input[name='option1']:checked").val();
        var requrl;
        if (radioValue1 == "fail") {
            requrl = "../../../testservice/getEmployeeIdss";
        } else {
            requrl = "../../../testservice/getEmployeeId";
        }
        return new RSVP.Promise(function (resolve, reject) {
            $.ajax({
                url: requrl,
                success: function (response) {
                    try {
                        $('#successBoard').append("<b> <i> Ajax Call 1 Succeeded! </i>  </b><br/>" + "Employee ID:" + response.stuId + "<br/>");
                        resolve(response.stuId);
                    } catch (e) {
                        reject(e);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log('Ajax 1 failed : Rejecting Promise 1');
                    $('#errorBoard').append("<b> <i> Ajax 1 failed : Rejecting Promise 1</i>  </b><br/>");
                    reject(thrownError);
                }
            });

        });
    }

typeahead doesnt process all bloodhound results

So I'm using typeahead for suggestions while typing. All is working like a charm except for one thing: It only shows results. I'm using a remote search. When i go directly to the page it displays 10 results like expected (query set to max 10 rsults). If i alert data.length from bloodhound it also shows 10 search results. I have checked via alert on the begining and alert on the ending if there was something wrong but all alerts where ok.

Here is my JQ:

var producten = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 100,
    remote: {
        'cache': false,
        url: 'ajax/mysite.php?query=%QUERY',
        wildcard: '%QUERY',
        filter: function (data) {
            //alert(data.length); when alert is active it shows that the length is 10
            return data;
        }
    }
});

producten.initialize();
var i=0 //Have this for the loops to check if all the alerts where coming trough
$('.menuTypeahead').typeahead({
    highlight: true
}, {
    name: 'menuZoek',
    source: producten.ttAdapter(),
    displayKey: 'artikelNaam',
    templates: {
        suggestion: function (producten) {
            i++;
            alert(i+".1"); //begin alert
            var resultaat=''
            if(producten.artikelNaam=='geen suggestie'){
                resultaat='<strong>' + producten.artikelNaam + '</strong>';
            } else {
                if(producten.foto==1){
                    imgLink='img/'+producten.barcode+'.jpg';
                } else {
                    imgLink='css/pics/no_image.jpg';
                }
                if(producten.vers==1){
                    $vers='(vers)';
                } else {
                    $vers='';
                }
                $("#menuSearchLink").val("artikel.php?barcode="+producten.barcode);
                resultaat= '<div>'+
                    '<a href="artikel.php?barcode=' + producten.barcode + '&refer='+temp+'">'+
                        '<div class="search-image">'+
                            '<img src="'+imgLink+'" style="height:50px;width:auto">'+
                        '</div>'+
                        '<div style="min-height:50px;">'+
                        '<strong>' + producten.artikelNaam + ' '+$vers+'</strong>' +
                            '<br>' + producten.inhoud + ' ' + producten.type + ' - ' + producten.artikelMerk + 
                        '</div>'+
                    '</a>'+
                '</div>';
            }
            alert(i+".2"); //end alert
            return resultaat;
        }
    }
});

The JSON i get back is as follows:

[{"ID":"266","barcode":"8711577077020","artikelNaam":"(combi)magnetronreiniger","artikelMerk":"HG","inhoud":"500","type":"ml","foto":"0","vers":"0","voorraadID":null},
{"ID":"329","barcode":"8710400307549","artikelNaam":"3 Laags Tissues","artikelMerk":"Albert Heijn","inhoud":"80","type":"stuks","foto":"0","vers":"0","voorraadID":"188"},
{"ID":"261","barcode":"5000204676150","artikelNaam":"5in1 Laminaatreiniger","artikelMerk":"Pledge","inhoud":"750","type":"ml","foto":"0","vers":"0","voorraadID":null},
{"ID":"14","barcode":"8718452111725","artikelNaam":"8 Goudeerlijk Witte Bollen","artikelMerk":"Jumbo","inhoud":"8","type":"stuks","foto":"0","vers":"0","voorraadID":null},
{"ID":"337","barcode":"8710400504498","artikelNaam":"Aardappelschijfjes Voorgekookt","artikelMerk":"Albert Heijn","inhoud":"450","type":"g","foto":"0","vers":"0","voorraadID":"195"},
{"ID":"72","barcode":"8718449034150","artikelNaam":"Acacia Honing","artikelMerk":"Jumbo","inhoud":"350","type":"g","foto":"0","vers":"0","voorraadID":null},
{"ID":"338","barcode":"5410036501726","artikelNaam":"Allesreiniger ","artikelMerk":"Dettol","inhoud":"1","type":"l","foto":"0","vers":"0","voorraadID":null},
{"ID":"283","barcode":"8710400771753","artikelNaam":"Appelsap uit Geconcentreerd Sap","artikelMerk":"Albert Heijn","inhoud":"1","type":"l","foto":"0","vers":"0","voorraadID":null},
{"ID":"315","barcode":"8718449066762","artikelNaam":"Augurken Fijn","artikelMerk":"Jumbo","inhoud":"340","type":"g","foto":"0","vers":"0","voorraadID":null},
{"ID":"40","barcode":"5410231103404","artikelNaam":"Backin Baking Powder","artikelMerk":"Dr. Oetker","inhoud":"5","type":"stuks","foto":"0","vers":"0","voorraadID":null}]

Also when searching other query's it gives back 5 results only in the dropdown. Hope someone has some clue about what is wrong with it.

How do you .unwrap() an element specified number of levels

Is there a way to use Jquery's .unwrap() multiple times without copying and pasting? It'd be nice if it could accept an argument or something like: .unwrap(4) but it doesn't. Is there a more clever solution to achieving the following:?

$(".foo a").unwrap().unwrap().unwrap().unwrap();
<li class="foo">
    <div>
        <ul>
            <li>
                <div>
                    <a href="#">Link</a>
                </div>
            </li>
        </ul>
    </div>
</li>

Second AJAX call data undefined

I have 2 ajax JSON calls with the second URL being a variable (nextURL) passed from the first.

The second ajax function registers the NextURL variable as tested with an Alert(nextURL) but I do not got any data. Error console states that $('#gameBoxleft').html(data.post.title); data is undefined.

I'm not sure if I have done something wrong with the second ajax call?

// -------------- MAIN AJAX CALL FUNCTION  --------------
function call_ajax(url, elem) {

    $.ajax({
        url: url,
        method: "GET",
        data: {json: 1},
        dataType: "JSON"
    })


    // -------------- FUNCTIONS FOR AFTER AJAX DONE --------------
    .done(function (data) {

        // Append the box
        appendBox(elem);

        // LOAD GAMEBOX JSON DATA

        $("#game-name").html(data.post.title);
        $("#game-reels").html(data.post.custom_fields.reels);
        $("#game-paylines").html(data.post.custom_fields.paylines);
        $("#game-minBet").html(data.post.custom_fields.min_bet);
        $("#game-maxBet").html(data.post.custom_fields.max_bet);
        $("#game-jackpot").html(data.post.custom_fields.jackpot);
        $("#game-info").html(data.post.custom_fields.game_info);


    var nextURL = (data.previous_url) + "?json=1";
            var prevURL = (data.next_url);

          processTwo(nextURL);

    });
}


// -------------- NEXT OBJEXT AJAX CALL FUNCTION  --------------
function processTwo(nextURL) {

alert(nextURL);
            $.ajax({
        url: 'nextURL',
        method: "GET",
        data: {json: 1},
        dataType: "JSON"
    })

            .done(function() {

          $('#gameBoxleft').html(data.post.title);
    });
}

I want to display the text on clicking on the input

Okay so I am trying display the text on focus in the input field all i've done so far is this.

HTML

<form>
                <span id="name">
                Name : <input type="text" class="name" name="name" title="lust"/><br />
                <span>ENTER NAME</span>
                </span>
                <span id="mail">
                E-mail : <input type="text" class="mail" name="mail" /><br />
                <span>ENTER NAME</span>
                </span>
                <input type="submit" class="button" />
            </form>

CSS

#forms {
    position: relative;
}

#name span, #mail span {
    display: none;
}

input[type='text']{
    border: 1px solid #008008;
    border-radius: 5px;
    background: #f1f1f1;
    padding: 10px;
    margin-bottom: 10px;
}

input[type='text']:focus {
    background: #fff;
    border: 1px solid #008080;
}

.assistant {
    position: abosolute;
    top: 0px;
}

Can anyone help me achieve this am I doing wrong or I am in correct path? I will be greatful if someone actually help me out.

Flexslider in Drupal 7 breaks JQuery

I've been working with Flexslider in Drupal 7, but when I try to create a page with a slider, the JQuery on the entire page stops working.

flexslider.load.js?no0zdc:41 
Uncaught TypeError: $(...).flexslider is not a function

That's the error message that I receive. I've already uploaded the javascript library files provided by WooThemes and I've checked to make sure that they have been uploaded to the correct folder (/sites/all/libraries/flexslider/).

I'm a bit stuck. My best guess is that there is a conflict in the way JQuery is being called on the page since JQuery works on every other page, so for reference, I have posted some code from my header below:

<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script><style type="text/css"></style>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
window.jQuery || document.write("<script src='/sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js'>\x3C/script>")
//--><!]]>
</script>
<script type="text/javascript" src="/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="/misc/drupal.js?no0zdc"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
window.jQuery.ui || document.write("<script src='/sites/all/modules/jquery_update/replace/ui/ui/minified/jquery-ui.min.js'>\x3C/script>")
//--><!]]>
</script>

I hope I've provided sufficient information. Any help would be greatly appreciated.

EDIT

Full header below:

<head profile="http://ift.tt/SX2Z8m">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="Sample content" about="/sample-content" property="dc:title">
<link rel="shortcut icon" href="/misc/favicon.ico" type="image/vnd.microsoft.icon">
<meta name="HandheldFriendly" content="true">
<meta name="MobileOptimized" content="width">
<meta name="Generator" content="Drupal 7 (http://drupal.org)">
<link rel="canonical" href="/sample-content">
<link rel="shortlink" href="/node/114">
  <title>Sample content | ILIAS Solutions</title>
  <link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_IoEPASs8P-5r05g2SNWObjq4Z3L1qnpf6AUHzJOv_Mw.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css__OGyo-ZLPb2eWR69kov4bKl5fA7ngglWR1B1kbenDy4.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_MnXiytJtb186Ydycnpwpw34cuUsHaKc80ey5LiQXhSY.css" media="all">
<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" media="all">
<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_9vS7KTziVXM6cOtv0jZFlm30ZZXGCzz9d4oZYdJnbf4.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_X2KZyy7-i2nDSO3slgqaJQDJe_rcOgl-_DFA2q0nlLI.css" media="all">
<link type="text/css" rel="stylesheet" href="/sites/all/themes/startupgrowth_lite/fonts/lato-font.css?no15n3" media="all">
<link type="text/css" rel="stylesheet" href="/sites/all/themes/startupgrowth_lite/fonts/sourcecodepro-font.css?no15n3" media="all">
<link type="text/css" rel="stylesheet" href="/sites/all/themes/startupgrowth_lite/fonts/ptserif-blockquote-font.css?no15n3" media="all">

<!--[if (IE 9)&(!IEMobile)]>
<link type="text/css" rel="stylesheet" href="/sites/all/themes/startupgrowth_lite/ie9.css?no15n3" media="all" />
<![endif]-->
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs.css" media="all">

  <!-- HTML5 element support for IE6-8 -->
  <!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <script type="text/javascript" src="/sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js?v=1.10.2"></script><style type="text/css"></style>
<script type="text/javascript" src="/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="/misc/drupal.js?no15n3"></script>
<script type="text/javascript" src="/sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js?v=1.10.2"></script>
<script type="text/javascript" src="/sites/all/modules/jquery_update/replace/misc/1.9/jquery.ba-bbq.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/sites/all/modules/jquery_update/replace/misc/1.9/overlay-parent.js?v=1.0"></script>
<script type="text/javascript" src="/sites/all/modules/admin_menu/admin_menu.js?no15n3"></script>
<script type="text/javascript" src="/sites/all/modules/admin_menu/admin_menu_toolbar/admin_menu_toolbar.js?no15n3"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) { 
        $(window).scroll(function() {
            if($(this).scrollTop() != 0) {
                $("#toTop").addClass("show");   
            } else {
                $("#toTop").removeClass("show");
            }
        });

        $("#toTop").click(function() {
            $("body,html").animate({scrollTop:0},800);
        }); 

        });
//--><!]]>
</script>
<script type="text/javascript" src="/sites/all/themes/startupgrowth_lite/js/jquery.mobilemenu.js?no15n3"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) { 

        $("#main-navigation ul.main-menu, #main-navigation .content>ul.menu").mobileMenu({
            prependTo: "#main-navigation",
            combine: false,
            nested: 1,
            switchWidth: 760,
            topOptionText: Drupal.settings.startupgrowth_lite['topoptiontext']
        });

        });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) { 

        var map;
        var myLatlng;
        var myZoom;
        var marker;

        });
//--><!]]>
</script>
<script type="text/javascript" src="http://ift.tt/Ylci2T"></script><script src="http://ift.tt/1dSfelX"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) { 

        if ($("#map-canvas").length) {

            myLatlng = new google.maps.LatLng(Drupal.settings.startupgrowth['google_map_latitude'], Drupal.settings.startupgrowth['google_map_longitude']);
            myZoom = 13;

            function initialize() {

                var mapOptions = {
                zoom: myZoom,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: myLatlng,
                scrollwheel: false
                };

                map = new google.maps.Map(document.getElementById(Drupal.settings.startupgrowth['google_map_canvas']),mapOptions);

                marker = new google.maps.Marker({
                map:map,
                draggable:true,
                position: myLatlng,
                url: "http://ift.tt/1EnM2IT"
                });

                google.maps.event.addListener(marker, "click", function() {     
                window.open(this.url, "_blank");
                });

                google.maps.event.addDomListener(window, "resize", function() {
                map.setCenter(myLatlng);
                });

            }

            google.maps.event.addDomListener(window, "load", initialize);

        }

        });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) { 

            var headerHeight = $("#header").height();
            $(window).scroll(function() {
            if(($(this).scrollTop() > headerHeight) && ($(window).width() > 767)) {
                $("body").addClass("onscroll"); 
                $("body").css("paddingTop", (headerHeight)+"px");
                if( $(this).scrollTop() > headerHeight+40 ) {
                $("body").addClass("show"); 
                }
            } else {
                $("body").removeClass("onscroll");
                $("body").removeClass("show");
                $("body").css("paddingTop", (0)+"px");
                $("body.logged-in").css("paddingTop", (64)+"px");
            }
            });
        });
//--><!]]>
</script>
<script type="text/javascript" src="/sites/all/themes/startupgrowth_lite/js/meanmenu/jquery.meanmenu.min.js?no15n3"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) {

            $("#main-navigation .sf-menu, #main-navigation .content>ul.menu, #main-navigation ul.main-menu").wrap("<div class='meanmenu-wrapper'></div>");
            $("#main-navigation .meanmenu-wrapper").meanmenu({
                meanScreenWidth: "767",
                meanRemoveAttrs: true,
                meanMenuContainer: "#header-inside",
                meanMenuClose: ""
            });

        });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function($) {

            $(window).load(function() {
                $("#highlighted-bottom-transparent-bg").css("backgroundColor", "rgba(255,255,255,0.8)");
            });

        });
//--><!]]>
</script>
<script type="text/javascript" src="/sites/all/themes/startupgrowth_lite/js/jquery.browser.min.js?no15n3"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, {"basePath":"\u002F", "pathPrefix":"", "ajaxPageState":{"theme":"startupgrowth_lite", "theme_token":"Cv8zpIqC1NrJFXXv3ef0_APXlwgYfd8ijffT8WgyKoc", "js":{"sites\u002Fall\u002Fmodules\u002Fflexslider\u002Fassets\u002Fjs\u002Fflexslider.load.js":1, "sites\u002Fall\u002Fmodules\u002Fjquery_update\u002Freplace\u002Fjquery\u002F1.10\u002Fjquery.min.js":1, "misc\u002Fjquery.once.js":1, "misc\u002Fdrupal.js":1, "sites\u002Fall\u002Fmodules\u002Fjquery_update\u002Freplace\u002Fui\u002Fui\u002Fminified\u002Fjquery.ui.core.min.js":1, "sites\u002Fall\u002Fmodules\u002Fjquery_update\u002Freplace\u002Fmisc\u002F1.9\u002Fjquery.ba-bbq.min.js":1, "sites\u002Fall\u002Fmodules\u002Fjquery_update\u002Freplace\u002Fmisc\u002F1.9\u002Foverlay-parent.js":1, "sites\u002Fall\u002Fmodules\u002Fadmin_menu\u002Fadmin_menu.js":1, "sites\u002Fall\u002Fmodules\u002Fadmin_menu\u002Fadmin_menu_toolbar\u002Fadmin_menu_toolbar.js":1, "\u002F\u002Fmaxcdn.bootstrapcdn.com\u002Fbootstrap\u002F3.3.2\u002Fjs\u002Fbootstrap.min.js":1, "0":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fjs\u002Fjquery.mobilemenu.js":1, "1":1, "2":1, "https:\u002F\u002Fmaps.googleapis.com\u002Fmaps\u002Fapi\u002Fjs?v=3.exp\u0026sensor=false":1, "3":1, "4":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fjs\u002Fmeanmenu\u002Fjquery.meanmenu.min.js":1, "5":1, "6":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fjs\u002Fjquery.browser.min.js":1}, "css":{"modules\u002Fsystem\u002Fsystem.base.css":1, "modules\u002Fsystem\u002Fsystem.menus.css":1, "modules\u002Fsystem\u002Fsystem.messages.css":1, "modules\u002Fsystem\u002Fsystem.theme.css":1, "misc\u002Fui\u002Fjquery.ui.core.css":1, "misc\u002Fui\u002Fjquery.ui.theme.css":1, "modules\u002Foverlay\u002Foverlay-parent.css":1, "modules\u002Ffield\u002Ftheme\u002Ffield.css":1, "modules\u002Fnode\u002Fnode.css":1, "modules\u002Fsearch\u002Fsearch.css":1, "modules\u002Fuser\u002Fuser.css":1, "sites\u002Fall\u002Fmodules\u002Fviews\u002Fcss\u002Fviews.css":1, "sites\u002Fall\u002Fmodules\u002Fadmin_menu\u002Fadmin_menu.css":1, "sites\u002Fall\u002Fmodules\u002Fadmin_menu\u002Fadmin_menu_toolbar\u002Fadmin_menu_toolbar.css":1, "modules\u002Fshortcut\u002Fshortcut.css":1, "sites\u002Fall\u002Fmodules\u002Fctools\u002Fcss\u002Fctools.css":1, "\u002F\u002Fmaxcdn.bootstrapcdn.com\u002Ffont-awesome\u002F4.2.0\u002Fcss\u002Ffont-awesome.min.css":1, "\u002F\u002Fmaxcdn.bootstrapcdn.com\u002Fbootstrap\u002F3.3.2\u002Fcss\u002Fbootstrap.min.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fjs\u002Fmeanmenu\u002Fmeanmenu.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fstyle.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Ffonts\u002Flato-font.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Ffonts\u002Fsourcecodepro-font.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Ffonts\u002Fptserif-blockquote-font.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Fie9.css":1, "sites\u002Fall\u002Fthemes\u002Fstartupgrowth_lite\u002Flocal.css":1}}, "overlay":{"paths":{"admin":"node\u002F*\u002Fedit\u000Anode\u002F*\u002Fdelete\u000Anode\u002F*\u002Frevisions\u000Anode\u002F*\u002Frevisions\u002F*\u002Frevert\u000Anode\u002F*\u002Frevisions\u002F*\u002Fdelete\u000Anode\u002Fadd\u000Anode\u002Fadd\u002F*\u000Aoverlay\u002Fdismiss-message\u000Auser\u002F*\u002Fshortcuts\u000Aadmin\u000Aadmin\u002F*\u000Abatch\u000Ataxonomy\u002Fterm\u002F*\u002Fedit\u000Auser\u002F*\u002Fcancel\u000Auser\u002F*\u002Fedit\u000Auser\u002F*\u002Fedit\u002F*", "non_admin":"admin\u002Fstructure\u002Fblock\u002Fdemo\u002F*\u000Aadmin\u002Freports\u002Fstatus\u002Fphp"}, "pathPrefixes":[  ], "ajaxCallback":"overlay-ajax"}, "flexslider":{"optionsets":{"flexslider_default_thumbnail_slider":{"namespace":"flex-", "selector":".slides \u003E li", "easing":"swing", "direction":"horizontal", "reverse":false, "smoothHeight":true, "startAt":0, "animationSpeed":600, "initDelay":0, "useCSS":true, "touch":true, "video":false, "keyboard":true, "multipleKeyboard":false, "mousewheel":0, "controlsContainer":".flex-control-nav-container", "sync":"", "asNavFor":"#flexslider-1", "itemWidth":210, "itemMargin":5, "minItems":0, "maxItems":0, "move":0, "animation":"slide", "slideshow":false, "slideshowSpeed":"7000", "directionNav":true, "controlNav":false, "prevText":"Previous", "nextText":"Next", "pausePlay":false, "pauseText":"Pause", "playText":"Play", "randomize":false, "animationLoop":false, "pauseOnAction":true, "pauseOnHover":false, "manualControls":""}}, "instances":{"flexslider-1":"flexslider_default_thumbnail_slider"}}, "startupgrowth_lite":{"topoptiontext":"Select a page", "google_map_latitude":"40.726576", "google_map_longitude":"-74.046822", "google_map_canvas":"map-canvas"}, "admin_menu":{"destination":"destination=node\u002F114", "hash":"37d586808ca3270fdd2a560149caab90", "basePath":"\u002Fadmin_menu", "replacements":{".admin-menu-users a":"0 \u002F 1"}, "margin_top":1, "toolbar":[  ]}});
//--><!]]>
</script>
<script type="text/javascript" charset="UTF-8" src="http://ift.tt/1dSfelZ"></script><script type="text/javascript" charset="UTF-8" src="http://ift.tt/1dSfem1"></script><script type="text/javascript" charset="UTF-8" src="http://ift.tt/1EnM0kj"></script></head>