Programs & Examples On #Policy based design

PYODBC--Data source name not found and no default driver specified

Below connection string is working

import pandas as pd
import pyodbc as odbc

sql_conn = odbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=SERVER_NAME;DATABASE=DATABASE_NAME;UID=USERNAME;PWD=PASSWORD;')

query = "SELECT * FROM admin.TABLE_NAME"
df = pd.read_sql(query, sql_conn)
df.head()

Do AJAX requests retain PHP Session info?

put your session() auth in all server side pages accepting an ajax request:

if(require_once("auth.php")) {

//run json code

}

// do nothing otherwise

that's about the only way I've ever done it.

Configuring angularjs with eclipse IDE

With current Angular 4 and 5 versions, there is an IDE for that.

Go to eclipse market place any search for 'Angular'. You will see the IDE and install it.

enter image description here

After that restart eclipse and follow the welcome messages to choose preferences.

How to start using eclipse with angular projects?

Considering you already have angular project and you want to import it into eclipse.

go to file > import > choose Angular Project

enter image description here

and It would be better to have your projects in a separate working set so that you will not confuse it with other kind of (like java)projects.

With Angular IDE You will have a terminal window too.

To open this type terminal in eclipse search box(quick access) on the top right corner.

enter image description here

Simple DateTime sql query

Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :

  1. Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.

  2. Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).

What are file descriptors, explained in simple terms?

Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.

When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :

Two Process

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

Getting the WordPress Post ID of current post

You can get id through below Code...Its Simple and Fast

 <?php $post_id = get_the_ID();
   echo $post_id;
   ?>

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

jquery get height of iframe content when loaded

simple one-liner starts with a default min-height and increases to contents size.

_x000D_
_x000D_
<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
_x000D_
_x000D_
_x000D_

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

postgresql return 0 if returned value is null

I can think of 2 ways to achieve this:

  • IFNULL():

    The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.

Syntax:

IFNULL(expression, alt_value)

Example of IFNULL() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5
  • COALESCE()

    The COALESCE() function returns the first non-null value in a list.

Syntax:

COALESCE(val1, val2, ...., val_n)

Example of COALESCE() with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

how to remove multiple columns in r dataframe?

Basic subsetting:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7

In plain English, what does "git reset" do?

The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset and git checkout.

After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:

That is basically it. The reset command overwrites these three trees in a specific order, stopping when you tell it to.

  1. Move whatever branch HEAD points to (stop if --soft)
  2. THEN, make the Index look like that (stop here unless --hard)
  3. THEN, make the Working Directory look like that

There are also --merge and --keep options, but I would rather keep things simpler for now - that will be for another article.

Check for file exists or not in sql server?

Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:

Set NOCOUNT ON

 DECLARE @Filename NVARCHAR(50)
 DECLARE @fileFullPath NVARCHAR(100)

 SELECT @Filename = N'LogiSetup.log'
 SELECT @fileFullPath = N'C:\LogiSetup.log'

create table #dir

(output varchar(2000))

 DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath     

insert into #dir    

exec master.dbo.xp_cmdshell @cmd

--Select * from #dir

-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')

       begin    
              Print 'File found'    
              --Add code you want to run if file exists    
       end    
else    
       begin    
              Print 'No File Found'    
              --Add code you want to run if file does not exists    
       end

drop table #dir

Find all paths between two graph nodes

Here is an algorithm finding and printing all paths from s to t using modification of DFS. Also dynamic programming can be used to find the count of all possible paths. The pseudo code will look like this:

AllPaths(G(V,E),s,t)
 C[1...n]    //array of integers for storing path count from 's' to i
 TopologicallySort(G(V,E))  //here suppose 's' is at i0 and 't' is at i1 index

  for i<-0 to n
      if i<i0
          C[i]<-0  //there is no path from vertex ordered on the left from 's' after the topological sort
      if i==i0
         C[i]<-1
      for j<-0 to Adj(i)
          C[i]<- C[i]+C[j]

 return C[i1]

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to remove RVM (Ruby Version Manager) from my system

In addition to @tadman's answer I removed the wrappers in /usr/local/bin as well as the file /etc/profile.d/rvm.

The wrappers include:

erb
gem
irb
rake
rdoc
ri
ruby
testrb

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

How to add Action bar options menu in Android Fragments

You need to call setHasOptionsMenu(true) in onCreate().

For backwards compatibility it's better to place this call as late as possible at the end of onCreate() or even later in onActivityCreated() or something like that.

See: https://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu(boolean)

How to create and handle composite primary key in JPA

You can make an Embedded class, which contains your two keys, and then have a reference to that class as EmbeddedId in your Entity.

You would need the @EmbeddedId and @Embeddable annotations.

@Entity
public class YourEntity {
    @EmbeddedId
    private MyKey myKey;

    @Column(name = "ColumnA")
    private String columnA;

    /** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {

    @Column(name = "Id", nullable = false)
    private int id;

    @Column(name = "Version", nullable = false)
    private int version;

    /** getters and setters **/
}

Another way to achieve this task is to use @IdClass annotation, and place both your id in that IdClass. Now you can use normal @Id annotation on both the attributes

@Entity
@IdClass(MyKey.class)
public class YourEntity {
   @Id
   private int id;
   @Id
   private int version;

}

public class MyKey implements Serializable {
   private int id;
   private int version;
}

Changing Background Image with CSS3 Animations

Your code can work well with some adaptations :

div {
  background-position: 50% 100%;
  background-repeat: no-repeat;
  background-size: contain;
  animation: animateSectionBackground infinite 240s;
}

@keyframes animateSectionBackground {
  00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
  12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
  25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
  37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
  50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
  62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
  75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
  87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}

Here is the explanation of the percentage to suit your situation:

First you need to calculate the "chunks". If you had 8 differents background, you need to do : 100% / 8 = 12.5% (to simplify you can let fall the decimals) => 12%

After that you obtain that :

@keyframes animateSectionBackground {
  00% { background-image: url(/assets/images/bg-1.jpg); }
  12% { background-image: url(/assets/images/bg-2.jpg); }
  25% { background-image: url(/assets/images/bg-3.jpg); }
  37% { background-image: url(/assets/images/bg-4.jpg); }
  50% { background-image: url(/assets/images/bg-5.jpg); }
  62% { background-image: url(/assets/images/bg-6.jpg); }
  75% { background-image: url(/assets/images/bg-7.jpg); }
  87% { background-image: url(/assets/images/bg-8.jpg); }
}

If you execute this code, you will see the transition will be permanantly. If you want the backgrounds stay fixed while a moment, you can do like this :

@keyframes animateSectionBackground {
  00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
  12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
  25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
  37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
  50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
  62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
  75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
  87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}

That mean you want :

  • bg-1 stay fixed from 00% to 11%
  • bg-2 stay fixed from 12% to 24%
  • etc

By putting 11%, the transtion duration will be 1% (12% - 11% = 1%). 1% of 240s (total duration) => 2.4 seconds.

You can adapt according to your needs.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

I had the perf counter reg issue and here's what I did.

  1. My exe file was SQLManagementStudio_x86_ENU.exe
  2. In command line typed in the below line and hit enter

C:\Projects\Installer\SQL Server 2008 Management Studio\SQLManagementStudio_x86_ENU.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

(Note : i had the exe in this location of my machine C:\Projects\Installer\SQL Server 2008 Management Studio)

  1. SQL Server installation started and this time it skipped the rule for Perf counter registry values. The installation was successful.

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I have similar problems, in my case seem to be related to network connectivity:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."

Things to check:

  • Is there any chance that your server is not able to respond within some time limit? Like 60 seconds or 4 minutes?
  • Is there a possibility that your device is switching networks (WiFi, 3G, VPN)?
  • Could someone (client vs. server) be waiting for authentication?

Sorry, no ideas how to fix. Just debugging this, trying to find out what the problem is (-1021, -1001, -1009)

Update: Google search was very kind to find this:

  • -1001 TimedOut - it took longer than the timeout which was alotted.
  • -1003 CannotFindHost - the host could not be found.
  • -1004 CannotConnectToHost - the host would not let us establish a connection.

nodemon not working: -bash: nodemon: command not found

I ran into the same problem since I had changed my global path of npm packages before.

Here's how I fixed it :

When I installed nodemon using : npm install nodemon -g --save , my path for the global npm packages was not present in the PATH variable .

If you just add it to the $PATH variable it will get fixed.

Edit the ~/.bashrc file in your home folder and add this line :-

export PATH=$PATH:~/npm

Here "npm" is the path to my global npm packages . Replace it with the global path in your system

javascript pushing element at the beginning of an array

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

What's the "average" requests per second for a production web application?

That is a very open apples-to-oranges type of question.

You are asking 1. the average request load for a production application 2. what is considered fast

These don't neccessarily relate.

Your average # of requests per second is determined by

a. the number of simultaneous users

b. the average number of page requests they make per second

c. the number of additional requests (i.e. ajax calls, etc)

As to what is considered fast.. do you mean how few requests a site can take? Or if a piece of hardware is considered fast if it can process xyz # of requests per second?

iPhone UITextField - Change placeholder text color

The following only with iOS6+ (as indicated in Alexander W's comment):

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];

Uncaught ReferenceError: $ is not defined

Strange enough, my problem was coming from PHP.

A REST API call was failing, and it was breaking the loading of the libraries afterwards. Since failure was from the REST call, it was not giving me a php compile error.

Keep this as an option also, if loading jquery seems ok.

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

Remove URL parameters without refreshing page

None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:

/**
* Removes URL parameters
* @param removeParams - param array
*/
function removeURLParameters(removeParams) {
  const deleteRegex = new RegExp(removeParams.join('=|') + '=')

  const params = location.search.slice(1).split('&')
  let search = []
  for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])

  window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
}

removeURLParameters(['param1', 'param2'])

How to vertically center content with variable height within a div?

This is my awesome solution for a div with a dynamic (percentaged) height.

CSS

.vertical_placer{
  background:red;
  position:absolute; 
  height:43%; 
  width:100%;
  display: table;
}

.inner_placer{  
  display: table-cell;
  vertical-align: middle;
  text-align:center;
}

.inner_placer svg{
  position:relative;
  color:#fff;
  background:blue;
  width:30%;
  min-height:20px;
  max-height:60px;
  height:20%;
}

HTML

<div class="footer">
    <div class="vertical_placer">
        <div class="inner_placer">
            <svg> some Text here</svg>
        </div>
    </div>
</div>  

Try this by yourself.

How can I make a div stick to the top of the screen once it's been scrolled to?

I have links setup in a div so it is a vertical list of letter and number links.

#links {
    float:left;
    font-size:9pt;
    margin-left:0.5em;
    margin-right:1em;
    position:fixed;
    text-align:center;
    width:0.8em;
}

I then setup this handy jQuery function to save the loaded position and then change the position to fixed when scrolling beyond that position.

NOTE: this only works if the links are visible on page load!!

var listposition=false;
jQuery(function(){
     try{
        ///// stick the list links to top of page when scrolling
        listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
        console.log(listposition);
        $(window).scroll(function(e){
            $top = $(this).scrollTop();
            $el = jQuery('#links');
            //if(typeof(console)!='undefined'){
            //    console.log(listposition.top,$top);
            //}
            if ($top > listposition.top && $el.css('position') != 'fixed'){
                $el.css({'position': 'fixed', 'top': '0px'});
            }
            else if ($top < listposition.top && $el.css('position') == 'fixed'){
                $el.css({'position': 'static'});
            }
        });

    } catch(e) {
        alert('Please vendor [email protected] (Myvendor JavaScript Issue)');
    }
});

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

How can I implement a tree in Python?

class Node:
    """
    Class Node
    """
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None

class Tree:
    """
    Class tree will provide a tree as well as utility functions.
    """

    def createNode(self, data):
        """
        Utility function to create a node.
        """
        return Node(data)

    def insert(self, node , data):
        """
        Insert function will insert a node into tree.
        Duplicate keys are not allowed.
        """
        #if tree is empty , return a root node
        if node is None:
            return self.createNode(data)
        # if data is smaller than parent , insert it into left side
        if data < node.data:
            node.left = self.insert(node.left, data)
        elif data > node.data:
            node.right = self.insert(node.right, data)

        return node


    def search(self, node, data):
        """
        Search function will search a node into tree.
        """
        # if root is None or root is the search data.
        if node is None or node.data == data:
            return node

        if node.data < data:
            return self.search(node.right, data)
        else:
            return self.search(node.left, data)



    def deleteNode(self,node,data):
        """
        Delete function will delete a node into tree.
        Not complete , may need some more scenarion that we can handle
        Now it is handling only leaf.
        """

        # Check if tree is empty.
        if node is None:
            return None

        # searching key into BST.
        if data < node.data:
            node.left = self.deleteNode(node.left, data)
        elif data > node.data:
            node.right = self.deleteNode(node.right, data)
        else: # reach to the node that need to delete from BST.
            if node.left is None and node.right is None:
                del node
            if node.left == None:
                temp = node.right
                del node
                return  temp
            elif node.right == None:
                temp = node.left
                del node
                return temp

        return node

    def traverseInorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traverseInorder(root.left)
            print(root.data)
            self.traverseInorder(root.right)

    def traversePreorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            print(root.data)
            self.traversePreorder(root.left)
            self.traversePreorder(root.right)

    def traversePostorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traversePostorder(root.left)
            self.traversePostorder(root.right)
            print(root.data)


def main():
    root = None
    tree = Tree()
    root = tree.insert(root, 10)
    print(root)
    tree.insert(root, 20)
    tree.insert(root, 30)
    tree.insert(root, 40)
    tree.insert(root, 70)
    tree.insert(root, 60)
    tree.insert(root, 80)

    print("Traverse Inorder")
    tree.traverseInorder(root)

    print("Traverse Preorder")
    tree.traversePreorder(root)

    print("Traverse Postorder")
    tree.traversePostorder(root)


if __name__ == "__main__":
    main()

Disable text input history

<input type="text" autocomplete="off" />

How to call C++ function from C?

You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.

Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:

 // *.h file
 // ...
 #ifdef __cplusplus
 #define EXTERNC extern "C"
 #else
 #define EXTERNC
 #endif

 typedef void* mylibrary_mytype_t;

 EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
 EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
 EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);

 #undef EXTERNC
 // ...


 // *.cpp file
 mylibrary_mytype_t mylibrary_mytype_init() {
   return new MyType;
 }

 void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
    MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
    delete typed_ptr;
 }

 void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
    MyType* typed_self = static_cast<MyType*>(untyped_self);
    typed_self->doIt(param);
 }

How to set default Checked in checkbox ReactJS?

Don't make it too hard. First, understand a simple example given below. It will be clear to you. In this case, just after pressing the checkbox, we will grab the value from the state(initially it's false), change it to other value(initially it's true) & set the state accordingly. If the checkbox is pressed for the second time, it will do the same process again. Grabbing the value (now it's true), change it(to false) & then set the state accordingly(now it's false again. The code is shared below.

Part 1

state = {
  verified: false
} // The verified state is now false

Part 2

verifiedChange = e => {
  // e.preventDefault(); It's not needed
  const { verified } = e.target;
  this.setState({
    verified: !this.state.verified // It will make the default state value(false) at Part 1 to true 
  });
}; 

Part 3

  <form> 
      <input
          type="checkbox"
          name="verified"
          id="verified"
          onChange={this.verifiedChange} // Triggers the function in the Part 2
          value={this.state.verified}
      />
      <label for="verified">
      <small>Verified</small>
      </label>
  </form>

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

An efficient way to Base64 encode a byte array?

Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):

    static public void testBase64EncodeToBuffer()
    {
        for (int i = 1; i < 200; ++i)
        {
            // prep test data
            byte[] testData = new byte[i];
            for (int j = 0; j < i; ++j)
                testData[j] = (byte)(j ^ i);

            // test
            testBase64(testData);
        }
    }

    static void testBase64(byte[] data)
    {
        if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
    }

    static public byte[] appendBase64(byte[] data
                              , int offset
                              , int size
                              , bool addLineBreaks = false)
    {
        byte[] buffer;
        int bufferPos = 0;
        int requiredSize = (4 * ((size + 2) / 3));
        // size/76*2 for 2 line break characters    
        if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);

        buffer = new byte[requiredSize];

        UInt32 octet_a;
        UInt32 octet_b;
        UInt32 octet_c;
        UInt32 triple;
        int lineCount = 0;
        int sizeMod = size - (size % 3);
        // adding all data triplets
        for (; offset < sizeMod;)
        {
            octet_a = data[offset++];
            octet_b = data[offset++];
            octet_c = data[offset++];

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
            if (addLineBreaks)
            {
                if (++lineCount == 19)
                {
                    buffer[bufferPos++] = 13;
                    buffer[bufferPos++] = 10;
                    lineCount = 0;
                }
            }
        }

        // last bytes
        if (sizeMod < size)
        {
            octet_a = offset < size ? data[offset++] : (UInt32)0;
            octet_b = offset < size ? data[offset++] : (UInt32)0;
            octet_c = (UInt32)0; // last character is definitely padded

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];

            // add padding '='
            sizeMod = size % 3;
            // last character is definitely padded
            buffer[bufferPos - 1] = (byte)'=';
            if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
        }
        return buffer;
    }

Extracting text OpenCV

Here is an alternative approach that I used to detect the text blocks:

  1. Converted the image to grayscale
  2. Applied threshold (simple binary threshold, with a handpicked value of 150 as the threshold value)
  3. Applied dilation to thicken lines in image, leading to more compact objects and less white space fragments. Used a high value for number of iterations, so dilation is very heavy (13 iterations, also handpicked for optimal results).
  4. Identified contours of objects in resulted image using opencv findContours function.
  5. Drew a bounding box (rectangle) circumscribing each contoured object - each of them frames a block of text.
  6. Optionally discarded areas that are unlikely to be the object you are searching for (e.g. text blocks) given their size, as the algorithm above can also find intersecting or nested objects (like the entire top area for the first card) some of which could be uninteresting for your purposes.

Below is the code written in python with pyopencv, it should easy to port to C++.

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image) 

The original image is the first image in your post.

After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:

Dilated image

Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:

enter image description here

You can see the text block on the left is detected as a separate block, delimited from its surroundings.

Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:

enter image description here

enter image description here

Tuning the parameters

The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.

For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.

Finding other object types:

For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):

enter image description here

Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.

How do I use brew installed Python as the default Python?

Homebrew does NOT replace stuff in "/usr/bin". You'll just want to put "/usr/local/bin" ahead of "/usr/bin" in your path, then "which python" will give you "/usr/local/bin/python".

Replacing /usr/bin/python (or /usr/bin/ruby) is highly unrecommended.

How can I set focus on an element in an HTML form using JavaScript?

If your code is:

<input type="text" id="mytext"/>

And If you are using JQuery, You can use this too:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

Keep in mind that you must draw the input first $(document).ready()

Can I use DIV class and ID together in CSS?

Of course you can.

Your HTML there is just fine. To style the elements with css you can use the following approaches:

#y {
    ...
}

.x {
    ...
}

#y.x {
    ...
}

Also you can add as many classes as you wish to your element

<div id="id" class="classA classB classC ...">
</div>

And you can style that element using a selector with any combination of the classes and id. For example:

#id.classA.classB.classC {
     ...
}

#id.classC {
}

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

Ignoring upper case and lower case in Java

The .equalsIgnoreCase() method should help with that.

How to print binary tree diagram?

Adapted from Vasya Novikov's answer to make it more binary, and use a StringBuilder for efficiency (concatenating String objects together in Java is generally inefficient).

public StringBuilder toString(StringBuilder prefix, boolean isTail, StringBuilder sb) {
    if(right!=null) {
        right.toString(new StringBuilder().append(prefix).append(isTail ? "¦   " : "    "), false, sb);
    }
    sb.append(prefix).append(isTail ? "+-- " : "+-- ").append(value.toString()).append("\n");
    if(left!=null) {
        left.toString(new StringBuilder().append(prefix).append(isTail ? "    " : "¦   "), true, sb);
    }
    return sb;
}

@Override
public String toString() {
    return this.toString(new StringBuilder(), true, new StringBuilder()).toString();
}

Output:

¦       +-- 7
¦   +-- 6
¦   ¦   +-- 5
+-- 4
    ¦   +-- 3
    +-- 2
        +-- 1
            +-- 0

How do I set the version information for an existing .exe, .dll?

I'm doing it with no additional tool. I have just added the following files to my Win32 app project.

One header file which defines some constants than we can reuse on our resource file and even on the program code. We only need to maintain one file. Thanks to the Qt team that showed me how to do it on a Qt project, it now also works on my Win32 app.

----[version.h]----

#ifndef VERSION_H
#define VERSION_H

#define VER_FILEVERSION             0,3,0,0
#define VER_FILEVERSION_STR         "0.3.0.0\0"

#define VER_PRODUCTVERSION          0,3,0,0
#define VER_PRODUCTVERSION_STR      "0.3.0.0\0"

#define VER_COMPANYNAME_STR         "IPanera"
#define VER_FILEDESCRIPTION_STR     "Localiza archivos duplicados"
#define VER_INTERNALNAME_STR        "MyProject"
#define VER_LEGALCOPYRIGHT_STR      "Copyright 2016 [email protected]"
#define VER_LEGALTRADEMARKS1_STR    "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR    VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR    "MyProject.exe"
#define VER_PRODUCTNAME_STR         "My project"

#define VER_COMPANYDOMAIN_STR       "www.myurl.com"

#endif // VERSION_H

----[MyProjectVersion.rc]----

#include <windows.h>
#include "version.h"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",        VER_COMPANYNAME_STR
            VALUE "FileDescription",    VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",        VER_FILEVERSION_STR
            VALUE "InternalName",       VER_INTERNALNAME_STR
            VALUE "LegalCopyright",     VER_LEGALCOPYRIGHT_STR
            VALUE "LegalTrademarks1",   VER_LEGALTRADEMARKS1_STR
            VALUE "LegalTrademarks2",   VER_LEGALTRADEMARKS2_STR
            VALUE "OriginalFilename",   VER_ORIGINALFILENAME_STR
            VALUE "ProductName",        VER_PRODUCTNAME_STR
            VALUE "ProductVersion",     VER_PRODUCTVERSION_STR
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

How can I specify a branch/tag when adding a Git submodule?

In my experience switching branches in the superproject or future checkouts will still cause detached HEADs of submodules regardless if the submodule is properly added and tracked (i.e. @djacobs7 and @Johnny Z answers).

And instead of manually checking out the correct branch manually or through a script git submodule foreach can be used.

This will check the submodule config file for the branch property and checkout the set branch.

git submodule foreach -q --recursive 'branch="$(git config -f <path>.gitmodules submodule.$name.branch)"; git checkout $branch'

Programmatically center TextView text

These two need to go together for it to work. Been scratching my head for a while.

numberView.textAlignment = View.TEXT_ALIGNMENT_CENTER
 numberView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)

How to get a json string from url?

If you're using .NET 4.5 and want to use async then you can use HttpClient in System.Net.Http:

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("url");

    // Now parse with JSON.Net
}

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

How to retrieve all keys (or values) from a std::map and put them into a vector?

Bit of a c++11 take:

std::map<uint32_t, uint32_t> items;
std::vector<uint32_t> itemKeys;
for (auto & kvp : items)
{
    itemKeys.emplace_back(kvp.first);
    std::cout << kvp.first << std::endl;
}

Inserting line breaks into PDF

After having so many nightmares, I found a solution.

utf8_decode(chr(10))

I tried \n, <br/> and chr(10) but nothing worked. Then I realized that it was utf-8 and just tried the above one. It works fine with MultiCell but not with Cell.

What is the difference between Left, Right, Outer and Inner Joins?

Check out Join (SQL) on Wikipedia

  • Inner join - Given two tables an inner join returns all rows that exist in both tables
  • left / right (outer) join - Given two tables returns all rows that exist in either the left or right table of your join, plus the rows from the other side will be returned when the join clause is a match or null will be returned for those columns

  • Full Outer - Given two tables returns all rows, and will return nulls when either the left or right column is not there

  • Cross Joins - Cartesian join and can be dangerous if not used carefully

How to create a md5 hash of a string in C?

To be honest, the comments accompanying the prototypes seem clear enough. Something like this should do the trick:

void compute_md5(char *str, unsigned char digest[16]) {
    MD5Context ctx;
    MD5Init(&ctx);
    MD5Update(&ctx, str, strlen(str));
    MD5Final(digest, &ctx);
}

where str is a C string you want the hash of, and digest is the resulting MD5 digest.

What's the difference between VARCHAR and CHAR?

CHAR is fixed length and VARCHAR is variable length. CHAR always uses the same amount of storage space per entry, while VARCHAR only uses the amount necessary to store the actual text.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

php: catch exception and continue execution, is it possible?

Another angle on this is returning an Exception, NOT throwing one, from the processing code.

I needed to do this with a templating framework I'm writing. If the user attempts to access a property that doesn't exist on the data, I return the error from deep within the processing function, rather than throwing it.

Then, in the calling code, I can decide whether to throw this returned error, causing the try() to catch(), or just continue:

// process the template
    try
    {
        // this function will pass back a value, or a TemplateExecption if invalid
            $result = $this->process($value);

        // if the result is an error, choose what to do with it
            if($result instanceof TemplateExecption)
            {
                if(DEBUGGING == TRUE)
                {
                    throw($result); // throw the original error
                }
                else
                {
                    $result = NULL; // ignore the error
                }
            }
    }

// catch TemplateExceptions
    catch(TemplateException $e)
    {
        // handle template exceptions
    }

// catch normal PHP Exceptions
    catch(Exception $e)
    {
        // handle normal exceptions
    }

// if we get here, $result was valid, or ignored
    return $result;

The result of this is I still get the context of the original error, even though it was thrown at the top.

Another option might be to return a custom NullObject or a UnknownProperty object and compare against that before deciding to trip the catch(), but as you can re-throw errors anyway, and if you're fully in control of the overall structure, I think this is a neat way round the issue of not being able to continue try/catches.

JavaScript style.display="none" or jQuery .hide() is more efficient?

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The answer is that older apps run in 2208 x 1242 Zoomed Mode. But when an app is built for the new phones the resolutions available are: Super Retina HD 5.8 (iPhone X) 1125 x 2436 (458ppi), Retina HD 5.5 (iPhone 6, 7, 8 Plus) 1242 x 2208 and Retina HD 4.7 (iPhone 6) 750 x 1334. This is causing the confusion mentioned in the question. To build apps that use the full screen size of the new phones add LaunchImages in the sizes: 1125 x 2436, 1242 x 2208, 2208 x 1242 and 750 x 1334.


Updated for the new iPhones 12, 12 mini, 12 Pro, 12 Pro Max

Size for iPhone 12 Pro Max with @3x scaling, coordinate space: 428 x 926 points and 1284 x 2778 pixels, 458 ppi, device physical size is 3.07 x 6.33 in or 78.1 x 160.8 mm. 6.7" Super Retina XDR display.

Size for iPhone 12 Pro with @3x scaling, coordinate space: 390 x 844 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.

Size for iPhone 12 with @2x scaling, coordinate space: 585 x 1266 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.

Size for iPhone 12 mini with @2x scaling, coordinate space: 540 x 1170 points and 1080 x 2340 pixels, 476 ppi, device physical size is 2.53 x 5.18 in or 64.2 x 131.5 mm. 5.4" Super Retina XDR display.


Size for iPhone 11 Pro Max with @3x scaling, coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.06 x 6.22 in or 77.8 x 158.0 mm. 6.5" Super Retina XDR display.

Size for iPhone 11 Pro with @3x scaling, coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.81 x 5.67 in or 71.4 x 144.0 mm. 5.8" Super Retina XDR display.

Size for iPhone 11 with @2x scaling, coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm. 6.1" Liquid Retina HD display.

Size for iPhone X Max with @3x scaling (Apple name: Super Retina HD 6.5 display"), coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.05 x 6.20 in or 77.4 x 157.5 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Max Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 1242.0, 2688.0), scale: 3.0

Size for iPhone X with @2x scaling (Apple name: Super Retina HD 6.1" display), coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 828.0, 1792.0), scale: 2.0

Size for iPhone X and iPhone X with @3x scaling (Apple name: Super Retina HD 5.8" display), coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.79 x 5.65 in or 70.9 x 143.6 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X and X Screen bounds: (0.0, 0.0, 375.0, 812.0), Screen resolution: (0.0, 0.0, 1125.0, 2436.0), scale: 3.0

enter image description here

Size for iPhone 6, 6S, 7 and 8 with @3x scaling (Apple name: Retina HD 5.5), coordinate space: 414 x 736 points and 1242 x 2208 pixels, 401 ppi, screen physical size is 2.7 x 4.8 in or 68 x 122 mm. When running in Zoomed Mode, i.e. without the new LaunchImages or choosen in Setup on iPhone 6 Plus, the native scale is 2.88 and the screen is 320 x 568 points, which is the iPhone 5 native size:

Screen bounds: {{0, 0}, {414, 736}}, Screen resolution: <UIScreen: 0x7f97fad330b0; bounds = {{0, 0}, {414, 736}};
mode = <UIScreenMode: 0x7f97fae1ce00; size = 1242.000000 x 2208.000000>>, scale: 3.000000, nativeScale: 3.000000

Size for iPhone 6 and iPhone 6S with @2x scaling (Apple name: Retina HD 4.7), coordinate space: 375 x 667 points and 750 x 1334 pixels, 326 ppi, screen physical size is 2.3 x 4.1 in or 58 x 104 mm. When running in Zoomed Mode, i.e. without the new LaunchImages, the screen is 320 x 568 points, which is the iPhone 5 native size:

Screen bounds: {{0, 0}, {375, 667}}, Screen resolution: <UIScreen: 0x7fa01b5182d0; bounds = {{0, 0}, {375, 667}};
mode = <UIScreenMode: 0x7fa01b711760; size = 750.000000 x 1334.000000>>, scale: 2.000000, nativeScale: 2.000000

And iPhone 5 for comparison is 640 x 1136, iPhone 4 640 x 960.


Here is the code I used to check this out (note that nativeScale only runs on iOS 8):

UIScreen *mainScreen = [UIScreen mainScreen];
NSLog(@"Screen bounds: %@, Screen resolution: %@, scale: %f, nativeScale: %f",
          NSStringFromCGRect(mainScreen.bounds), mainScreen.coordinateSpace, mainScreen.scale, mainScreen.nativeScale);

Note: Upload LaunchImages otherwise the app will run in Zoomed Mode and not show the correct scaling, or screen sizes. In Zoomed Mode the nativeScale and scale will not be the same. On an actual device the scale can be 2.608 on the iPhone 6 Plus, even when it is not running in Zoomed Mode, but it will show scale of 3.0 when running on the simulator.

Comparing iPhone 6 and 6 Plus

jQuery: set selected value of dropdown list?

You can select dropdown option value by name

jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }
});

How do you test to see if a double is equal to NaN?

Try Double.isNaN():

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.

How do I get the path of the Python script I am running in?

import os
print os.path.abspath(__file__)

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

In R, how to find the standard error of the mean?

There's the plotrix package with has a built-in function for this: std.error

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

What is makeinfo, and how do I get it?

For Centos , I solve it by installing these packages.

yum install texi2html texinfo 

Dont worry if there is no entry for makeinfo. Just run

make all

You can do it similarly for ubuntu using sudo.

Kill a postgresql session/connection

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

SELECT 
    pg_terminate_backend(pid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:

REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

If you're using Postgres 8.4-9.1 use procpid instead of pid

SELECT 
    pg_terminate_backend(procpid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    procpid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

CSS Div Background Image Fixed Height 100% Width

See my answer to a similar question here.

It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:

.chapter {
    position: relative;
    height: 1200px;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/3/

The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

.chapter {
    position: relative;
    height: 0;
    padding-bottom: 75%;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/4/

You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.

How do I find which transaction is causing a "Waiting for table metadata lock" state?

mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks table.

Documentation here

How do you change the launcher logo of an app in Android Studio?

I created my icons using this tool:

https://romannurik.github.io/AndroidAssetStudio/index.html

After I downloaded these (they were already pre named to ic_launcher, very useful!) I found the

mipmap ic_launcher folder under the res folder

and I replaced the pre icons with the ones I created. Reinstall your app, and you'll see your new icon!

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

While developing the ios app i too face similar kind of issue. Simple Restart of the xcode works for me. Hope this will help some one.

Check that an email address is valid on iOS

To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.

Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$

How you can use regular expressions depends on the version of iOS you are using.

iOS 4.x and Later

You can use NSRegularExpression, which allows you to compile and test against a regular expression directly.

iOS 3.x

Does not include the NSRegularExpression class, but does include NSPredicate, which can match against regular expressions.

NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];

Read a full article about this approach at cocoawithlove.com.

iOS 2.x

Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

heroku - how to see all the logs

I prefer to do it this way

heroku logs --tail | tee -a herokuLogs

You can leave the script running in background and you can simply filter the logs from the text file the way you want anytime.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to detect the physical connected state of a network cable/connector?

Use 'ip monitor' to get REAL TIME link state changes.

Passing multiple variables to another page in url

Use the ampersand & to glue variables together:

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

What is use of c_str function In c++

In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.

for example

// a string to a C-style string conversion//

const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

And the output will be,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str 
Operation: strlen(cstr1)
The length of C-style string str1 = 17

How to make div occupy remaining height?

<div>
  <div id="header">header</div>
  <div id="content">content</div>
  <div id="footer">footer</div>
</div>

#header {
  height: 200px;
}

#content {
  height: 100%;
  margin-bottom: -200px;
  padding-bottom: 200px;
  margin-top: -200px;
  padding-top: 200px;
}

#footer {
  height: 200px;
}

Key existence check in HashMap

You won't gain anything by checking that the key exists. This is the code of HashMap:

@Override
public boolean containsKey(Object key) {
    Entry<K, V> m = getEntry(key);
    return m != null;
}

@Override
public V get(Object key) {
    Entry<K, V> m = getEntry(key);
    if (m != null) {
        return m.value;
    }
    return null;
}

Just check if the return value for get() is different from null.

This is the HashMap source code.


Resources :

Using external images for CSS custom cursors

I found out that you need to add the pointer eg:

div{
    cursor: url('cursorurl.png'), pointer;
}

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

NULL or BLANK fields (ORACLE)

SELECT COUNT (COL_NAME) 
FROM TABLE 
WHERE TRIM (COL_NAME) IS NULL 
or COL_NAME='NULL'

Is there a way to specify a default property value in Spring XML?

http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  <property name="location"><value>my_config.properties</value></property>  
  <property name="properties">  
    <props>  
      <prop key="entry.1">123</prop>  
    </props>  
  </property>  
</bean> 

Using fonts with Rails asset pipeline

You need to use font-url in your @font-face block, not url

@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts

config.assets.paths << Rails.root.join("app", "assets", "fonts")

How can I run NUnit tests in Visual Studio 2017?

Using the CLI, to create a functioning NUnit project is really easy. The template does everything for you.

dotnet new -i NUnit3.DotNetNew.Template
dotnet new nunit

On .NET Core, this is definitely my preferred way to go.

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

How to play ringtone/alarm sound in Android

You can push a MP3 file in your /sdcard folder using DDMS, restart the emulator, then open the Media application, browse to your MP3 file, long press on it and select "Use as phone ringtone".

Error is gone!

Edit: same trouble with notification sounds (e.g. for SMS) solved using Ringdroid application

Get URL query string parameters

Also if you are looking for current file name along with the query string, you will just need following

basename($_SERVER['REQUEST_URI'])

It would provide you info like following example

file.php?arg1=val&arg2=val

And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing

$_SERVER['REQUEST_URI']

Getting new Twitter API consumer and secret keys

From the Twitter FAQ:

Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.

cannot make a static reference to the non-static field

Just write:

private static double balance = 0;

and you could also write those like that:

private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;

How can I find all of the distinct file extensions in a folder hierarchy?

Since there's already another solution which uses Perl:

If you have Python installed you could also do (from the shell):

python -c "import os;e=set();[[e.add(os.path.splitext(f)[-1]) for f in fn]for _,_,fn in os.walk('/home')];print '\n'.join(e)"

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

Number of processors/cores in command line

The lscpu(1) command provided by the util-linux project might also be useful:

$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 58
Model name:            Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
Stepping:              9
CPU MHz:               3406.253
CPU max MHz:           3600.0000
CPU min MHz:           1200.0000
BogoMIPS:              5787.10
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");

For the time picker, you should add timepicker to Datepicker, and it would be formatted with one equivalent command.

EDIT

Use this one that extend jQuery UI Datepicker. You can pick up both date and time.

http://trentrichardson.com/examples/timepicker/

How to revert uncommitted changes including files and folders?

Git 2.23 introduced git restore command to restore working tree files.

https://git-scm.com/docs/git-restore

To restore all files in the current directory

git restore .

If you want to restore all C source files to match the version in the index, you can do

git restore '*.c'

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

In jQuery, how do I select an element by its name attribute?

$('input:radio[name=theme]').bind(
  'click',
  function(){
    $(this).val();
});

Best way to convert an ArrayList to a string

Download the Apache Commons Lang and use the method

 StringUtils.join(list)

 StringUtils.join(list, ", ") // 2nd param is the separator.

You can implement it by yourself, of course, but their code is fully tested and is probably the best possible implementation.

I am a big fan of the Apache Commons library and I also think it's a great addition to the Java Standard Library.

Check if enum exists in Java

If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.

Sample code:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    private static final Map<String, SampleEnum> nameToValueMap =
        new HashMap<String, SampleEnum>();

    static {
        for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
            nameToValueMap.put(value.name(), value);
        }
    }

    public static SampleEnum forName(String name) {
        return nameToValueMap.get(name);
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    // We know we'll never mutate this, so we can keep
    // a local copy.
    private static final SampleEnum[] copyOfValues = values();

    public static SampleEnum forName(String name) {
        for (SampleEnum value : copyOfValues) {
            if (value.name().equals(name)) {
                return value;
            }
        }
        return null;
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

Fastest way to tell if two files have the same contents in Unix/Linux?

For files that are not different, any method will require having read both files entirely, even if the read was in the past.

There is no alternative. So creating hashes or checksums at some point in time requires reading the whole file. Big files take time.

File metadata retrieval is much faster than reading a large file.

So, is there any file metadata you can use to establish that the files are different? File size ? or even results of the file command which does just read a small portion of the file?

File size example code fragment:

  ls -l $1 $2 | 
  awk 'NR==1{a=$5} NR==2{b=$5} 
       END{val=(a==b)?0 :1; exit( val) }'

[ $? -eq 0 ] && echo 'same' || echo 'different'  

If the files are the same size then you are stuck with full file reads.

How to get the current time in milliseconds from C in Linux?

Derived from Dan Moulding's POSIX answer, this should work :

#include <time.h>
#include <math.h>

long millis(){
    struct timespec _t;
    clock_gettime(CLOCK_REALTIME, &_t);
    return _t.tv_sec*1000 + lround(_t.tv_nsec/1.0e6);
}

Also as pointed out by David Guyon: compile with -lm

How to append text to a text file in C++?

I got my code for the answer from a book called "C++ Programming In Easy Steps". The could below should work.

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    ofstream writer("filename.file-extension" , ios::app);

    if (!writer)
    {
        cout << "Error Opening File" << endl;
        return -1;
    }

    string info = "insert text here";
    writer.append(info);

    writer << info << endl;
    writer.close;
    return 0;   
} 

I hope this helps you.

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

Kendo grid date column not formatting

Try formatting the date in the kendo grid as:

columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Try to check here

res >> values >> styles.xml

make sure that there no code like this

<item name="windowActionBar">false</item>

if there are code like that, you can disable for a while, or erase it

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Function to check if a string is a date

If that's your whole string, then just try parsing it:

if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
  // it's a date
}

How do I move a redis database from one server to another?

Nowadays you can also use MIGRATE, available since 2.6.

I had to use this since I only wanted to move the data in one database and not all of them. The two Redis instances live on two different machines.

If you can't connect directly to Redis-2 from Redis-1, use ssh port binding:

 ssh [email protected] -L 1234:127.0.0.1:6379

A small script to loop all the keys using KEYS and MIGRATE each key. This is Perl, but hopefully you get the idea:

 foreach ( $redis_from->keys('*') ) {

    $redis_from->migrate(
        $destination{host},    # localhost in my example
        $destination{port},    # 1234
        $_,                    # The key
        $destination{db},
        $destination{timeout} 
    );
 }

See http://redis.io/commands/migrate for more info.

How to convert all tables from MyISAM into InnoDB?

<?php

// Convert all MyISAM tables to INNODB tables in all non-special databases.
// Note: With MySQL less than 5.6, tables with a fulltext search index cannot be converted to INNODB and will be skipped.

if($argc < 4)
    exit("Usage: {$argv[0]} <host> <username> <password>\n");
$host = $argv[1];
$username = $argv[2];
$password = $argv[3];

// Connect to the database.
if(!mysql_connect($host, $username, $password))
    exit("Error opening database. " . mysql_error() . "\n");

// Get all databases except special ones that shouldn't be converted.
$databases = mysql_query("SHOW databases WHERE `Database` NOT IN ('mysql', 'information_schema', 'performance_schema')");
if($databases === false)
    exit("Error showing databases. " . mysql_error() . "\n");

while($db = mysql_fetch_array($databases))
{
    // Select the database.
    if(!mysql_select_db($db[0]))
        exit("Error selecting database: {$db[0]}. " . mysql_error() . "\n");
    printf("Database: %s\n", $db[0]);

    // Get all MyISAM tables in the database.
    $tables = mysql_query("SHOW table status WHERE Engine = 'MyISAM'");
    if($tables === false)
        exit("Error showing tables. " . mysql_error() . "\n");

    while($tbl = mysql_fetch_array($tables))
    {
        // Convert the table to INNODB.
        printf("--- Converting %s\n", $tbl[0]);
        if(mysql_query("ALTER TABLE `{$tbl[0]}` ENGINE = INNODB") === false)
            printf("--- --- Error altering table: {$tbl[0]}. " . mysql_error() . "\n");
    }
}

mysql_close();

?>

How do I remove accents from characters in a PHP string?

Indeed is a matter of taste. There are many flavors for converting such letters.

function replaceAccents($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'Ð', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', '?', '?', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', '?', '?', 'L', 'l', 'N', 'n', 'N', 'n', 'N', 'n', '?', 'O', 'o', 'O', 'o', 'O', 'o', 'Œ', 'œ', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'Š', 'š', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Ÿ', 'Z', 'z', 'Z', 'z', 'Ž', 'ž', '?', 'ƒ', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', '?', '?', '?', '?', '?', '?');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

Clear form after submission with jQuery

Propably this would do it for you.

 $('input').val('').removeAttr('checked').removeAttr('selected');

Dark theme in Netbeans 7 or 8

Darcula

UPDATE 2016-02: NetBeans 8 now has a Darcula plugin, better and more complete than the alternatives discussed in old version of this Answer.

The attractive and productive Darcula theme in JetBrains IntelliJ is now available in NetBeans 8.0 & 8.1!

The Real Thing

This plugin provides the real Darcula, not an imitation.

Konstantin Bulenkov of the JetBrains company open-sourced the Darcula look-and-feel originally built for the IntelliJ IDE. This NetBeans plugin discussed here wraps that original implementation, adapting it to NetBeans. So we see close fidelity to the original Darcula. [By the way, there are many other reasons beyond Darcula to use IntelliJ – both IntelliJ and NetBeans are truly excellent and amazing products.]

This NetBeans plugin is itself open-source as well.

Installation

Comes in two parts:

  • A plugin
  • A Fonts & Colors profile

Plugin

The plugin Darcula LAF for NetBeans is easily available through the usual directory within NetBeans.

Choose Tools > Plugins. On the Available Plugins tab, scroll or search for "Darcula LAF for NetBeans". As per usual, check the checkbox and click the Install button. Restart NetBeans.

enter image description here

Profile

  1. In NetBeans > Preferences > Fonts & Colors (tab) > Profile (popup menu), choose the new Darcula item.
  2. Click the Apply button.

I suggest also hitting Duplicate in case you ever make any modifications (discussed below).

enter image description here

Fix overly-bright background colors

You may find the background color of lines of code may be too bright such as lines marked with a breakpoint, or the currently executing line in the debugger. These are categories listed on the Annotations tab of the Fonts & Colors tab.

Of course you can change the background color of each Category manually but that is tedious.

Workaround: Click the Restore button found to the right of the Profile name. Double-check to make sure you have Darcula as the selected Profile of course. Then click the Apply and OK buttons at the bottom.

enter image description here

Font

You may want to change the font in the method editor. I most highly recommend the commercial font for programmers, PragmataPro. For a free-of-cost and open-source font, the best is Hack. Hack was built on the very successful DejaVu font which in turn was built on Bitstream Vera.

To change the font, add these steps to the above to duplicate the profile as a backup before making your modification:

  1. Click the Duplicate button.
  2. Save the duplicate with a different name such as appending your name.
    Example: “Darcula - Juliette”.
  3. Click the Apply button.

While in that same Fonts & Colors tab, select Default in the Category list and hit the button to choose a font.

You might also want to change the font seen in the Output and the Terminal panes. From that Fonts & Colors tab, switch to the sibling tab Miscellaneous. Then see both the Output tab and the Terminal tab.

Experience So Far

While still new I am reserving final judgement on Darcula. So far, so good. Already the makers have had a few updates fixing a few glitches, so that is good to see. This seems to be a very thorough product. As a plugin this affects the entire user interface of NetBeans; that can be very tricky to get right.

There was a similar plugin product predating Darcula: the “Dark Look And Feel Themes” plugin. While I was grateful to use that for a while, I am much happier with Darcula. That other one was more clunky and I had to spend much time tweaking colors of “Norway Today” to work together. Also, that plugin was not savvy with Mac OS X menus so the main Mac menu bar was nearly empty while NetBeans’ own menu bar was embedded within the window. The Darcula plugin has no such problem; the Mac menu bar appears normally.


The rest of this Answer is left intact for history, and for alternatives if Darcula proves problematic.


NetBeans 8 – Dark Editor

At least in NetBeans 8.0, two dark profiles are now built-in. Profile names:

  • Norway Today
  • City Lights

The profiles affect only the code editing pane, not the entire NetBeans user-interface. That should mean much less risk of side-effects and bugs than a plugin.

Norway Today

screen shot of NetBeans editor using the dark profile 'Norway Today'

City Lights

screen shot of NetBeans editor using the dark profile 'City Lights'

Tip: You can alter the font in either theme, while preserving the other aspects. Perhaps Menlo on a Mac, or its parent DejaVu. Or my fav, the commercial font Pragmata.

Unfortunately, neither theme suits my eyes. They do not begin to compare to the excellent Darcula theme in JetBrains IntelliJ.

Choose Profile in Font Settings

On a Mac, the menu path is Netbeans > Preferences > Fonts & Colors (tab) > Profile (popup menu).

On other host operating systems, the menu path may be Tools > Options > Fonts & Colors. Not sure, but it was so in previous versions.

screen shot of picking either of the built-in dark themes in NetBeans 8 Prefences > Fonts & Colors > Profile pop-up menu

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

Solve Cross Origin Resource Sharing with Flask

Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.

Install flask-cors

pip install -U flask-cors

then after app initialization, initialize flask-cors with default arguments:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
   return "Hello, cross-origin-world!"

How to deal with a slow SecureRandom generator?

On Linux, the default implementation for SecureRandom is NativePRNG (source code here), which tends to be very slow. On Windows, the default is SHA1PRNG, which as others pointed out you can also use on Linux if you specify it explicitly.

NativePRNG differs from SHA1PRNG and Uncommons Maths' AESCounterRNG in that it continuously receives entropy from the operating system (by reading from /dev/urandom). The other PRNGs do not acquire any additional entropy after seeding.

AESCounterRNG is about 10x faster than SHA1PRNG, which IIRC is itself two or three times faster than NativePRNG.

If you need a faster PRNG that acquires entropy after initialization, see if you can find a Java implementation of Fortuna. The core PRNG of a Fortuna implementation is identical to that used by AESCounterRNG, but there is also a sophisticated system of entropy pooling and automatic reseeding.

Force sidebar height 100% using CSS (with a sticky bottom image)?

I have run into this issue several times on different projects, but I have found a solution that works for me. You have to use four div tags - one that contains the sidebar, the main content, and a footer.

First, style the elements in your stylesheet:

#container {
width: 100%;
background: #FFFAF0;
}

.content {
width: 950px;
float: right;
padding: 10px;
height: 100%;
background: #FFFAF0;
}

.sidebar {
width: 220px;
float: left;
height: 100%;
padding: 5px;
background: #FFFAF0;
}

#footer {
clear:both;
background:#FFFAF0;
}

You can edit the different elements however you want to, just be sure you dont change the footer property "clear:both" - this is very important to leave in.

Then, simply set up your web page like this:

<div id=”container”>
<div class=”sidebar”></div>
<div class=”content”></div>
<div id=”footer”></div>
</div>

I wrote a more in-depth blog post about this at http://blog.thelibzter.com/how-to-make-a-sidebar-extend-the-entire-height-of-its-container. Please let me know if you have any questions. Hope this helps!

How to use XPath in Python?

If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use parsel:

>>> from parsel import Selector
>>> sel = Selector(text=u"""<html>
        <body>
            <h1>Hello, Parsel!</h1>
            <ul>
                <li><a href="http://example.com">Link 1</a></li>
                <li><a href="http://scrapy.org">Link 2</a></li>
            </ul
        </body>
        </html>""")
>>>
>>> sel.css('h1::text').extract_first()
'Hello, Parsel!'
>>> sel.xpath('//h1/text()').extract_first()
'Hello, Parsel!'

How can I check if a user is logged-in in php?

Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.

I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.

The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].

Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Add views below toolbar in CoordinatorLayout

To use collapsing top ToolBar or using ScrollFlags of your own choice we can do this way:From Material Design get rid of FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleGravity="top"
            app:layout_scrollFlags="scroll|enterAlways">


        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/ic_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_arrow_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                android:textSize="16sp"
                android:textStyle="bold" />

        </androidx.appcompat.widget.Toolbar>


        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_details_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

What does it mean if a Python object is "subscriptable" or not?

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

Value Change Listener to JTextField

Use a KeyListener (which triggers on any key) rather than the ActionListener (which triggers on enter)

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Goto xampp folder in local drive c, click on mysql folder, then click on bin and finally click on "mysqladmin" application. Then go back and refresh your browser and the problem is solved.

How to append elements into a dictionary in Swift?

Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh In your case, it will be,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

Please let me know if you find any issues in using above syntax.

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

Import txt file and having each line as a list

lines=[]
with open('file') as file:
   lines.append(file.readline())

How do I find which process is leaking memory?

You can run the top command (to run non-interactively, type top -b -n 1). To see applications which are leaking memory, look at the following columns:

  • RPRVT - resident private address space size
  • RSHRD - resident shared address space size
  • RSIZE - resident memory size
  • VPRVT - private address space size
  • VSIZE - total memory size

CSS – why doesn’t percentage height work?

A percentage value in a height property has a little complication, and the width and height properties actually behave differently to each other. Let me take you on a tour through the specs.

height property:

Let's have a look at what CSS Snapshot 2010 spec says about height:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element.

OK, let's take that apart step by step:

The percentage is calculated with respect to the height of the generated box's containing block.

What's a containing block? It's a bit complicated, but for a normal element in the default static position, it's:

the nearest block container ancestor box

or in English, its parent box. (It's well worth knowing what it would be for fixed and absolute positions as well, but I'm ignoring that to keep this answer short.)

So take these two examples:

_x000D_
_x000D_
<div   id="a"  style="width: 100px; height: 200px; background-color: orange">_x000D_
  <div id="aa" style="width: 100px; height: 50%;   background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="b"  style="width: 100px;              background-color: orange">_x000D_
  <div id="bb" style="width: 100px; height: 50%; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example, the containing block of #aa is #a, and so on for #b and #bb. So far, so good.

The next sentence of the spec for height is the complication I mentioned in the introduction to this answer:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

Aha! Whether the height of the containing block has been specified explicitly matters!

  • 50% of height:200px is 100px in the case of #aa
  • But 50% of height:auto is auto, which is 0px in the case of #bb since there is no content for auto to expand to

As the spec says, it also matters whether the containing block has been absolutely positioned or not, but let's move on to width.

width property:

So does it work the same way for width? Let's take a look at the spec:

The percentage is calculated with respect to the width of the generated box's containing block.

Take a look at these familiar examples, tweaked from the previous to vary width instead of height:

_x000D_
_x000D_
<div   id="c"  style="width: 200px; height: 100px; background-color: orange">_x000D_
  <div id="cc" style="width: 50%;   height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="d"  style="            height: 100px; background-color: orange">_x000D_
  <div id="dd" style="width: 50%; height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • 50% of width:200px is 100px in the case of #cc
  • 50% of width:auto is 50% of whatever width:auto ends up being, unlike height, there is no special rule that treats this case differently.

Now, here's the tricky bit: auto means different things, depending partly on whether its been specified for width or height! For height, it just meant the height needed to fit the contents*, but for width, auto is actually more complicated. You can see from the code snippet that's in this case it ended up being the width of the viewport.

What does the spec say about the auto value for width?

The width depends on the values of other properties. See the sections below.

Wahey, that's not helpful. To save you the trouble, I've found you the relevant section to our use-case, titled "calculating widths and margins", subtitled "block-level, non-replaced elements in normal flow":

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

OK, so width plus the relevant margin, border and padding borders must all add up to the width of the containing block (not descendents the way height works). Just one more spec sentence:

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

Aha! So in this case, 50% of width:auto is 50% of the viewport. Hopefully everything finally makes sense now!


Footnotes

* At least, as far it matters in this case. spec All right, everything only kind of makes sense now.

Entity Framework - Include Multiple Levels of Properties

I figured out a simplest way. You don't need to install package ThenInclude.EF or you don't need to use ThenInclude for all nested navigation properties. Just do like as shown below, EF will take care rest for you. example:

var thenInclude = context.One.Include(x => x.Twoes.Threes.Fours.Fives.Sixes)
.Include(x=> x.Other)
.ToList();

Crystal Reports - Adding a parameter to a 'Command' query

The solution I came up with was as follows:

  1. Create the SQL query in your favorite query dev tool
  2. In Crystal Reports, within the main report, create parameter to pass to the subreport
  3. Create sub report, using the 'Add Command' option in the 'Data' portion of the 'Report Creation Wizard' and the SQL query from #1.
  4. Once the subreport is added to the main report, right click on the subreport, choose 'Change Subreport Links...', select the link field, and uncheck 'Select data in subreport based on field:'

    NOTE: You may have to initially add the parameter with the 'Select data in subreport based on field:' checked, then go back to 'Change Subreport Links ' and uncheck it after the subreport has been created.

  5. In the subreport, click the 'Report' menu, 'Select Expert', use the 'Formula Editor', set the SQL column from #1 either equal to or like the parameter(s) selected in #4.

                    (Subreport SQL Column)  (Parameter from Main Report)
            Example:  {Command.Project} like {?Pm-?Proj_Name}
    

ngModel cannot be used to register form controls with a parent formGroup directive

The answer is right on the error message, you need to indicate that it's standalone and therefore it doesn't conflict with the form controls:

[ngModelOptions]="{standalone: true}"

php delete a single file in directory

The script you downloaded lists the content of a specified folder. You probably put the unlink - call in one of the while-loops that list the files.

EDIT - Now that you posted your code:

echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';

Doing this calls the unlink-function each time the line is written, deleting your file. You have to write a link to a script that contains a delete function and pass some parameter that tells your script what to delete.

Example:

<a href="/path/to/script.php?delete='. $FileLink .'">delete</a>

You should not pass the path to a file this script and just delete it though, because malevolent being might use it to just delete everything or do other evil things.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to align this span to the right of the div?

An alternative solution to floats is to use absolute positioning:

.title {
  position: relative;
}

.title span:last-child {
  position: absolute;
  right: 6px;   /* must be equal to parent's right padding */
}

See also the fiddle.

ArrayList vs List<> in C#

Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList ?” and “Why is it slower overall ?”, have a look below.

Whenever value types are used as elements, performance drops dramatically with ArrayList. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList’s Add only takes object parameters - the Garbage Collector gets triggered into performing a lot more work than with List<T>.

How much is the time difference ? At least several times slower than with List<T>. Just take a look at what happens with code adding 10 mil int values to an ArrayList vs List<T>: enter image description here

That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).

Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity: enter image description here

I’ve written a detailed analysis of what goes on with the above ArrayList scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.

Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):

[…] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.

00:00:01.6246959 (GCs= 6) List<Int32>
00:00:10.8555008 (GCs=390) ArrayList of Int32
00:00:02.5427847 (GCs= 4) List<String>
00:00:02.7944831 (GCs= 7) ArrayList of String

The output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.

How do I Validate the File Type of a File Upload?

Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: http://www.brettle.com/neatupload

Faster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.

Iterating each character in a string using Python

Well you can also do something interesting like this and do your job by using for loop

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

Answer is

M r . S u r y a a

However since range() create a list of the values which is sequence thus you can directly use the name

for e in name:
    print(e)

This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.

We have used tow Built in Functions ( BIFs in Python Community )

1) range() - range() BIF is used to create indexes Example

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2) len() - len() BIF is used to find out the length of given string

force line break in html table cell

Try using

<table  border="1" cellspacing="0" cellpadding="0" class="template-table" 
style="table-layout: fixed; width: 100%"> 

as table style along with

<td style="word-break:break-word">long text</td>

for td it works for normal/real scenario text with words, not for random typed letters without gaps

Difference between del, remove, and pop on lists

While pop and delete both take indices to remove an element as stated in above comments. A key difference is the time complexity for them. The time complexity for pop() with no index is O(1) but is not the same case for deletion of last element.

If your use case is always to delete the last element, it's always preferable to use pop() over delete(). For more explanation on time complexities, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

Android "hello world" pushnotification example

Update 2016:

GCM is being replaced with FCM

Update 2015:

Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To

Update 2014:

1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.

2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.

3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.

First Answer 2014

Here is a good question you may should have a look at it: How to add a push notification in my own android app

Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/

How do I remove/delete a virtualenv?

Just to echo what @skytreader had previously commented, rmvirtualenv is a command provided by virtualenvwrapper, not virtualenv. Maybe you didn't have virtualenvwrapper installed?

See VirtualEnvWrapper Command Reference for more details.

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

How to clear browser cache with php?

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

www.mywebsite.com/site1

www.mywebsite.com/site2

www.mywebsite.com/site3

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

How to change progress bar's progress color in Android

There's probably one thing that hasn't been referred to in this answer:

If your theme is inheriting from Theme.AppCompat, ProgressBar will assume the color you defined as "colorAccent" in your theme.

So, using..

<item name="colorAccent">@color/custom_color</item>

..will tint the color of the ProgressBar automagically to the @color/custom_color .

How can I get the current PowerShell executing file?

A short demonstration of @gregmac's (excellent and detailed) answer, which essentially recommends $PSCommandPath as the only reliable command to return the currently running script where Powershell 3.0 and above is used.

Here I show returning either the full path or just the file name.

Test.ps1:

'Direct:'
$PSCommandPath  # Full Path 
Split-Path -Path $PSCommandPath -Leaf  # File Name only

function main () {
  ''
  'Within a function:'
  $PSCommandPath
  Split-Path -Path $PSCommandPath -Leaf
}

main

Output:

PS> .\Test.ps1
Direct:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1

Within a function:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1

Visual Studio breakpoints not being hit

If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.

enter image description here

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

fetch gives an empty response body

fetch("http://localhost:8988/api", {
    method: "GET",
    headers: {
       "Content-Type": "application/json"
    }
})
.then((response) =>response.json());
.then((data) => {
    console.log(data);
})
.catch(error => {
    return error;
});

How to validate an e-mail address in swift?

Here is a fuse of the two most up-voted answer with the correct regex: a String extension using predicate so you can call string.isEmail

    extension String {
        var isEmail: Bool {
           let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,20}"            
           let emailTest  = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
           return emailTest.evaluateWithObject(self)
        }
    }

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How can I use optional parameters in a T-SQL stored procedure?

The answer from @KM is good as far as it goes but fails to fully follow up on one of his early bits of advice;

..., ignore compact code, ignore worrying about repeating code, ...

If you are looking to achieve the best performance then you should write a bespoke query for each possible combination of optional criteria. This might sound extreme, and if you have a lot of optional criteria then it might be, but performance is often a trade-off between effort and results. In practice, there might be a common set of parameter combinations that can be targeted with bespoke queries, then a generic query (as per the other answers) for all other combinations.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
BEGIN

    IF (@FirstName IS NOT NULL AND @LastName IS NULL AND @Title IS NULL)
        -- Search by first name only
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
            FirstName = @FirstName

    ELSE IF (@FirstName IS NULL AND @LastName IS NOT NULL AND @Title IS NULL)
        -- Search by last name only
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
            LastName = @LastName

    ELSE IF (@FirstName IS NULL AND @LastName IS NULL AND @Title IS NOT NULL)
        -- Search by title only
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
            Title = @Title

    ELSE IF (@FirstName IS NOT NULL AND @LastName IS NOT NULL AND @Title IS NULL)
        -- Search by first and last name
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
            FirstName = @FirstName
            AND LastName = @LastName

    ELSE
        -- Search by any other combination
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))

END

The advantage of this approach is that in the common cases handled by bespoke queries the query is as efficient as it can be - there's no impact by the unsupplied criteria. Also, indexes and other performance enhancements can be targeted at specific bespoke queries rather than trying to satisfy all possible situations.

curl: (60) SSL certificate problem: unable to get local issuer certificate

I have encountered this problem as well. I've read this thread and most of the answers are informative but overly complex to me. I'm not experienced in networking topics so this answer is for people like me.

In my case, this error was happening because I didn't include the intermediate and root certificates next to the certificate I was using in my application.

Here's what I got from the SSL certificate supplier:

- abc.crt
- abc.pem
- abc-bunde.crt

In the abc.crt file, there was only one certificate:

-----BEGIN CERTIFICATE-----
/*certificate content here*/
-----END CERTIFICATE-----

If I supplied it in this format, the browser would not show any errors (Firefox) but I would get curl: (60) SSL certificate : unable to get local issuer certificate error when I did the curl request.

To fix this error, check your abc-bunde.crt file. You will most likely see something like this:

-----BEGIN CERTIFICATE-----
/*additional certificate content here*/
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
/*other certificate content here*/
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
/*different certificate content here*/
-----END CERTIFICATE-----

These are your Intermediate and root certificates. Error is happening because they are missing in the SSL certificate you're supplying to your application.

To fix the error, combine the contents of both of these files in this format:

-----BEGIN CERTIFICATE-----
/*certificate content here*/
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
/*additional certificate content here*/
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
/*other certificate content here*/
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
/*different certificate content here*/
-----END CERTIFICATE-----

Note that there are no spaces between certificates, at the end or at the start of the file. Once you supply this combined certificate to your application, your problem should be fixed.

How do you set the startup page for debugging in an ASP.NET MVC application?

While you can have a default page in the MVC project, the more conventional implementation for a default view would be to use a default controller, implememented in the global.asax, through the 'RegisterRoutes(...)' method. For instance if you wanted your Public\Home controller to be your default route/view, the code would be:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Public", action = "Home", id = UrlParameter.Optional } // Parameter defaults
        );

    }

For this to be functional, you are required to have have a set Start Page in the project.

How to prevent gcc optimizing some statements in C?

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How to convert a Scikit-learn dataset to a Pandas dataset?

TOMDLt's solution is not generic enough for all the datasets in scikit-learn. For example it does not work for the boston housing dataset. I propose a different solution which is more universal. No need to use numpy as well.

from sklearn import datasets
import pandas as pd

boston_data = datasets.load_boston()
df_boston = pd.DataFrame(boston_data.data,columns=boston_data.feature_names)
df_boston['target'] = pd.Series(boston_data.target)
df_boston.head()

As a general function:

def sklearn_to_df(sklearn_dataset):
    df = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
    df['target'] = pd.Series(sklearn_dataset.target)
    return df

df_boston = sklearn_to_df(datasets.load_boston())

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

How do I sort strings alphabetically while accounting for value when a string is numeric?

namespace X
{
    public class Utils
    {
        public class StrCmpLogicalComparer : IComparer<Projects.Sample>
        {
            [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
            private static extern int StrCmpLogicalW(string x, string y);


            public int Compare(Projects.Sample x, Projects.Sample y)
            {
                string[] ls1 = x.sample_name.Split("_");
                string[] ls2 = y.sample_name.Split("_");
                string s1 = ls1[0];
                string s2 = ls2[0];
                return StrCmpLogicalW(s1, s2);
            }
        }

    }
}

How to format a number 0..9 to display with 2 digits (it's NOT a date)

In android resources it's rather simple

<string name="smth">%1$02d</string>

Load image with jQuery and append it to the DOM

Here is the code I use when I want to preload images before appending them to the page.

It is also important to check if the image is already loaded from the cache (for IE).

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
        src: photoUrl
    });

    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {

        //image loaded:
        //your code here to insert image into page

    } else {
        //go fetch the image:
        $(imgPreload).load(function (response, status, xhr) {
            if (status == 'error') {

                //image could not be loaded:

            } else {

                //image loaded:
                //your code here to insert image into page

            }
        });
    }

Does Google Chrome work with Selenium IDE (as Firefox does)?

artejera, do you mean Selenium as plugin to your browser (Selenium IDE)? Here is something for automation in Google Chrome.

But if you want to work with Selenium RC, just set up browser in your test script. There is setBrowser() method in Selenium.

Access index of the parent ng-repeat from child ng-repeat

My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

<div ng-repeat="f in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething($parent.$index)">Add Something</a>
    </div>
  </div>
</div>

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

Restarting cron after changing crontab file?

There are instances wherein cron needs to be restarted in order for the start up script to work. There's nothing wrong in restarting the cron.

sudo service cron restart

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

List all the files and folders in a Directory with PHP recursive function

It's shorter version :

function getDirContents($path) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

    $files = array(); 
    foreach ($rii as $file)
        if (!$file->isDir())
            $files[] = $file->getPathname();

    return $files;
}

var_dump(getDirContents($path));

How do I create a file at a specific path?

The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:

"C:\\Test"

or

r"C:\Test"

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How to get current class name including package name in Java?

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

How does collections.defaultdict work?

My own 2¢: you can also subclass defaultdict:

class MyDict(defaultdict):
    def __missing__(self, key):
        value = [None, None]
        self[key] = value
        return value

This could come in handy for very complex cases.

I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

How do I make a JSON object with multiple arrays?

Using below method pass any value which is any array:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

It can be used for any response:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}

Changing the width of Bootstrap popover

Increase width with CSS

You can use CSS to increase the width of your popover, like so:

/* The max width is dependant on the container (more info below) */
.popover{
    max-width: 100%; /* Max Width of the popover (depending on the container!) */
}

If this doesn't work, you probably want the solution below and alter your container element. (View the JSFiddle)


Twitter bootstrap Container

If that doesn't work, you probably need to specify the container:

// Contain the popover within the body NOT the element it was called in.
$('[data-toggle="popover"]').popover({
    container: 'body'
});

More Info

Twitter Bootstrap popover increase width

The popover is contained within the element that it is triggered in. In order to extend it "full width" - specify the container:

// Contain the popover within the body NOT the element it was called in.
$('[data-toggle="popover"]').popover({
    container: 'body'
});

JSFiddle

View the JSFiddle to try it out.

JSFiddle: http://jsfiddle.net/xp1369g4/

What is the purpose of XSD files?

An .xsd file is called an XML schema. Via an XML schema, we may require a certain structure in a given XML - which elements in which order, how many times, with which attributes, how they are nested, etc. If we have a schema for our XML input, we can verify that it contains the data we need it to contain, and nothing else, with a few lines invoking a schema validator.

Display only date and no time

If the column type is DateTime in SQL then it will store a time where you pass one or not.

It'd be better to save the date properly:

model.ReturnDate = DateTime.Now;

and then format it when you need to display it:

@Html.Label(Model.ReturnDate.ToShortDateString())

Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

or

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

To add a property to your model add this code:

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

EDIT:

I just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

Editor templates are a cool way of managing repetitive controls in MVC:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

How do I install a Python package with a .whl file?

The only way I managed to install NumPy was as follows:

I downloaded NumPy from here https://pypi.python.org/pypi/numpy

This Module

https://pypi.python.org/packages/d7/3c/d8b473b517062cc700575889d79e7444c9b54c6072a22189d1831d2fbbce/numpy-1.11.2-cp35-none-win32.whl#md5=e485e06907826af5e1fc88608d0629a2

Command execution from Python's installation path in PowerShell

PS C:\Program Files (x86)\Python35-32> .\python -m pip install C:/Users/MyUsername/Documents/Programs/Python/numpy-1.11.2-cp35-none-win32.whl
Processing c:\users\MyUsername\documents\programs\numpy-1.11.2-cp35-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.11.2
PS C:\Program Files (x86)\Python35-32>

PS.: I installed it on Windows 10.

SOAP client in .NET - references or examples?

Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.

There are 2 main way of doing this:

A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.

Adding a service reference step by step

The simplest way is to generate proxy classes in C# application (this process is called adding service reference).

  1. Open your project (or create a new one) in visual studio
  2. Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
  3. A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.

    add service reference dialog

    I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example

  4. Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).

    You should see generated proxy class name and namespace.

    In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.

    service reference proxy calss

  5. Go to your C# source code and add the following

    using WindowsFormsApplication1.ServiceReference1
    
  6. Now you can call the service this way.

    Service1Client service = new Service1Client();
    int year = service.getCurrentYear();
    

Hope this helps. If you encounter any problems, let us know.

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

jQuery: more than one handler for same event

Both handlers get called.

You may be thinking of inline event binding (eg "onclick=..."), where a big drawback is only one handler may be set for an event.

jQuery conforms to the DOM Level 2 event registration model:

The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values