How to retrieve entity name by object type code using JavaScript in CRM?

Is there anyway on client side in Dynamics CRM 2011 from JavaScript to retrieve Entity Logical Name by Object Type Code?

Example: Object Type Code = 1, Logical Name is Account


effect of instance type on Method invocation from derived class

Suppose I have the following:

static void Main(string[] args)
{
    DerivedClass input = new DerivedClass();
    input.WriteName(); // Outputs BaseClass
}

class BaseClass
{
    public void WriteName()
    {
        Console.WriteLine(GetName());//this.GetType()
    }

    protected string GetName()
    {
        return "BaseClass";
    }
}

class DerivedClass : BaseClass
{
    protected new string GetName()
    {
        return "DerivedClass";
    }
}

I ran some tests(using GetType()) about the object type from which GetName() Method is invoked (I mean DerivedClass.GetName from WriteName). I know that WriteName cannot see the new Method in DerivedClass class and GetName Method is hidden by new keyword, but does the instance type (DerivedClass) not have any effect on that?
is the type up-casted to base class when calling GetName Method? when calling from Main Method DerivedClass.GetName seems to provide the expected result.


Grunt Task "default" not found

I'm new to use grunt, I just create a real sample to run. But I get blocked my A warning Warning: Task "default" not found

I just copied sample from http://gruntjs.com/getting-started

My package is

{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-uglify": "~0.5.0"
  }
}

my Gruntfile.js is

module.exports = function(grunt) {

    grunt.registerTask('default', 'Log some stuff.', function() {
        grunt.log.write('Logging some stuff...').ok();
    });

};

it just print some simple log, why it doesn't work?


Install PDO_OCI on PHP7

He,

I try since several days to install PDO_OCI on PHP7 on a new server.
I have ever on other server PDO_OCI but on PHP 5.4, and all is good, not problem with this version.

I have the message :

:/home/pear/download/PDO_OCI-1.0# make
/bin/bash /home/pear/download/PDO_OCI-1.0/libtool --mode=compile cc -I -I.
-I/home/pear/download/PDO_OCI-1.0 -DPHP_ATOM_INC
-I/home/pear/download/PDO_OCI-1.0/include
-I/home/pear/download/PDO_OCI-1.0/main
-I/home/pear/download/PDO_OCI-1.0
-I/usr/include/php/20151012
-I/usr/include/php/20151012/main
-I/usr/include/php/20151012/TSRM
-I/usr/include/php/20151012/Zend
-I/usr/include/php/20151012/ext
-I/usr/include/php/20151012/ext/date/lib
-I/usr/lib/oracle/instantclient/include/oracle/12.1/client  -DHAVE_CONFIG_H  -g -O2   -c
/home/pear/download/PDO_OCI-1.0/oci_driver.c -o oci_driver.lo
libtool: compile:  cc -I -I.
-I/home/pear/download/PDO_OCI-1.0 -DPHP_ATOM_INC
-I/home/pear/download/PDO_OCI-1.0/include
-I/home/pear/download/PDO_OCI-1.0/main
-I/home/pear/download/PDO_OCI-1.0
-I/usr/include/php/20151012
-I/usr/include/php/20151012/main
-I/usr/include/php/20151012/TSRM
-I/usr/include/php/20151012/Zend
-I/usr/include/php/20151012/ext
-I/usr/include/php/20151012/ext/date/lib
-I/usr/lib/oracle/instantclient/include/oracle/12.1/client -DHAVE_CONFIG_H -g -O2 -c
/home/pear/download/PDO_OCI-1.0/oci_driver.c  -fPIC -DPIC -o .libs/oci_driver.o

/home/pear/download/PDO_OCI-1.0/oci_driver.c: In function 'pdo_oci_fetch_error_func':
/home/pear/download/PDO_OCI-1.0/oci_driver.c:51:3: error:
too many arguments to function 'add_next_index_string' add_next_index_string(info, einfo->errmsg, 1);

In file included from /usr/include/php/20151012/main/php.h:39:0,
                 from /home/pear/download/PDO_OCI-1.0/oci_driver.c:25:
/usr/include/php/20151012/Zend/zend_API.h:432:14: note: declared here
 ZEND_API int add_next_index_string(zval *arg, const char *str);
              ^
/home/pear/download/PDO_OCI-1.0/oci_driver.c: In function 'oci_handle_preparer':
/home/pear/download/PDO_OCI-1.0/oci_driver.c:238:59: warning: passing argument 5 of 'pdo_parse_params' from incompatible pointer type
  ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);
                                                       ^
In file included from /home/pear/download/PDO_OCI-1.0/oci_driver.c:29:0:
/usr/include/php/20151012/ext/pdo/php_pdo_driver.h:678:13: note: expected 'size_t *' but argument is of type 'int *'
 PDO_API int pdo_parse_params(pdo_stmt_t *stmt, char *inquery, size_t inquery_len,
         ^
/home/pear/download/PDO_OCI-1.0/oci_driver.c: At top level:
/home/pear/download/PDO_OCI-1.0/oci_driver.c:411:2: warning: initialization from incompatible pointer type
  oci_handle_preparer,
 ^
/home/pear/download/PDO_OCI-1.0/oci_driver.c:411:2: warning: (near initialization for 'oci_methods.preparer')
/home/pear/download/PDO_OCI-1.0/oci_driver.c:412:2: warning: initialization from incompatible pointer type
  oci_handle_doer,
  ^
/home/pear/download/PDO_OCI-1.0/oci_driver.c:412:2: warning: (near initialization for 'oci_methods.doer')
/home/pear/download/PDO_OCI-1.0/oci_driver.c:413:2: warning: initialization from incompatible pointer type
  oci_handle_quoter,
  ^
/home/pear/download/PDO_OCI-1.0/oci_driver.c:413:2: warning: (near initialization for 'oci_methods.quoter')
Makefile:198: recipe for target 'oci_driver.lo' failed
make: *** [oci_driver.lo] Error 1

My configuration :
Linux server System     Linux 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt20-1+deb8u4 (2016-02-29) x86_64
PHP PHP Version 7.0.4-1~dotdeb+8.1
PDO drivers     mysql
OCI8 Support    enabled (is work).

I have read PDO_OCI is include on PHP7 https://github.com/php/php-src/tree/PHP-7.0.7/ext/pdo_oci
but how activate it ?

My code to PHP 5.4 doesn't work on this server PHP7.

Somebody have a solution ?

Regards


Sync Vue.js data with some existing html?

I am using Vue.js clientside, and populate a list as follows (this works after an ajax/json api request which I populate with Vue data and methods).

<div id="myDiv1">
  <li v-for="item in items">
    {{ item.title }}
  </li>
</div>

I currently intialise Vue with

var vueApp = new Vue({
...
  data: {
    items: {},
  },
  methods: { ajaxCallAndUpdateVueItems: function(){...}
  }
})

ajaxCallAndUpdateVueItems() on some event

However, I would like to preload/render on the server side an initial state of the list (for a few reasons like speed, seo, initialstate first time only). This state varies depending on things like location of the user, which the server calculates.

So I want to send the initial page to the client with

<div id="myDiv1">
  <li>Some title1</li>
  <li>Some title2</li>
</div>

Is there any way to somehow initialise the Vue data with the content of myDiv1 for example, so I don't have 2 sets of html I somehow mess with (e.g deleting the initial html block and repopulating via Vue) ?


Javascript "not a function" error, on an already defined function

I was just playing around with DFS in node, and suddenly got this error.

TypeError: sNode.hasNeighbors is not a function
    at recursiveDFS (/home/***/Graphs/dfs2.js:53:27)
    at /home/***/Graphs/dfs2.js:56:17
    at Array.forEach (<anonymous>)
    at recursiveDFS (/home/***/Graphs/dfs2.js:54:30)
    at Object.<anonymous> (/home/***Graphs/dfs2.js:62:1)

Here is the code.
If I reference the function it says "is not a function"
When I reference the function as a property it says "it's a function"

function Node(vert) {
    this.visited = false;
    this.vertex = vert;
    let neighbors = [];

    this.addNeighbors = function(node_str) {
        if (node_str.length == 1) {
            neighbors.push(parseInt(node_str));
        } else {
            nodes = node_str.split(" ");
            for (var i = 0; i < nodes.length; i++) {
                neighbors.push(parseInt(nodes[nodes[i]]));
            }
        }
    };

    this.hasNeighbors = function() {
        return neighbors.length > 0;
    };

    this.getNeighbors = function() {
        return neighbors;
    };
}

let node = [];
node[0] = new Node(0);
node[1] = new Node(1);
node[2] = new Node(2);
node[3] = new Node(3);
node[4] = new Node(4);
node[5] = new Node(5);
node[6] = new Node(6);
node[7] = new Node(7);
node[8] = new Node(8);
node[9] = new Node(9);

node[0].addNeighbors("1");

node[1].addNeighbors("0 1");

node[2].addNeighbors("1 3");

node[3].addNeighbors("2 4 5");

node[4].addNeighbors("3 5 6");

function recursiveDFS(sNode) {
    if (!sNode.visited) {
        sNode.visited = true;
        //console.log(sNode.hasNeighbors());
        sNode.getNeighbors().forEach(function(neighbor) {
            if (!neighbor.visited) {
                recursiveDFS(neighbor);
            }
        }, this);
    }
}

recursiveDFS(node[0]);

Outside the recursiveDFS function everything works completely fine.


Store ByteArrayOutputStream in SD Card

I am getting a ByteArrayOutputStream of Camera and want to Store this video stream into SD Card as a file, file extension would be anything.

How can I fetch streaming and store it into SD Card,as I am getting a live camera stream and want to update that continously in SD Card.

Could you please provide me a sample tutorials related to camera streaming.

Thanks.


Spring Data Solr - Exception in mapping a custom repository

I am trying to use faceted search with a custom repository as follows:

Repository:

public interface POISearchRepository extends CustomSolrRepository, SolrCrudRepository<POISearch, String>

Custom interface:

public interface CustomSolrRepository {

     FacetPage<POISearch> facetSearch(String location, String categories, String duration, Pageable page) throws Exception;
}

Custom impl:

@Repository
public class POISearchImpl implements CustomSolrRepository {

@Resource
private SolrTemplate solrTemplate;

@Override
public FacetPage<POISearch> facetSearch(String location, String categories, String duration, Pageable page) throws Exception {

......
}

Unfortunately, I keep getting the following exception:

Caused by:
  org.springframework.data.mapping.PropertyReferenceException: No
  property facet found for type com.example.domain.POISearch at
  org.springframework.data.mapping.PropertyPath.(PropertyPath.java:75)
  at
  org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
  at
  org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:353)
  at
  org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
  at
  org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:271)
  at
  org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:245)
  at
  org.springframework.data.repository.query.parser.Part.(Part.java:72)
  at
  org.springframework.data.repository.query.parser.PartTree$OrPart.(PartTree.java:180)
  at
  org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:260)
  at
  org.springframework.data.repository.query.parser.PartTree$Predicate.(PartTree.java:240)
  at
  org.springframework.data.repository.query.parser.PartTree.(PartTree.java:68)
  at
  org.springframework.data.solr.repository.query.PartTreeSolrQuery.(PartTreeSolrQuery.java:36)
  at
  org.springframework.data.solr.repository.support.SolrRepositoryFactory$SolrQueryLookupStrategy.resolveQuery(SolrRepositoryFactory.java:101)
  at
  org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.(RepositoryFactorySupport.java:279)
  at
  org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:147)
  at
  org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:153)
  at
  org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:43)
  at
  org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
  ... 57 more

It seems like the repository tries to resolve the custom method and that causes the exception (changing the method names shows that)


Full width nav bar for my website

I need some help. I have a website and I want to make some changes, but I don't know how. I read other questions here, but they didn't help. This is my website: http://www.bijuterii-din-inox.ro.

I want my nav bar to be the full width of the page. Can you please give me a hand!?  Thanks.

This is my css:

#top_nav {
    padding: 0 2px;
}

#top_nav ul {
    display: block;
    height: 43px;
}

#top_nav ul li i,
#top_nav ul li b {
    display: none;
    float: none;
    width: auto;
    height: auto;
}

#top_nav ul li a {
    float: left;
    height: 43px;
    line-height: 43px;
    padding: 0 20px;
    font-weight: 700;
}

#top_nav ul li.first a {
    padding-left: 20px;
}

#top_nav ul li.last,
#top_nav ul li.single {
    background: none;
}

#top_nav ul li.single a {
    padding-left: 0;
    padding-top: 2px;
}


How can I know request destination?

I created a webpage by classic asp. A date was displayed in this page. But I want to display it with request country dateformat. So, I need to know which request came from? How can I know it? Thanks.


How to Group Data between DateTime using Linq

My student class is

class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public DateTime Admission{get; set;}
}

I want to group the data between datetime where Admission must between Today 7 am to next morning 7 am , for example :- 11/4/2014 7:0:0 and 11/5/2014 7:0:0 all data between these datetime's must be in a single group

Currently i am doing it like this

var groupByAdmsn = listOfStudent.
GroupBy(x => x.Admission < new DateTime(x.Admission.Year, x.Admission.Month, x.Admission.Day, 7, 0, 0).AddDays(1) &&
 x.Admission >= new DateTime(x.Admission.Year, x.Admission.Month, x.Admission.Day, 7, 0, 0))
.Select(x => x)
.ToList();

but it is not working.


How to plot random x-values in gnuplot

I have a data set with two columns, (x,y) which looks like:

4 16
1 1
5 25
3 9
7 49
0 0
2 4

Now I want to plot this in gnuplot u 1:2 in the order in which column 1 is arranged. Basically on x-axis, gnuplot should have first 4, then 1, then 5 and so on. Is it possible with gnuplot or any other plotting tool?


memory allocation in custom initialization

Ran allocation profiler on my code. Found following problem on the inserted code. Could someone please point me what is wrong in the code. Added the picture so as too show the color coding.

Code for initializing the point is as below:

@autoreleasepool {

if(!coordString){
    return nil;
}
if([coordString length]<3){
    return nil;
}

__weak NSArray* coords=[coordString componentsSeparatedByString:@","];
    if(nil != coords && ([coords count]==2)){
    self = [super init];
    if(nil != self){
        self.coordX=  [[coords objectAtIndex:0] doubleValue];
        self.coordY = [[coords objectAtIndex:1] doubleValue];

        return self;
    }else {
        return nil;
    }

    }else{

        return nil;
    }
}

Please suggest where the problem might be.
Allocation snapshot indicates the persistance memory.


What is the difference between X509Certificate2 and X509Certificate in .NET?

What is the difference between the two?


aligning text fields in css html form

I'm trying to make a website form look like this where the
right side of text fields are aligned

When I change the size of the screen, the text fields are no longer in alignment. How can I keep them aligned regardless of screen size?

Here is my code:

<head>

  <META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">
    <title>Coat Request Form</title>

    </head>

  <body>

    <form target="_top" action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">

      <p>
        <input type=hidden name="oid" value="00Di0000000gO95">
        <input type=hidden name="retURL" value="http://www.empowermentplan.org/#!thank-you/jiwpq">

        <span style="display:inline-block" margin-right="30px">
          <label class="required" for="first_name" style="display:block">First Name</label>
          <input id="first_name" maxlength="40" name="first_name" size="20" type="text" required /><br>
        </span>

        <span style="display:inline-block">
          <label class="required" for="last_name" style="display:block">Last Name</label>
          <input id="last_name" maxlength="80" name="last_name" size="20" type="text" required /><br>
        </span>
        <br>
        <span style="display:inline-block">
          <label class="required" for="email" style="display:block" >Email</label>
          <input id="email" maxlength="80" name="email" size="20" type="text" required/><br>
        </span>

        <span style="display:inline-block">
          <label for="phone" style="display:block" >Phone</label>
          <input  id="phone" maxlength="40" name="phone" size="20" type="text" /><br>
        </span>

        <br>

        <span style="display:inline-block">
          <label for="company" style="display:block">Company (optional)</label>
          <input id="company" maxlength="40" name="company" size="20" type="text" /><br>
        </span>

        <span style="display:inline-block">

          <label style="display:block">How many coats?</label>
          <input  id="00Ni000000H0CxE" name="00Ni000000H0CxE" size="20" type="text" /><br>

        </span>

        <label style="display:block">Who are the coats for?</label>
        <textarea  id="00Ni000000H0Cy2" name="00Ni000000H0Cy2" rows="3" type="text" wrap="soft"></textarea><br>
        <input type="submit" name="submit" class="btn">

        <select style="visibility:hidden" id="00Ni000000H0Cxx" name="00Ni000000H0Cxx" title="Topic">
          <option type="hidden" value="Coats">Coats</option> </select><br>
      </p>
    </form>
  </body>


Open files limit server can support

I am continuously getting Socket connection problem (too many open files) in tomcats catalina.out. When I do

ulimit -n

I get 1024. Is there a way I can find whats the maximum number of open files the server can support before increasing the limit. I don't want to arbitrarily increase the limit to a value the server cant support. I am searching, I can find how to increase it but cant find how to figure out server limitations.

cat /proc/version

Linux version 2.6.32-431.5.1.el6.x86_64 (mockbuild@c6b10.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Wed Feb 12 00:41:43 UTC 2014

cat /etc/redhat-release

CentOS release 6.5 (Final)

As pointed out by my friend in the answer below.

cat /proc/sys/fs/file-max

I want to know this limit (maximum number of open files) the system supports. So I can set it.


How to bind DBnull values to grid view?

I am facing struggle to bind values to grid which are retrieved from data base.  I have a database column of type DateTime which is nullable. So, when I am trying to bind that null value, it is throwing an error while adding those column value to object property . So, before adding values fetched from database, i am using a function that converts the value to its default type before adding to object. Since , the default value for datetime Type is 1/1/0001 12:00:00 AM . So, where ever null values are present , I am getting this value for this field.

How to solve this issue? Please give your sugesstions.

To explain my scenario , i am adding a piece of code here.

public static T GetValue<T>(object o)
{
    T val = default(T);

    if (o != null && o != DBNull.Value)
    {
        val = (T)o;
    }
    return val;
}

This is the helper function I am using while reading data from the data reader.


http rest: Disadvantages of using json in query string?

I want to use query string as json, for example: /api/uri?{"key":"value"}, instead of /api/uri?key=value. Advantages, from my point of view, are:

json keep types of parameters, such are booleans, ints, floats and strings. Standard query string treats all parameters as strings.

json has less symbols for deep nested structures, For example, ?{"a":{"b":{"c":[1,2,3]}}} vs ?a[b][c][]=1&a[b][c][]=2&a[b][c][]=3

Easier to build on client side

What disadvantages could be in that case of json usage?


C# novice in need

Below is the code to our cs.aspx recall page.  The idea is that we scan a barcode and it references the code to see of a UPC is on the recall list.  If it is, the "STOP SIGN" is supposed to show, if it is not on the list, the "GREEN Light" is supposed to show.  The problem with the code below is that after the "GREEN LIGHT" icon is called, it requires a manual enter on the keyboard for the next barcode scan to work properly.

Here is what the results are:

Scan Barcode  12345

Green light icon shows

Scan Barcode 54321

Green light icon goes away  (this is where I need the Green Light to show again or stay)

I am lost. Here is the code  (we use Chrome or Firefox browser to call the cs.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<!DOCTYPE html>
<html lang="en">
<head id="Head1">
    <meta charset="utf-8" />

    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
     </script>
    <script>
        $(document).ready(function () {
            $('#txtUPC').focus();

            $("input").keyup(function (event) {

                var strUPC = $(this).val();

                if (strUPC == "000035" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:000035  Product: Test Scan";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }

                 if (strUPC == "037600245289" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:037600245289  Product: Hormel Chili Hot No Beans";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }

                if (strUPC == "013409128442" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:013409128442  Product: Sweet Baby Ray's Baffolo Wing Sauce";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }

                if (strUPC == "041130311222" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:041130311222  Product: Shoppers Value Pinto Beans";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }

                if (strUPC == "041800501267" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:041800501267  Product: Welch's Grape";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }

                if (strUPC == "041130311208" ) {
                    $("#stop_dialog").show();
                    var lblStopText = "Recalled Product: UPC:041130311208  Product: Shoppers Value Dark Red Kidney Beans";
                    $('#lblStop').val(lblStopText);
                    $("#check_green").hide();
                     setTimeout(function () {
                     $("input").prop('disabled', true);}, 800);

                    return;
                }
                $("#check_green").toggle();

                   enterUPC(strUPC);

                 $('#txtUPC').focus();

                $('#Reset').click();

            });

            $('#Reset').click(function () {

                setTimeout(function () {

                    document.getElementById('txtUPC').focus();
                }, 800);

                setTimeout(function () {

                    document.getElementById('txtUPC').value = "";
                }, 800);

            });

            function doreset() {
                $('#txtUPC').val("");
                $('#txtUPC').focus();

            }

            function enterUPC(strUPC) {

                $('#lblUPC').val(strUPC);

                var dNow = new Date();
                var localdate = (dNow.getMonth() + 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes() + ':' + dNow.getSeconds();

                $('#lbltimestamp').val(localdate);

                setTimeout(function () {

                    $('#Go').click();
                }, 200);

            }

            $('#Go').click(function () {
                var code = {};
                code.UPC = $("[id*=lblUPC]").val();
                code.strDate = $("[id*=lbltimestamp]").val();
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/SaveUPC",
                    data: '{code: ' + JSON.stringify(code) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",

                });
                return false;
            });

        });

</script>

</head>
<body>

Enter UPC: <input type="text" ID="txtUPC"/>
    <br />  <input type="text" id="lblUPC" runat="server" readonly="readonly" style="border: 0px; background-color: transparent;" size="100" />
    <br />
<input type="text" id="lbltimestamp" runat="server" readonly="readonly" style="border: 0px; background-color: transparent;" size="100" />

 <input type="button" id="Go" value=""/>
 <input type="button" id="Reset" value="Reset"/>
  <br />
<div id="check_green" style="display: none">

 <br /> <img src="Green.png" alt="Good" />
  <br />
</div>

  <div id="stop_dialog" style="display: none">

  <input type="text" id="lblStop" runat="server" readonly="readonly" style="border: 0px; background-color: transparent;" size="100" />
<br />
  <img src="Stop.png" alt="Stop" />

</div>

    <form id="form1" runat="server">

    <br />
   </form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>

</body>
</html>

(I am not sure what I am doing)


Capybara: How to hit the first button in rspec?

Here is the html source code for 2 Save buttons in Rails 4 spec. The program should click the first Save:

<div class="btn-toolbar">
 <a class="btn btn-primary" href="/view_handler?index=0">
  <span class="translation_missing" title="translation missing: en.Back">Back</span>
 </a>
 <input class="btn btn-default btn btn-primary" name="commit" value="Save" type="submit">
 <input class="btn btn-default btn btn-primary" name="commit" value="Save & New" and_new="true" type="submit">
</div>`

Here is the code I tried:

first('input.btn.btn-default').click_button 'Save'

The error returned is:

Capybara::ElementNotFound:
             Unable to find button "Save"

What's the right way to click button Save in spec?


C# Creating admin shortcut

I found this article but it does not contain support for run as admin..

Well i need to create a shortcut to notepad to edit a xml file, but i need notepad to run as administrator, how would i go about to do that?


FullCalendar adding data-date at tbody td on the div with a class of fc-content-skeleton

Can I add date-add at the tbody td of the div with class fc-content-skeleton table? coz only the thead td has a data-date, can we data-date at it also?


Error with popover and UIAlertController

I have an app with a popover.  As I'm coming out of the popover.  I am dismissing the popover via a UIAlertController (user answers Yes).  Before dismissing the popover, though, I am calling a function on the delegate.  Within that function is another UIAlertController.  The second UIAlertController is not displaying because of the following error:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior.

To demo this here, I created a quick project that shows the problem.  It is just a view controller with a button that calls the popover and a button on the popover that closes it and calls a delegate function containing another UIAlertController.

This is the code for the view controller that calls the popover:

//Delegate function called from popover
func doSomeStuff() {
    let alert = UIAlertController(title: "Some Stuff", message: "Do you want to do some stuff", preferredStyle: .Alert)

    alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {action in
        print("We did something here.")
    }))
    alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))

    presentViewController(alert, animated: true, completion: nil)
}

@IBAction func callPopover(sender: UIButton) {
    let popoverVC = self.storyboard?.instantiateViewControllerWithIdentifier("PopoverView") as! PopoverController
    popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
    popoverVC.preferredContentSize = CGSizeMake(200, 200)

    if let popoverController = popoverVC.popoverPresentationController {
        popoverController.backgroundColor = UIColor.lightGrayColor()
        popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

        popoverController.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)
        popoverController.sourceView = callPopoverButton

        popoverController.delegate = self

        popoverVC.delegate = self

        self.presentViewController(popoverVC, animated: true, completion: nil)
    }
}

//Allows popover to present on devices besides iPad.
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle{
    return UIModalPresentationStyle.None
}

The callPopover function is the action for the button on the first screen.

This is the code for the popover screen:

var delegate: ViewController!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func returnToMainView(sender: UIButton) {
    let alert = UIAlertController(title: "Dismiss Popover", message: "Do you want to dismiss this popover?", preferredStyle: .Alert)

    alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {action in
        self.delegate.doSomeStuff()
        self.dismissViewControllerAnimated(true, completion: nil)
    }))

    alert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)
}

When tapping the popover button on the first screen, the popover displays correctly:

Tapping the return button displays the alert:

Clicking Yes returns from the alert and should display the second alert, but that's where I get the error.

I think that the second alert is not displaying because the popover has not finished being dismissed, but have no idea how to get around it.


MediaPlayer crashing while playing mp3 from chunks of bytes?

I’m building an android application. The app functionality is that it transfer audio file from one device to another via bluetooth.

I’m trying to play the file in chunks in media player. Means that reciever receive audio file in chunks,play this file and add next chunk into the existing file.

I’m sending chunks of bytes(audio file) to another device and adding followed chunks into it. Playing these chunks at receiver side.

But the is issue my app is crashing and getting this error:

Error: MediaPlayer prepare failed: status = 0x1

Here is my code:

This is my code where i am sending audiofile when devices are paired,

InputStream inStream = getResources().openRawResource(R.raw.comman);
                        byte[] music = inputStreamToByteArray(inStream);

                        // Invoke client thread to send
                         message = new Message();
                        message.obj = music;
                        MainApplication.clientThread.incomingHandler.sendMessage(message);

this is code where converting sending data into chunks:

 byte[] buffer = new byte[Constants.CHUNK_SIZE];
                Log.v(TAG, "Waiting for data.  Expecting " + progressData.remainingSize + " more bytes.");
                int bytesRead = inputStream.read(buffer);
                dataOutputStream.write(buffer, 0, bytesRead);
                progressData.remainingSize -= bytesRead;
                readBuf = buffer;

this is code where i am receiving chunks of bytes,

 File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
        tempMp3.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempMp3);
        fos.write(mp3SoundByteArray);  //mp3SoundByteArray is byte chunks
        fos.close();
        MediaPlayer mediaPlayer = new MediaPlayer();
        FileInputStream fis = new FileInputStream(tempMp3);
        FileDescriptor fileDescriptor = fis.getFD();
        mediaPlayer.reset();
        mediaPlayer.setDataSource(fileDescriptor);
        mediaPlayer.prepare();  // here my app is crashing
        mediaPlayer.start();


Fancy Tree Plugin is removing <a>-tags and IDs from my <li>-elements

edit: Somehow i have forgotten to say hi... Hi guys!

so far i've always found an answere to my questions because the question has already been asked and answered. But this time i searched for hours and still have no idea why my code is not working how it is supposed to do.

To my background: i am an apprentice in the 2nd year, so please don't be to hard on me :-)

I am using Fancytree-2.12.0, jQuery-UI-1.11.4 and jQuery-1.11.3.

Here is the HTML Markup:

<div id="CategorieTree">
    <ul id="treeData" style="display:none;">
        <li id="rootNode" class="expanded">
            <a href="loadPage.asp?Start=1"><strong>rootNode title</strong></a>
            <ul>
                <li id="100"><a href="loadPage.asp?Content=100">title 100</a></li>
                <li id="200"><a href="loadPage.asp?Content=200">title 200</a>
                    <ul>
                        <li id="210"><a href="loadPage.asp?Content=210">title 210</a>
                            <ul>
                                <li id="211"><a href="loadPage.asp?Content=211">title 211</a></li>
                                <li id="212"><a href="loadPage.asp?Content=212">title 212</a></li>
                            </ul>
                        </li>
                        <li id="220"><a href="loadPage.asp?Content=220">title 220</a></li>
                    </ul>
                </li>
                <li id="300"><a href="loadPage.asp?Content=300">title 300</a>
                    <ul>
                        <li id="310"><a href="loadPage.asp?Content=310">title 310</a></li>
                        <li id="320"><a href="loadPage.asp?Content=320">title 320</a>
                            <ul>
                                <li id="321"><a href="loadPage.asp?Content=321">title 321</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</div>

The Tree is displayed totally fine. But when i try to click an element and the links should reload the page with different content, nothing happens! When i open the dev-tools (i am using chrome Version 45.0.2454.101 m) i can see my original  and another  that is obviously created by FancyTree, but here all my IDs and the aTag-elments are removed like that:

<div id="CategorieTree">
    <ul class="ui-fancytree fancytree-container fancytree-plain">
        <li class="fancytree-lastsib">
            <span class="lots of classes">
                <span class="fancytree-expander"></span>
                <span class="fancytree-title"><strong>rootNode title</strong></span>
            </span>
            <ul>
                <li>
                    <span class="lots of classes">
                        <span class="fancytree-expander"></span>
                        <span class="fancytree-title">title 100</span>
                    </span>
                </li>
                <li>
                    <span class="lots of classes">
                        <span class="fancytree-expander"></span>
                        <span class="fancytree-title">title 200</span>
                    </span>
                    <ul>
                        <li>
                            <span class="lots of classes">
                                <span class="fancytree-expander"></span>
                                <span class="fancytree-title">title 210</span>
                            </span>
                            <ul>
                                <li>
                                    ....and so on
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</div>

Here is my JavaScript for the initialization:

<script type="text/javascript">
  $("#CategorieTree").fancytree({
    activeVisible: true, // Make sure, active nodes are visible (expanded).
    aria: false, // Enable WAI-ARIA support.
    autoActivate: true, // Automatically activate a node when it is focused (using keys).
    autoCollapse: false, // Automatically collapse all siblings, when a node is expanded.
    autoScroll: false, // Automatically scroll nodes into visible area.
    clickFolderMode: 4, // 1:activate, 2:expand, 3:activate and expand, 4:activate (dblclick expands)
    checkbox: false, // Show checkboxes.
    debugLevel: 2, // 0:quiet, 1:normal, 2:debug
    disabled: false, // Disable control
    focusOnSelect: false, // Set focus when node is checked by a mouse click
    generateIds: false, // Generate id attributes like <span id='fancytree-id-KEY'>
      idPrefix: "ft_", // Used to generate node id´s like <span id='fancytree-id-<key>'>.
    icons: false, // Display node icons.
    keyboard: true, // Support keyboard navigation.
    keyPathSeparator: "/", // Used by node.getKeyPath() and tree.loadKeyPath().
    minExpandLevel: 1, // 1: root node is not collapsible
    quicksearch: false, // Navigate to next node by typing the first letters.
    selectMode: 2, // 1:single, 2:multi, 3:multi-hier
    tabbable: true, // Whole tree behaves as one single control
    titlesTabbable: false // Node titles can receive keyboard focus
  });
</script>

My Question is:
Do aTags NEVER work when you initialize fancytree with pure HTML-Markup or did i just do something wrong?

Edit: I got my IDs!

generateIds: false;

had to be set to true.

Edit 2: I have not found a solution for my a-Tag problem. They still get removed when i initialize my tree with plain HTML-markup. Thus i have rewritten my code and now i initialize the tree by using the source-attribute.


XSL: How can I access a variable defined in a called template, in the calling parent scope?

My code looks something like this (deliberate simplification):

<xsl:template match="/">
  <xsl:call-template name="call_me" />
  <xsl:value-of select="$inner_variable" />
</xsl:template>

<xsl:template name="call_me">
  <xsl:variable name="inner_variable" select="/*" />
</xsl:template>

Obviously this won't work because of the scope of the variable. My question is:
is there any way to either define the variable globally from the call_me template, or to access this local variable from the parent (calling template) scope?

EDIT: The variable is not a XML tree fragment, but a node-set processed by C# functions. So I really need to access the variable.

Thanks!


Is it possible to permit all users except anonymous one?

How can I permit access to URL such that only anonymous one can't get the page?
I'm using Spring security.

<intercept-url pattern="/pattern/page.html" access="__WHAT_SHOULD_BE_HERE__"/>


Python: Can't Convert lists from SQL

Hello I am trying to learn Python, and right now I want to import some data from SQL. Unfortunately I have a problem that I wasn't capable of solving. I am getting the following error message:

cursor.execute("select * from matchinfo WHERE matchid = '%i'" %
  Matchid) TypeError: %i format: a number is required, not pyodbc.Row"

I guess the issue is that the list data isn't formatted as integers, however when I try to do stuff like "Matchid[0] = int(Matchid[0])" (and then print out Matchid[0]) it's not working either. So I am not really sure how to fix the problem. The code is below and thanks in advance.

import pyodbc

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-
FCDHA0J\SQLEXPRESS;DATABASE=Data')

cursor = cnxn.cursor()

cursor.execute("select matchid from matchinfo where matchid > 1 order by dato asc")

Matchinfo = cursor.fetchall()

for Matchid in Matchinfo:

    print(Matchinfo[0])

    cursor.execute("select * from matchinfo WHERE matchid = '%i'" % Matchid)


Is it possible to create a multiplot of data and images with ggplot?

I would like to know if it is possible with ggplot2 to create a multiple plot (like a facet) including images to look like that:

I don't know exactly how to arrange the image data to pass them to geom_raster() or how to include an image in a data frame...

what I have tried:

> img1 <- readPNG('1.png')
> img2 <- readPNG('2.png')
> img3 <- readPNG('3.png')

> test <- data.frame(c(1,2,3),c(5,2,7),c(img1,img2,img3))
> nrow(test)
 [1] 4343040

I already have a problem here to build a data frame with the images inside... each 3 lines a repeated (I guess once per pixel).


Concurrent Modification Exception in publishResults

I'm implementing Filter in my Custom Adapter but I got CME when I press the search icon in action bar. I do some research and edit my code but no effect.

My code:

private class TaskFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if (constraint != null && constraint.toString().length() > 0) {
                ArrayList<TaskModel> filteredItems = new ArrayList<TaskModel>();

                for (int i = 0, l = originalList.size(); i < l; i++) {
                    TaskModel country = originalList.get(i);
                    if (country.getName().toString().toLowerCase().contains(constraint))
                        filteredItems.add(country);
                }
                result.count = filteredItems.size();
                result.values = filteredItems;
            } else {
                synchronized (this) {
                    result.values = originalList;
                    result.count = originalList.size();
                }
            }
            return result;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            clear();
            List<TaskModel> listcopy = (List<TaskModel>) results.values;
            synchronized (listcopy) {
                for (Iterator<TaskModel> it = listcopy.iterator(); it.hasNext(); ) {
                    TaskModel f = (TaskModel) it.next();  //this one cause the CME
                    add(f);
                }
            }
            notifyDataSetChanged();
        }
    }

What can I do?


jQuery CrossDomain iframe Mousemove function

I'm working on project where I'm embedding vimeo videos FULLSCREEN using code :

<iframe id="iframe" src="http://player.vimeo.com/video/...../.." width="100%" height="100%" frameborder="0"></iframe>

I'm using Mousemove function on parent page to show company logo on Mousemove like this :

    $(document).ready(function() {
    var $top = $('#logo');
    var $document = $(document);
    var timer = null;
    var timerIsRunning = false;

    $top.hide();

    $document.mousemove(function(e){
    e.stopPropagation();
    });
    setTimeout(function() {
                    $document.mousemove(function(e) {
                            if($top.is(':hidden')) {
                                $top.fadeIn(2000);
                            } else {
                                if(!timerIsRunning) {
                                    timerIsRunning = true;
                                    clearTimeout(timer);
                                    timer = setTimeout(function() { $top.fadeOut();  }, 15000);
                                    setTimeout(function() {timerIsRunning = true;}, 15000);
                                }
                            }
                    });
            }, 2000);

});

My issue is browser doesn't detect Mousemove function over embedded fullscreen video & that is why Logo div doesn't appear...

Using CSS pointer-events: none; It works but disabled Video Player Control.

Is there any Solution ?

Thanks


Wiring up Knockout with SignalR (Object doesn't support property or method)

I'm getting the following js error (on the line of code marked ###) when starting my app:

JavaScript runtime error: Object doesn't support property or method 'messages'

I've previously had this working without knockout, but am trying to add in knockout as I feel this will be easier to maintain in the long run. I suspect that as this is my first venture into both SignalR and Knockout, I've done something blindingly stupid, so any pointers please let me know. The mappedMessages data is fully populated, it's just when it tries to set self.messages it has the issue. Knockout 3.0.0, SignalR 1.1.3.

The full javascript code is below:

$(function () {

    var messageHub = $.connection.messageHubMini;

    function init() { }

    function Message(data) {
        this.Operator = ko.observable(data.Operator);
        this.text = ko.observable(data.Text);
    }

    function MessagesViewModel() {
        // Data
        var self = this;
        self.messages = ko.observableArray([]); //### message on this line
    }

    // Add a client-side hub method that the server will call
    messageHub.client.updateMessages = function (data) {

        var mappedMessages = $.map(data, function (item) { return new Message(item) });
        self.messages(mappedMessages);
    }

    // Start the connection
    $.connection.hub.start().done(init);

    ko.applyBindings(new MessagesViewModel());
});

Thanks :)


SWRevealViewController toggle not working with custom Navigation Bar Button

I am using SWRevealViewController to show a side menu in Swift 2.0 I have downloaded the files from GitHub, created the bridging header and connected segues correctly. I am creating a custom button but the action "reveal toggle" is not firing. Where am I making a mistake?

super.viewDidLoad()
    self.navigationController?.navigationBar.topItem?.title = "DASHBOARD"
    self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
    self.navigationController!.navigationBar.titleTextAttributes =
        [NSForegroundColorAttributeName: UIColor.whiteColor()]
    self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Teko-Regular", size: 26)!]
    self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
    let btnName = UIButton()
    btnName.setImage(UIImage(named: "LeftNavItem"), forState: .Normal)
    btnName.frame = CGRectMake(0, 0, 20, 20)

    let leftBarButton = UIBarButtonItem()
    leftBarButton.customView = btnName
    self.navigationItem.leftBarButtonItem = leftBarButton
    if self.revealViewController() != nil {
        //print(self.revealViewController())
        leftBarButton.target = self.revealViewController()
        leftBarButton.action = Selector("revealToggle:")

        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

The gesture recognizer is firing properly, but not the "revealToggle:" What's the mistake?


Indy 9 - Email with body as RTF and with attachments

I'm trying to send a email with indy 9:

Body as RTF, formatted from a TRichEdit

A single file attached

The code:

 Message := TIdMessage.Create()
 Message.Recipients.EMailAddresses := 'someone@domain.dotcom';

 Message.ContentType := 'multipart/alternative';

 with TIdText.Create(Message.MessageParts) do
   ContentType := 'text/plain';

 with TIdText.Create(Message.MessageParts) do
 begin
   ContentType := 'text/richtext';
   Body.LoadFromFile('c:\bodymsg.rtf');
 end;

 TIdAttachment.Create(Message.MessageParts, 'c:\myattachment.zip');

 // send...

The result: body comes empty (using web gmail and outlook 2010 as clients).

I'm already tried other content types without success:

text/rtf

text/enriched

NOTE: I'll not upgrade to Indy 10.


How to insert into an existing temp table in SQL Server

I am trying to execute two select statements into a query that pumps data into a temp table. The first query will have 5 columns while the second query will have only one column.

The first can be achieved by:

Select a.ID AS [a],
       b.ID AS [b],
       c.ID AS [c]
INTO #testingTemp
FROM
....

Now I have my second query trying to pump data into #testingTemp:

Select z.ID AS [c]
INTO #testingTemp
FROM
....

But my problem is There is already an object named #testingTemp in the database?

I tried to search for a solution on the Internet but mostly people are only facing the problem at my first part but apparently nobody trying to expand a temp table on second query?


Regular Expression in Sql Server

I have special selection criterion for particular column and need the regular epxression for that.
e.g: A123456, S008942
this id's should get selected only
The first letter is alphabet and next 6 letters are digits.
It will always be like total of 7 letters (1Alphabet+6NumericDigits)

Any help is appreciated.
Thanks


Database solution for chat app

I am building a chat app with swift.You know I need to store all messages in a database.But I am so confused right now.Because I found the core data but I am not sure it is good for this case.

I need to store all messages like this:

id  -> Primary key
sender -> String
receiver -> String
message -> String
date -> Integer

Is core data good for this case ? If it is not then which solution is good for this case ?

Ps:If you have a question please ask me in the comments.


Pandas does not plot if label includes Turkish Characters like ş,ö,ü

My problem, I can't plot when label include turkish characters like ş,ö,ü,İ,Ğ,ğ

it just gives this output --> matplotlib.figure.Figure at 0x7f8499386050   not show the graph

How can I fix it?

here is my code:

def draw_pie(year,y,by):

    v=data[data['yil']==year]

    v=v.sort(y,ascending=False).head(20)

    v=v.groupby(by).aggregate('sum')

    veri= v[ y ]

    veri.plot(figsize=(10,10),kind='pie', labels=v.index,
               autopct='%.2f', fontsize=20)
    plt.show()

    draw_pie(2014,'toplam_hasilat','tur')

don't show beacuse tur contains 'Aşk' , 'Gençlik'

it is okay without turkish characters.

Thank you in advance


Bootstrap scrollspy offset on a fixed navbar does not work

I have created and exact fiddle of my problem here for testing: http://jsfiddle.net/aVBUy/7/

The issue is, when I click on navbar items, I have a script which scrolls to the element id. And I am using scrollspy to highlight the nav elements when page is in correct position. However the scrollspy is only changing the active state when it hits the top of the browser/device. Because my navbar is fixed I need an offset applied to scrollspy to offset by 51px (navbar height).

I've tried everything and I can't get it to work. Please check my fiddle and see if you can find the where I'm going wrong, would help me so much.

Here's my minimised code...

HTML

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </a>
            <a class="brand" href="#"><img src="img/logo.gif" alt="" /></a>
            <div class="nav-collapse collapse">
                <ul class="nav">
                    <li><a href="#welcome" data-scroll="#welcome">Welcome</a></li>
                    <li><a href="#about" data-scroll="#about">About</a></li>
                    <li><a href="#route" data-scroll="#route">The Route</a></li>
                    <li><a href="#bike" data-scroll="#bike">The Bike</a></li>
                </ul>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div id="welcome" class="row-fluid">
        <div class="span12">
            <h3>Welcome</h3>
            ...
        </div>
    </div>
    <hr />
    <div id="about" class="row-fluid">
        <div class="span12">
            <h3>About the ride</h3>
            ...
        </div>
    </div>
    <hr />
    <div id="route" class="row-fluid">
        <div class="span12">
            <h3>The Route</h3>
            ...
        </div>
    </div>
    <hr />
    <div id="bike" class="row-fluid">
        <div class="span12">
            <h3>The Bike</h3>
            ...
        </div>
    </div>
    <hr>
    <footer>
        <p class="muted"><small>© 2013 All rights reserved.</small></p>
    </footer>
</div>

CSS

body {
    padding: 51px 0 0;
}
/* Override Bootstrap Responsive CSS fixed navbar */
 @media (max-width: 979px) {
    .navbar-fixed-top, .navbar-fixed-bottom {
        position: fixed;
        margin-left: 0px;
        margin-right: 0px;
    }
}
body > .container {
    padding: 0 15px;
}

SCRIPT

var offsetHeight = 51;

$('.nav-collapse').scrollspy({
    offset: offsetHeight
});

$('.navbar li a').click(function (event) {
    var scrollPos = $('body > .container').find($(this).attr('href')).offset().top - offsetHeight;
    $('body,html').animate({
        scrollTop: scrollPos
    }, 500, function () {
        $(".btn-navbar").click();
    });
    return false;
});

FIDDLE

http://jsfiddle.net/aVBUy/7/


SyntaxError: missing ; before statement on JSONResponse

I am getting this kind of error:

SyntaxError: missing ; before statement

I don't know what causes the error but I have this code here:

(function pollschedule(){
    $.ajax({type: "GET",
    dataType: "jsonp",
    contentType: "application/json",
    url: "http://127.0.0.1:8080/get/schedule/1/",
    success: function(data){
        console.log(data);
    },
    complete: pollschedule, timeout: 5000});
})();

In case you might need to see what http://127.0.0.1:8080/get/schedule/1/ is:

def get_schedule(request, sid):
    schedule = Schedule.objects.filter(id=sid, date=datetime.datetime.now()).values('id', 'sched__name', 'date', 'time')
    sched_collection = collections.defaultdict(list)
    for i in schedule:
        sched_collection[i['sched__name']].append(i)

    return JsonResponse({"schedule" : dict(sched_collection)})

And returns this:

{"schedule": {"CWW": [{"date": "2016-11-11", "time": "17:10:10"}]}}

The error points the semi-colon after "schedule" in the response.


Can I create a ranked dict by iterating over an existing dict?

I've been searching for the answer to this for a while, but no joy.

I have a dict containing hotel names and prices.

mydict = {'HotelA': 100, 'HotelB': 300, 'HotelC': 200}

I would simply like to iterate over the dict and return a separate dict whose values rank the keys based on lowest to highest values, eg:

mynewdict = {'HotelA': 1, 'HotelB': 3, 'HotelC': 2}

I am aware of how to use sorted to iterate over a dictionary and provide an ordered list, but am unsure as to the best way to handle the above. All help greatly appreciated.


Round cells then auto fill VBA

In cell AR8, I am looking for a macro that will insert this equation " =ROUND(IF(AP8>(AN8*P8),AP8,AN8*P8),2) " then auto fill it down the column for the next 800-1000 rows below.


UITextField to sms recipents

I have a UITextField that the user will enter a cell phone number.The user touches a IBAction button and it is passed to the MFMessageComposeViewController sms recipients.it seems that the recipients will not alow a NSString to be used.Passing a NSString to the body works but not the recipients.

-(IBAction)buttonSMS: (id)sender
{
    if([MFMessageComposeViewController canSendText])
    {

    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];

    picker.recipients=[NSArray arrayWithObjects:@"15557774444", nil];
    picker.body = textField.text;
    picker.messageComposeDelegate = self;
    [self presentViewController:picker animated:YES completion:NULL];
    }

}

this is what i tried

picker.recipients = telField.text;

in place of

picker.recipients=[NSArray arrayWithObjects:@"15557774444", nil];

Can some one point me in the rite direction with some sample code.....please and thankyou

Expert in all things html,javascript and css but newbee in objective c


How to remove a nested div in HTML via child selector

how can I select and remove the div shown in the picture with a red frame:

I dont get any jQuery selection correctly, in my opinion I need to find div with title = Heatmap, then navigate two divs up and delete the whole div - is this possible ??
Thanks !


Bug with kendo grid,for closing pop up editor,you need to press cancel many times

its over a week im dealing with a  strange behavior of kendo grid ,let me split my problem, for better understanding ,i have a autocomplete text box ,after I press ENTER,it binds my grid,when I press "add new record" on my kendo grid,if I press cancel,the pop up will be closed,BUTTT after second search and the add new record,if press cancel,this time needs 2times pressing,3d time needs 3times pressing.......made me crazy,badly need your help

Here is the code

    $(document).keypress(function (e) {

        var myResult;
        var modelProducerResult;
        var temp = null;
        var mydata;
        var mydata_deviceType;
        var modelProducerDrpList;
        if (e.which == 13) {
            var i = 0;
            debugger;
            var flag = 0;
            // $('#turbingrid').data().kendoGrid.refresh();
            var drp = document.getElementById('autocomplete').value;
            $.ajax({
                dataType: "json",
                type: "POST",
                url: "@Url.Action("turbineDeviceDetail","AdminTool")",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ "turbine": drp, }),

                success: function (result) {
                    //debugger;
                    myResult = result;
                    var flg = "s";
                    $.ajax({
                        dataType: "json",
                        type: "POST",
                        url: "@Url.Action("producersDevice","AdminTool")",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ "flg": flg, }),
                        success: function (data) {
                            //    debugger;
                            mydata = data;
                        }
                    })

                    var flg_dvType = "s";
                    $.ajax({
                        dataType: "json",
                        type: "POST",
                        url: "@Url.Action("deviceTypeList","AdminTool")",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ "flg": flg_dvType, }),
                        success: function (data) {
                            //    debugger;
                            mydata_deviceType = data;

                        }

                    });

                    dataSource = new kendo.data.DataSource({
                        transport: {
                            read: function (options) {
                                options.success(result); // where data is the local data array

                            },

                            create: function (options) {

                                if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
                                    alert("DeviceIP and TurbineID could not be blank ");
                                    $("input[name='DeviceIP']").css("background-color", "red");
                                    $("input[name='TurbineId']").css("background-color", "red");

                                }
                                else

                                    $.ajax({
                                        type: "POST",
                                        url: "@Url.Action("AddDeviceToTurbine","AdminTool")",
                                        data: options.data.models[0],
                                        dataType: "json",
                                        success: function (data) {
                                            options.success(data);
                                            alert("New Device Has Been Inserted");
                                            //var e = $.Event("keypress", { which: 13 });
                                            //$('#autocomplete').trigger(e);

                                        },
                                        //error: function (data) {
                                        //    options.error(data);
                                        //    alert("Insert New Data Has Been Failed");
                                        //    alert(data);

                                        //},
                                        error: function (xhr, status, error) {
                                            alert(xhr.responseText);

                                        }
                                    });

                            },
                            update: function (options) {

                                if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
                                    alert("DeviceIP and TurbineID could not be blank ");

                                    $("input[name='DeviceIP']").css("background-color", "red");
                                    $("input[name='TurbineId']").css("background-color", "red");
                                }
                                else
                                    $.ajax({
                                        type: "POST",
                                        url: "@Url.Action( "update_grid","AdminTool")",
                                        data: options.data.models[0],
                                        dataType: "json",
                                        success: function (data) {
                                            options.success(data);
                                            alert("Update Has Been Done!");
                                            var value = document.getElementById('autocomplete').value;
                                            var e = $.Event("keypress", { which: 13 });
                                            $('#autocomplete').trigger(e);

                                        },
                                        error: function (data) {
                                            options.error(data);
                                            alert("Update Failed!");
                                        },
                                    });

                            },

                            parameterMap: function (options, operation) {
                                if (operation !== "read" && options.models) {
                                    return { models: kendo.stringify(options.models) };
                                }
                            }
                        },
                        batch: true,
                        pageSize: 40,
                        schema: {
                            //data: employee,
                            model: {
                                id: "DeviceIP",
                                fields: {
                                    DeviceIP: { editable: true, nullable: false },
                                    //Producer: { type:"string" },
                                    //3 Model: { type: "string" },
                                    DeviceType: { type: "string" },
                                    Description: { type: "string" },
                                    Username: { type: "string" },
                                    Password: { type: "string" },
                                    PublicIP: { type: "string" },
                                    ModelProducer: { type: "string" },
                                    Model: { type: "string" },
                                    Producer: { type: "string" },
                                    TurbineId: { type: "string" }
                                    //UnitPrice: { type: "number", validation: { required: true, min: 1} },
                                    //Discontinued: { type: "boolean" },
                                    //UnitsInStock: { type: "number", validation: { min: 0, required: true } }
                                }
                            }
                        }

                    });

                    $("#turbingrid").kendoGrid({
                        //   debugger;

                        dataSource: dataSource,
                        scrollable: false,

                        //toolbar: ["create"],
                        toolbar: [
                                 {
                                     name: "create",
                                     text: "ADD NEW DEVICE"
                                 }
                        ],

                        columns: [
                                 { field: 'DeviceIP', title: 'DeviceIP', width: '100px', id: 'DeviceIP' },
                                 { field: 'Producer', title: 'Producer', width: '80px', id: 'Producer' },//editor: ProductNameDropDownEditor,
                                 { field: 'Model', title: 'Model', width: '220px', id: 'Model' },
                                // { field: 'DeviceType', title: 'DeviceType', width: '100px', id: 'DeviceType', editor: deviceTypesList },
                                 { field: 'Description', title: 'Description', width: '220px' },
                                 { field: 'Username', title: 'Username', width: '120px' },
                                 { field: 'Password', title: 'Password', width: '100px' },
                                 { field: 'PublicIP', title: 'PublicIP', width: '120px', id: 'PublicIP' },
                                 { field: 'TurbineId', title: 'TurbineId', width: '120px', id: 'TurbineId', hidden: true },
                                 { field: 'device_id', title: 'device_id', width: '120px', id: 'deviceid', hidden: true },
                               //  { field: 'ModelProducer', title: 'Producer/Model', id: 'ModelProducer', hidden: true, editor: modelPro },
                                 {
                                     command: ["edit"], title: "&nbsp;"

                                 }
                        ],

                        editable: "popup",

                    });
                }
            })
        }
    });

    //This Part Is For The AUTOCOMPLETE textbox

    $(document).ready(function () {
        var value = document.getElementById('autocomplete').value;
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "@Url.Action("List_Turbine","AdminTool")",
            contentType: "application/json; charset=utf-8",
            //data: JSON.stringify({ "name": value ,}),
            data: {},
            success: function (result) {
                $("#autocomplete").kendoAutoComplete({
                    dataSource: result,
                    dataTextField: "Text",

                    // filter: "contains"

                });

            }
        })

    });


Singleton in enum performance

I was wondering about singleton in enum and it's performance.

When we have multithreaded environment we have to synchronize moment, when an instance is created.

Simply, we can use synchronized mod, for function called getInstance() which create instance
Somethink like that:

public synchronized Singleton getInstance(){
    if(instance == null){
        instance = new Singleton();
    }
    return instance;
}

It's lazy implementation it's good for me. But synchronized method is slow.
We can use double-locking to make it faster.

How about enum?
When we implement singleton as enum, instance of singleton will be created as first use. Next use, return current instance.

How it works?
When we want to get existing instance, there is implicit synchronized method which are slow? Or there is Double-lock implemented?


Determining matrix dimensions

While previously attempting to ascertain the dimensions of a matrix, I have used the core.matrix function shape. This function has done exactly what I have asked. I input one nested vector into the function and output the dimension. However, I am looking to input multiple matrices/nested vectors into the function and am running into trouble. Is the shape function capable of handling multiple inputs, or is there another way to determine the dimensions of multiple nested vectors?

An example input would look like: [[1 1] [1 1]] [[2 2 2] [2 2 2]]

the expected output would be: [2 2] for first matrix and [3 3] for second matrix, as both inputs are square matrices.


How to fix the first row in jquery datatable?

I want to provide a dropdown list to my DataTable on first row by following this page: jQuery DataTable. However, I don't want this row being sortable which the whole row will stay on the top of the tbody.

So how to set this row will not be sortable?

$('.tables').dataTable({
  "columnDefs": [{
    "targets": 4,
    "orderable": false
  }],
  "order": [
    [9, "desc"]
  ],
  'initComplete': function() {
    this.api().columns().every(function() {
      var column = this;
      console.log(column);
      var header = column.header();
      if (header.innerText != "myKeyword") {
        console.log(column.header());
        var select = $('<select>' +
            '<option value="All">All</option>' +
            '</select>')
          .appendTo($(column.header()))
          .on('change', function() {
            var val = $.fn.dataTable.util.escapeRegex(
              $(this).val()

            );

            if (val == 'All')
              val = '';
            column
              .search(val ? '^' + val + '$' : '', true, false)
              .draw();
          });

        column.data().unique().sort().each(function(d, j) {

          select.append('<option value="' + d + '">' + d + '</option>')
        });

      }

    });
  }
});


Competing-Consumers Messaging Pattern in Azure Service Bus

I'm just getting started with Windows Azure Service Bus (Topics & Queues) and I'm trying to implement a Competing-Consumers messaging pattern.

Essentially, I want to have a set of message Producers and a set of message Consumers. Once a message is produced, I want the first available Consumer to process the message. No other Consumers should get the message.

Is there a way to do this in Azure?


C# Asynchronous Function Threading

Tests

I have a function f1(string, string) which takes 4 seconds to execute (irrelevant what it does). Tested this by calling f1("a", "b") in main.

Calling

Console.WriteLine(f1("a", "b"));
Console.WriteLine(f1("a", "b"));

will wait 4 seconds for the first function to finish, prompt the return, wait another 4 seconds, prompt the second result all fine and dandy.

I've tried doing this in parallel by creating two separate anonymous threads with lambda like so:

new Thread(() => {Console.WriteLine(f1("a", "b")); }).Start();
new Thread(() => {Console.WriteLine(f1("a", "b")); }).Start();

Since I have a dual core processor and the functions are processing heavy (OS balanced this out very well) I have gotten both prompts after 4 seconds (instead of 8) so I know it worked in parallel.

Question

How can I write a function f1Async(string, string) which would initially call f1(string, string) albeit on a different thread every time (like I've done manually in main)? In order to know what the output of f1Async will be I have to wait for the thread to finish thus calling f1Async() two times in a row will result in the function waiting for one thread to finish before moving on to the second call.


Stop Angular from listing all from database?

I have a simple Angular Script which works like ajax to return search results, but when I don't type anything into the search box, it lists all of the data in the data base, how do I stop this?

My script is here: http://www.elliottcoe.com/search/search.js


Docker \ commit a container with its data

lots of documentation, but I still missing something. My Goal is to run one-time registry (2.0) push to it couple of images and export\commit the container.
I need to take it in zip file to machine without internet.

Thing is - the images I pushed to registry aren't kept. whenever I import the regsitry to test - it comes empty. I understand that commit\export will not work on mounted volumes - how do I "disable" the volumes of the initial registry docker?


Get RowEditing or Grid from a RowEditing component (a combobox in this case)

I'm building a "fix" for combobox because it shows the value field instead of the display field in the textbox when you open the row editor. However, to do this I have to change the value of the combobox just before is sent to the server. To do this, my idea was to hook to beforeedit event of row editing plugin.

The biggest problem, is that I can't find a way to reach the grid which I'm row editing, or directly the row editing plugin.

Only thing I can find is the form where the combobox is in with combobox.up('form') and I can hook to those events, but I think they don't happen "early enough". I can't find a way to obtain the rowediting plugin from the form however :\

Any idea on how to solve this problem?

Edit 1:

As sha requested, this is the problem shown as images:

http://dl.dropbox.com/u/762638/Files/Images/Screenshots/show_combobox_extjs_problem/part_1.png

http://dl.dropbox.com/u/762638/Files/Images/Screenshots/show_combobox_extjs_problem/part_2.png

http://dl.dropbox.com/u/762638/Files/Images/Screenshots/show_combobox_extjs_problem/part_3.png

And here you can find the combobox code:

Ext.define('Fdd.form.field.XComboBox', {
  extend: 'Ext.form.field.ComboBox',
  alias: 'widget.xcombobox',

  displayField: 'display',
  queryMode: 'local',
  valueField: 'value',
  //forceSelection: true,

  /**
   *
   * @property {Ext.form.Panel} parentForm
   * Contains a reference to the combobox form, used internally
   *
   * @readonly
   */
  parentForm: null,
  /**
   *
   * @property {Boolean} hasChanged
   * `true` if the combobox has changed its value since last show/hide cycle
   */
  hasChanged: false,

  statics: {
    xcomboboxRenderer: function(xcombobox) {
      return function(value, metaData, record, rowIndex) {
        if (value === null)
          return '';
        return xcombobox.store.getById(value.toString()).get('display');
      }
    }
  },

  initComponent: function() {
    var me                  = this;
    var xComboBoxStoreClass = 'Fdd.data.XComboBoxStore';
    var xComboBoxStoreKey   = Ext.getClassName(me);

    // FIXME: Fix default value to be display and not value field
    // Create the combo store if not exists
    me.createComboStoreIfNotExists = function() {
      // If store is not set, we can't do anything
      if (!me.store)
        return false;

      // If the store is an array, we break the functionality and return to a normal combobox
      // because XComboBox is to avoid problems with stores
      if (Ext.isArray(me.store))
        return false;

      // We need the object for the parent store, to avoid missing references
      var parentStore = null;
      if (Ext.isString(me.store))
        parentStore = Ext.getStore(me.store)
      else
        parentStore = me.store;

      // If the store doesn't have the updatedAt variable, we don't enable functionalities
      // because that is a requirement
      if (!Ext.isDefined(parentStore.updatedAt))
        return false;

      // If parent store is of type XComboBoxStore, it means that we already have created a combo store
      if (Ext.getClassName(parentStore) == xComboBoxStoreClass)
        return false;

      var comboStore = Fdd.NamespaceKeyedStoreManager.lookup(xComboBoxStoreKey, parentStore.storeId);
      if (!comboStore) {
        comboStore = Ext.create(xComboBoxStoreClass, parentStore);
        Fdd.NamespaceKeyedStoreManager.register(xComboBoxStoreKey, parentStore.storeId, comboStore);
      }
      me.store = comboStore;

      //me.on('afterrender', function(obj, eOpts) {
      //  obj.setValue(1);
      //});

      return comboStore;
    }

    // Load data if required
    me.loadUpdatedData = function() {
      me.createComboStoreIfNotExists();
      if (me.store)
        Fdd.NamespaceKeyedStoreManager.lookup(xComboBoxStoreKey, me.store.parentStore.storeId).loadIfNotUpdated();
    };

    // Load data if required
    me.loadUpdatedData();

    // Fires loadUpdatedData every time trigger is pressed
    me.on('expand', function(obj) {
      obj.loadUpdatedData();
    });

    // TODO: Building a fix for the problem combobox input field shows the value field instead of the display field
    me.on('boxready', function(obj) {
      obj.parentForm = obj.up('form');
      console.log(obj.parentForm);
      obj.mon(obj.parentForm, 'edit', function(editor) {
        console.log("beforeaction");
        console.log(e.originalValue);
        console.log(obj);
        if (!obj.hasChanged)
          obj.setValue(obj.originalValue);
      });
      obj.mon(obj.parentForm, 'show', function() {
        /*console.log("move:");
        console.log(obj.getValue());
        console.log(obj.inputEl.dom.value);*/
        obj.hasChanged = false;

        if (obj.parentForm) {
          if (obj.getValue() === null)
            obj.inputEl.dom.value = "";
          else
            obj.inputEl.dom.value = obj.store.getById(obj.getValue().toString()).get('display');
        }
      });
    });
    me.on('change', function(obj) {
      obj.hasChanged = true;
    });

    // Call parent initializator
    me.callParent(arguments);
  }
});

The code we are talking about starts from the TODO.

I suggest to ignore previous part because is used to create a store-duplicate to avoid filtering and buffered stores.

Edit 2:

It seems like the problem I'm trying to solve through this question is not directly related to the issue I'm trying to solve anymore (solved in a different way) so the question can be closed.

Thanks anyway.


Dexie function return item after seaching

I have a simple Dexie table search function that I want to return the searched item after the searching code is actually run

function ReturnItemFromTable() {
  db.table1
   .where('field1')
   .equals('some value')
   .first(function(item) {
     return item
  }
}

So I know the 'return' in the above code is in the wrong place for the function to know it's supposed to be returned. But if I put it in the right place it gets returns before the table.where has had a chance to run and thus returns undefined.

Is there a way to get this ordering done right?

Thanks,
Frank


ActionLayout not showing when LayoutDirection is set to rtl

I have an actionLayout to work as a notification badge on my toolbar. When I have my Phone in ltr everything works fine. When I turn my phone to rtl locale the badge and the menu icon disappear, though they take space on toolbar and click on them is working. Can anybody tell me what I'm doing wrong?

code

public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
        {
            inflater.Inflate(Resource.Menu.welcome_menu, menu);

            using (var icon = menu.FindItem(Resource.Id.action_notification))
            {
                icon.Icon.ApplyDrawableTint(MobileSettingsManager.Instance.MobileSettings.Theme.NavigationBar.Icon);
                if ((Activity as BaseActivity).IsRtl() && Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    icon.Icon.AutoMirrored = true;
                    var notification = menu.FindItem(Resource.Id.action_notification).ActionView;
                    notification.Click += async delegate
                    {
                        if (Utils.IsOnline(Context))
                            await MoveToNotifications();
                    };
                    _badge = notification.FindViewById<TextView>(Resource.Id.tv_notif_count);
                    _badge.ApplyFont();
                    _badge.Visibility = ViewStates.Gone;
                }
            }
            using (var icon = menu.FindItem(Resource.Id.action_filter))
                icon.Icon.ApplyDrawableTint(MobileSettingsManager.Instance.MobileSettings.Theme.NavigationBar.Icon);
        }

welcome_menu.xml

<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
      >

  <item
    android:id="@+id/action_filter"
    android:icon="@drawable/ic_filter"
    app:showAsAction="always"/>

  <item
    android:id="@+id/action_notification"
    app:actionLayout="@layout/action_notification_badge"
    android:icon="@drawable/notification_bell"
    app:showAsAction="always"/>
</menu>

action_notification_badge.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:clickable="true"
                android:background="@android:color/transparent"
    style="@android:style/Widget.ActionButton">
   <ImageView
        android:id="@+id/hotlist_bell"
        android:src="@drawable/notification_bell"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:contentDescription="bell" />
    <TextView
        android:id="@+id/tv_notif_count"
        android:layout_width="wrap_content"
        android:minWidth="17sp"
        android:textSize="10sp"
        android:textColor="#ffffff"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@null"
        android:backgroundTint="#ff0000"
        android:layout_alignTop="@id/hotlist_bell"
        android:layout_alignEnd="@id/hotlist_bell"
        android:layout_marginBottom="4dp"
        android:layout_marginStart="4dp"
        android:background="@drawable/rounded_square" />
</RelativeLayout>

rounded_square.xml

<?xml version="1.0" encoding="utf-8" ?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
  <solid
      android:color="#a3a3a3"/>
</shape>


Why not always use psyco for Python code?

psyco seems to be quite helpful in optimizing Python code, and it does it in a very non-intrusive way.

Therefore, one has to wonder. Assuming you're always on a x86 architecture (which is where most apps run these days), why not just always use psyco for all Python code? Does it make mistakes sometimes and ruins the correctness of the program? Increases the runtime for some weird cases?

Have you had any negative experiences with it? My most negative experience so far was that it made my code faster by only 15%. Usually it's better.

Naturally, using psyco is not a replacement for efficient algorithms and coding. But if you can improve the performance of your code for the cost of two lines (importing and calling psyco), I see no good reason not to.


Ajax content is being loaded regardless of if statement

I have a div being loaded with ajax but I wanted to add an if statement to only load the ajax if it is not already loaded. For some reason this isn't working on my site( Click on the left eye to see the error. ). Instead, the ajax content slides in and then the content is reloaded via ajax.

Here is my code:

    <script type="text/javascript">
    $(window).load(function () {
        function SlideOut(element) {
            var opened = $(".opened"),
                div = $("#" + element),
                content = $("#content");
            opened.removeClass("opened");
            div.addClass("opened");
            content.removeClass().addClass(element);
        }
        $("#content div").click(
            function () {
                var move = $(this).attr('data-move'),
                    id   = $(this).attr("id");
                if( id == 'forehead')
                {
                    $('#resume img').css('display', 'block');
                }

                else if(id =='left-eye23')
                {
                    var  leftcontent;
                    leftcontent = $("#left-content");
                    content = leftcontent.attr('class');
                    if( !leftcontent.hasClass('photos'))
                    {
                      SlideOut(move);
                        $("#left").bind("webkitTransitionEnd mozTransitionEnd oTransitionEnd msTransitionEnd transitionend",
                        function(){
                            $.ajax({
                            url:'photos.php',
                            beforeSend: function(){
                                leftcontent.html('<img src="loading.gif" /> Now loding...');
                            },
                            }).done(function(data){
                                leftcontent.html(data);
                                leftcontent.addClass("photos");
                            });
                            });
                        }
                    else if (leftcontent.hasClass('photos'))
                    {
                      SlideOut(move);
                    }

                }...


Cannot set property 'innerHTML' of null??

Why do I get this error in javascript:
Cannot set property 'innerHTML' of null

My code:

<asp:Literal ID="topLinkArticleOut" runat="server"></asp:Literal>
<button type="button" id="deleteTopLinkArticle" name="deleteTopLinkArticle"
onclick="ChangeText()" class="btn red" style="float: right;">Delete</button>

function ChangeText()
{
document.getElementById("topLinkArticleOut").innerHTML = "";
}


Already selected items of dropdown/combo box should reflect as selected on click over Label

I  am using label for attribute for input elements in my website that will help blind users. I have Combobox/Drop down in my code to enter Date (Month/Day) format. Currently if there is only single drop down , for example Select Country, then on click on Label, already selected country is reflecting as selected, that is okay. I have used this code of Jquery:

$(function () {
    $('label').click(function () {
        var id = $(this).attr('for');
        $('#' + id).select();
    });
});

But in Case of Date format as there are Child 'Label for' under Parent 'Label for' that is used for "ExpiryDate". So in this case my upper written Jquery is not working. That Jquery is working fine for Single Dropdown and for Teaxt boxes. But I want to select First child i.e. Month's already selected month should be selected. Please assist me so that I can implement it. I want to handle that when user click over Label then TextBox, Single Dropdown and Combobox/Multiple related dropdown's already entered/selected items should be shown as selected. My HTML Code is here:

<div class="editor-label">
  <label for="ExpiryDate">*Expiration Date</label>
</div>

<div class="editor-field">
  <label class="accessibleText" for="ExpirationMonth">
    <label for="ExpiryDate">*Expiration Date</label>
  </label>
  <select id="ExpirationMonth" name="ExpirationMonth" tabindex="0"><option value="">Month</option>
    <option selected="selected" value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
    <option value="4">Apr</option>
    <option value="5">May</option>
    <option value="6">Jun</option>
    <option value="7">Jul</option>
    <option value="8">Aug</option>
    <option value="9">Sep</option>
    <option value="10">Oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
  </select>

  <label class="accessibleText" for="ExpirationDay">
    <label for="ExpiryDate">*Expiration Date</label>
  </label>
  <select id="ExpirationDay" name="ExpirationDay" tabindex="0"><option value="">Day</option>
    <option selected="selected" value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>

  </select>
</div>


Sencha Touch 2: Simulating different profiles (phone/tablet) on Desktop OS (Linux/Windows)

I am learning Sench Touch 2. I figured if I want my app to be "responsive" to phone vs tablet platforms, I can use Profiles.

Ext.define('Mail.profile.Phone', {
    extend: 'Ext.app.Profile',

    config: {
        name: 'Phone',
        views: ['Main']
    },

    isActive: function() {
        return Ext.os.is.Phone;
    },

    launch: function() {
        Ext.create('Mail.view.phone.Main');
    }
});

I am developing on Arch Linux with Chromium. I installed installed user agent switchers to fake running on a tablet/phone OS, but the profiles doesn't appear to change anything. I added console.log() in the launch function

I wonder if I am using Profiles for the right thing? For example, I may want my app to display a list and a details view on tablets, and the list, animating to the details view
on a phone. If so, do I need a real tablet/phone just to test this profiles?


Dynamic Where clause with unknown number of parameters

I have searched for an answer to my question, but have been unable to find one that meets my needs.

The following two code snippets return the same thing and I have no preference which one to use, I am just including both in case it helps someone answer my question

private List<MyClass> GetMyClass(string name, string city, string state, string zip)
{
    using (MyEntities ctx = new MyEntities())
    {
        var results = from a in ctx.MyEntity
                      where (a.Name == name &&
                             a.City == city &&
                             a.State == state &&
                             a.ZIP == zip)
                      select a;

        return results.ToList();
    }
}

private List<MyClass> GetMyClass(string name, string city, string state, string zip)
{
    using (MyEntities ctx = new MyEntities())
    {
        var results = ctx.MyEntity.Where(a => a.Name == name)
                                  .Where(a => a.City == city)
                                  .Where(a => a.State == state)
                                  .Where(a => a.ZIP == zip)
                                  .Select(a => a);

        return results.ToList();
    }
}

For the purposes of this example, let's say I have a search screen which requires users to enter a Name and a City; State and ZIP are optional.  The query must at least search by those two fields, and any additional fields, if necessary.

Obviously, with my above examples, if a user searches only by Name and City, they would not get any results as the queries would be trying to match State == null and ZIP == null since those two parameters where not supplied.

How can I rewrite this code to only search on the fields that parameters have been supplied for?


Set div to width and height of child image?

JSFiddle

I have a div with class of container. The height of this div must equal the width. I have achieved this with:

.container{
    background-color: #e6e6e6;
    position: relative;
}

.container:before{
    content: "";
    display: block;
    padding-top: 100%;
}

Inside the container is an image holder, and inside this an image. The image must be constrained, it's height or width must not exceed the container and still maintain aspect ratio. This is achieved by:

img{
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

    max-height: 100%;
    max-width: 100%;
    width: auto;
    height: auto;

}

My question concerns the image holder, I need this to be the same width and height as the image that is inside of it. How can I do this? Using CSS only please.


Problems with "Team Foundation Server is not your current Source Control plug-in" when I try to start a new project in VS2017

I am new to Visual Studio 2017 and VSTS.
From my VSTS page I choose to create a new application and clone it in Visual Studio.
When I do this it launches Visual Studio. But then I get these error messages. How do I fix this?


Hide data, process to new div with each function

I have multiple same class divs that produce an array and a script that puts them into lists.

I would like to hide a JSON array object from briefly flashing (unprocessed) on the page before the script can process it into lists.

So I put them into a hidden div and the each function stops working.

The .hid divs actually contain:

<%=getCurrentAttribute('item','lists')%> that produce the JSON array.

<div class="hid" style="display:none;">[{"k":"Model","v":"AB"},{"k":"Color","v":"green"}]</div>
<div class="overview"></div>
<div class="hid" style="display:none;">[{"k":"Model","v":"AC"},{"k":"Color","v":"blue"}]</div>
<div class="overview"></div>
<div class="hid" style="display:none;">[{"k":"Model","v":"AD"},{"k":"Color","v":"red"}]</div>
<div class="overview"></div>

My script

jQuery('.hid').each(function () {
   var $data = jQuery(this), spec,
       specs = jQuery.parseJSON($data.html());
   jQuery(".overview").html('<div class="bullet_spec"></div>');
   jQuery.each(specs, function () {
       jQuery(".overview").children('div').append('<div class="specs"><span class="label">' + this.k + ':</span><span class="value"> ' + this.v + '</span></div>');
   });
   {
   }
});

http://jsfiddle.net/Qta2p/