Programs & Examples On #Wake on lan

Wake-on-LAN is an Ethernet computer networking standard that allows a computer to be turned on or woken up by a network message

Why does z-index not work?

Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.

Here's an example:

<section class="content">            
    <div class="modal"></div>
</section>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;
}

.modal {
    position: fixed;
    z-index: 100;
}

.side-tab {
    position: fixed;
    z-index: 5;
}

In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.

Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

Facebook Open Graph not clearing cache

I've found out that if your image is 72dpi it will give you the image size error. Use 96dpi instead. Hope this helps.

Run Executable from Powershell script with parameters

Just adding an example that worked fine for me:

$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg

Get individual query parameters from Uri

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

PHPExcel Make first row bold

These are some tips to make your cells Bold, Big font, Italic

Let's say I have columns from A to L

A1 - is your starting cell

L1 - is your last cell

$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setItalic(true);

Cannot issue data manipulation statements with executeQuery()

Use executeUpdate() to issue data manipulation statements. executeQuery() is only meant for SELECT queries (i.e. queries that return a result set).

PHP: Get key from array?

Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

How to remove a web site from google analytics

UPDATED ANSWER

Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :

  1. Account (Contains multiple properties, and views)
  2. Properties (Contains Views, a subset of Account)
  3. Views (subset of properties)

Google Analytics Admin Panel


Deleting an Account

Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.

To delete the account, follow the following steps : (refer to image below)

  • Choose the account you want to delete.

Choose the account you want to delete

  • Click on Account Settings

Click Account Settings

  • Bottom right, a small link that says delete this account.

Delete account

  • You will get a confirmation, if you are sure to, click Delete Account
  • It will give you details, and will confirm deletion (and provide additional info like to remove GA snippet on your website, etc)

Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.


Deleting a property

Deleting a property will remove the selected property, and all the views it holds. To delete a property, delete all views it contains individually (see below for deleting views)

  • Choose the property

Property choice

  • All profiles related to that property appear on the right
  • Delete all the views related to the property individually (details in next section).

Deleting a View (profile)

Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.

  • Choose the profile you want to delete

Choose profile

  • Click View Settings

Settings

  • Click on delete View (Bottom right)

Delete the view

  • Click Confirm, and that view will be deleted. If there is only a single view in the property, that property gets automatically deleted.

I want to keep the data, but not see them in the list

Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.

Use another account.

  1. Say, your primary account is A, and you make another account B.
  2. Make B an administrator from A
  3. Remove A

Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.


Previous Answer :

These are the steps to delete a profile from Google Support page :

Delete profiles

Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.

To delete a profile:

  1. Click the Admin tab at the top right of any Analytics page.
  2. Click the account that contains the profile you want to delete.
  3. Click the web property from which you want to delete the profile.
  4. Use the Profile menu to select the profile.
  5. Click the Profile Settings tab.
  6. Click Delete this profile at the bottom of the page.
  7. Click Delete in the confirmation message.

Rails DateTime.now without Time

What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Replace input type=file by an image

You can put an image instead, and do it like this:

HTML:

<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1"  name="file1" style="display:none" />

JQuery:

$("#upfile1").click(function () {
    $("#file1").trigger('click');
});

CAVEAT: In IE9 and IE10 if you trigger the onclick in a file input via javascript the form gets flagged as 'dangerous' and cannot be submmited with javascript, no sure if it can be submitted traditionaly.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Example with glob() function. It will delete all files and folders recursively, including files that starts with dot.

delete_all( 'folder' );

function delete_all( $item ) {
    if ( is_dir( $item ) ) {
        array_map( 'delete_all', array_diff( glob( "$item/{,.}*", GLOB_BRACE ), array( "$item/.", "$item/.." ) ) );
        rmdir( $item );
    } else {
        unlink( $item );
    }
};

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

How to determine if a number is odd in JavaScript

function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }

MVC DateTime binding with incorrect date format

I set CurrentCulture and CurrentUICulture my custom base controller

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
    }

How to set back button text in Swift

If you are using xib file for view controller then do this in your view controller class.

class AboutUsViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    edgesForExtendedLayout = []
    setUpNavBar()
}

func setUpNavBar(){
    //For title in navigation bar
    self.navigationController?.view.backgroundColor = UIColor.white
    self.navigationController?.view.tintColor = UIColor.orange
    self.navigationItem.title = "About Us"

    //For back button in navigation bar
    let backButton = UIBarButtonItem()
    backButton.title = "Back"
    self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}

}

The result will be:

enter image description here

How do I declare an array variable in VBA?

As pointed out by others, your problem is that you have not declared an array

Below I've tried to recreate your program so that it works as you intended. I tried to leave as much as possible as it was (such as leaving your array as a variant)

Public Sub Testprog()
    '"test()" is an array, "test" is not
    Dim test() As Variant
    'I am assuming that iCounter is the array size
    Dim iCounter As Integer

    '"On Error Resume Next" just makes us skip over a section that throws the error
    On Error Resume Next

    'if test() has not been assigned a UBound or LBound yet, calling either will throw an error
    '   without an LBound and UBound an array won't hold anything (we will assign them later)

    'Array size can be determined by (UBound(test) - LBound(test)) + 1
    If (UBound(test) - LBound(test)) + 1 > 0 Then
        iCounter = (UBound(test) - LBound(test)) + 1

        'So that we don't run the code that deals with UBound(test) throwing an error
        Exit Sub
    End If

    'All the code below here will run if UBound(test)/LBound(test) threw an error
    iCounter = 0

    'This makes LBound(test) = 0
    '   and UBound(test) = iCounter where iCounter is 0
    '   Which gives us one element at test(0)
    ReDim Preserve test(0 To iCounter)

    test(iCounter) = "test"
End Sub

How to update values in a specific row in a Python Pandas DataFrame?

There are probably a few ways to do this, but one approach would be to merge the two dataframes together on the filename/m column, then populate the column 'n' from the right dataframe if a match was found. The n_x, n_y in the code refer to the left/right dataframes in the merge.

In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])

In[101] : df
Out[101]: 
    filename   m   n_x  n_y
0  test0.dat  12  None  NaN
1  test2.dat  13  None   16

In[102] : df['n'] = df['n_y'].fillna(df['n_x'])

In[103] : df = df.drop(['n_x','n_y'], axis=1)

In[104] : df
Out[104]: 
    filename   m     n
0  test0.dat  12  None
1  test2.dat  13    16

How to test valid UUID/GUID?

regex to the rescue

/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test('01234567-9ABC-DEF0-1234-56789ABCDEF0');

or with brackets

/^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}??\}?$/

HTTP status code for update and delete?

RFC 2616 describes which status codes to use.

And no, it's not always 200.

Django Multiple Choice Field / Checkbox Select Multiple

The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).

You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.

There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField.

In LINQ, select all values of property X where X != null

There is no way to skip a check if it exists.

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.

Count number of tables in Oracle

REM setting current_schema is required as the 2nd query depends on the current user referred in the session

ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;

SELECT table_name,
         TO_NUMBER (
            EXTRACTVALUE (
               xmltype (
                  DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
               '/ROWSET/ROW/C'))
            COUNT
    FROM dba_tables
   WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;

How to overlay one div over another div

Here follows a simple solution 100% based on CSS. The "secret" is to use the display: inline-block in the wrapper element. The vertical-align: bottom in the image is a hack to overcome the 4px padding that some browsers add after the element.

Advice: if the element before the wrapper is inline they can end up nested. In this case you can "wrap the wrapper" inside a container with display: block - usually a good and old div.

_x000D_
_x000D_
.wrapper {_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.hover {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: rgba(0, 188, 212, 0);_x000D_
    transition: background-color 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover {_x000D_
    background-color: rgba(0, 188, 212, 0.8);_x000D_
    // You can tweak with other background properties too (ie: background-image)..._x000D_
}_x000D_
_x000D_
img {_x000D_
    vertical-align: bottom;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="hover"></div>_x000D_
    <img src="http://placehold.it/450x250" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

By default, the Command Prompt is connected to System32. Run a 64-bit command prompt, i.e., C:\WINDOWS\SYSWOW64\CMD.EXE. In that, compile and run your java application.

TypeScript, Looping through a dictionary

To loop over the key/values, use a for in loop:

for (let key in myDictionary) {
    let value = myDictionary[key];
    // Use `key` and `value`
}

Open file in a relative location in Python

This code works fine:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

Node Sass couldn't find a binding for your current environment

Windows 10 This was a fun one for me... In order to resolve it I had to do all of the following.. 1.) Apparently node-sass isn't supported by some of the more recent versions of Node.js so I had to Uninstall Node-v 12.14.1, and delete the nodejs directory in C:/Program Files. 2.) Reinstall a earlier version of Node (for me 10.16.2 worked). NOTE: I had initially downloaded the x86 version so if your System is x64 download the x64 verison... 3.) From here I had to delete my entire project and re-clone it. After this things ran fine.

How can I create a dynamic button click event on a dynamic button?

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};

log4j vs logback

Your decision should be based on

  • your actual need for these "more features"; and
  • your expected cost of implementing the change.

You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."

If your application requires a very sophisticated logging framework, you may want to consider why.

How to combine multiple inline style objects?

So basically I'm looking at this in the wrong way. From what I see, this is not a React specific question, more of a JavaScript question in how do I combine two JavaScript objects together (without clobbering similarly named properties).

In this StackOverflow answer it explains it. How can I merge properties of two JavaScript objects dynamically?

In jQuery I can use the extend method.

Android Studio drawable folders

This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/

All the best.

Import pfx file into particular certificate store from command line

In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.

Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""

Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""

For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]

How to stop (and restart) the Rails Server?

Now in rails 5 yu can do:

rails restart

This print by rails --tasks

Restart app by touching tmp/restart.txt

I think that is usefully if you run rails as a demon

How do I monitor all incoming http requests?

You might consider running Fiddler as a reverse proxy, you should be able to get clients to connect to Fiddler's address and then forward the requests from Fiddler to your application.

This will require either a bit of port manipulation or client config, depending on what's easier based on your requirements.

Details of how to do it are here: http://www.fiddler2.com/Fiddler/Help/ReverseProxy.asp

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

align images side by side in html

Try using this format

<figure>
   <img src="img" alt="The Pulpit Rock" width="304" height="228">
   <figcaption>Fig1. - A view of the pulpit rock in Norway.</figcaption>
</figure>

This will give you a real caption (just add the 2nd and 3rd imgs using Float:left like others suggested)

How to remove a field completely from a MongoDB document?

{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } }

Ans:

db.tablename.remove({'tags.words':['abc','123']})

Html.HiddenFor value property not getting set

Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.

How to get rid of underline for Link component of React Router?

<Link to="/page">
    <Box sx={{ display: 'inline-block' }}>
        <PLink variant="primary">Page</PLink>
    </Box>
</Link>

In some cases when using another component inside the Gatsby <Link> component, adding a div with display: 'inline-block' around the inner component, prevents underlining (of 'Page' in the example).

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

Best way to remove from NSMutableArray while iterating?

Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes.

Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.

under Xcode 6 this works

NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];

    for (id object in array)
    {
        if ( [object isNotEqualTo:@"whatever"]) {
           [itemsToKeep addObject:object ];
        }
    }
    array = nil;
    array = [[NSMutableArray alloc]initWithArray:itemsToKeep];

How to compile .c file with OpenSSL includes?

From the openssl.pc file

prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: OpenSSL
Description: Secure Sockets Layer and cryptography libraries and tools
Version: 0.9.8g
Requires:
Libs: -L${libdir} -lssl -lcrypto
Libs.private: -ldl -Wl,-Bsymbolic-functions -lz
Cflags: -I${includedir}

You can note the Include directory path and the Libs path from this. Now your prefix for the include files is /home/username/Programming . Hence your include file option should be -I//home/username/Programming.

(Yes i got it from the comments above)

This is just to remove logs regarding the headers. You may as well provide -L<Lib path> option for linking with the -lcrypto library.

Open soft keyboard programmatically

There are already too many answers but nothing worked for me apart from this

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

I used showSoftInput with SHOW_FORCED

And my activity has

 android:windowSoftInputMode="stateVisible|adjustResize"

hope this helps someone

Why can't overriding methods throw exceptions broader than the overridden method?

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

Example:

class Super {
    public void throwCheckedExceptionMethod() throws IOException {
        FileReader r = new FileReader(new File("aFile.txt"));
        r.close();
    }
}

class Sub extends Super {    
    @Override
    public void throwCheckedExceptionMethod() throws FileNotFoundException {
        // FileNotFoundException extends IOException
        FileReader r = new FileReader(new File("afile.txt"));
        try {
            // close() method throws IOException (that is unhandled)
            r.close();
        } catch (IOException e) {
        }
    }
}

class Sub2 extends Sub {
    @Override
    public void throwCheckedExceptionMethod() {
        // Overriding method can throw no exception
    }
}

How to copy file from HDFS to the local file system

  1. bin/hadoop fs -get /hdfs/source/path /localfs/destination/path
  2. bin/hadoop fs -copyToLocal /hdfs/source/path /localfs/destination/path
  3. Point your web browser to HDFS WEBUI(namenode_machine:50070), browse to the file you intend to copy, scroll down the page and click on download the file.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

Setting DEBUG = False causes 500 Error

I have the similar issue, in my case it was caused by having a Commented script inside the body tag.

<!--<script>  </script>-->

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

Saving timestamp in mysql table using php

This should do it:

  $time = new DateTime; 

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

Set ImageView width and height programmatically?

In the scenario where the widget size needs to be set programmatically, ensure the below rules.

  1. Set LayoutParam for the Layout in which you are adding that view. In my case I am adding to TableRow so I had to do TableRow.LayoutParams
  2. Follow this code

final float scale = getResources().getDisplayMetrics().density; int dpWidthInPx = (int) (17 * scale); int dpHeightInPx = (int) (17 * scale);

TableRow.LayoutParams deletelayoutParams = new TableRow.LayoutParams(dpWidthInPx, dpHeightInPx); button.setLayoutParams(deletelayoutParams); tableRow.addView(button, 1);

Toggle input disabled attribute using jQuery


    $('#checkbox').click(function(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

When to use "new" and when not to, in C++?

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

Android - How to get application name? (Not package name)

From any Context use:

getApplicationInfo().loadLabel(getPackageManager()).toString();

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

Pagination using MySQL LIMIT, OFFSET

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.

It is better to remember where you left off.

How to merge two sorted arrays into a sorted array?

I think introducing the skip list for the larger sorted array can reduce the number of comparisons and can speed up the process of copying into the third array. This can be good if the array is too huge.

php stdClass to array

Here is a version of Carlo's answer that can be used in a class:

class Formatter
{
    public function objectToArray($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map(array($this, 'objectToArray'), $data);
        }

        return $data;
    }
}

How to create a jar with external libraries included in Eclipse?

While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.

You then run the jar directly by java -jar example.jar.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

Note for Android 9 (Pie).

Additionally to useLibrary 'org.apache.http.legacy' you have to add in AndroidManifest.xml:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Source: https://developer.android.com/about/versions/pie/android-9.0-changes-28

Find duplicate lines in a file and count how many time each line was duplicated?

To find and count duplicate lines in multiple files, you can try the following command:

sort <files> | uniq -c | sort -nr

or:

cat <files> | sort | uniq -c | sort -nr

Open URL in new window with JavaScript

Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.

window.open('https://play.google.com/store/apps/details?id=com.drishya');

How do I import a sql data file into SQL Server?

A .sql file is a set of commands that can be executed against the SQL server.

Sometimes the .sql file will specify the database, other times you may need to specify this.

You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.

See the other answers if you want to plunge ahead.

Very simple C# CSV reader

First of all need to understand what is CSV and how to write it.

(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)

  1. Every next string ( /r/n ) is next "table" row.
  2. "Table" cells is separated by some delimiter symbol.
  3. As delimiter can be used ANY symbol. Often this is \t or ,.
  4. Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)
  5. Each cell possibly can contains /r/n symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)

Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO library. Using this simple class you will be able to work with CSV like with 2 dimensions array.

Simple example of using my library:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");

You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter

This library code is really fast in work and source code is really short.

PS: In the same time this solution will not work for unity.

PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.

Python - Get path of root project structure

A standard way to achieve this would be to use the pkg_resources module which is part of the setuptools package. setuptools is used to create an install-able python package.

You can use pkg_resources to return the contents of your desired file as a string and you can use pkg_resources to get the actual path of the desired file on your system.

Let's say that you have a package called stackoverflow.

stackoverflow/
|-- app
|   `-- __init__.py
`-- resources
    |-- bands
    |   |-- Dream\ Theater
    |   |-- __init__.py
    |   |-- King's\ X
    |   |-- Megadeth
    |   `-- Rush
    `-- __init__.py

3 directories, 7 files

Now let's say that you want to access the file Rush from a module app.run. Use pkg_resources.resouces_filename to get the path to Rush and pkg_resources.resource_string to get the contents of Rush; thusly:

import pkg_resources

if __name__ == "__main__":
    print pkg_resources.resource_filename('resources.bands', 'Rush')
    print pkg_resources.resource_string('resources.bands', 'Rush')

The output:

/home/sri/workspace/stackoverflow/resources/bands/Rush
Base: Geddy Lee
Vocals: Geddy Lee
Guitar: Alex Lifeson
Drums: Neil Peart

This works for all packages in your python path. So if you want to know where lxml.etree exists on your system:

import pkg_resources

if __name__ == "__main__":
    print pkg_resources.resource_filename('lxml', 'etree')

output:

/usr/lib64/python2.7/site-packages/lxml/etree

The point is that you can use this standard method to access files that are installed on your system (e.g pip install xxx or yum -y install python-xxx) and files that are within the module that you're currently working on.

Is #pragma once a safe include guard?

Additional note to the people thinking that an automatic one-time-only inclusion of header files is always desired: I build code generators using double or multiple inclusion of header files since decades. Especially for generation of protocol library stubs I find it very comfortable to have a extremely portable and powerful code generator with no additional tools and languages. I'm not the only developer using this scheme as this blogs X-Macros show. This wouldn't be possible to do without the missing automatic guarding.

Taking screenshot on Emulator from Android Studio

Starting with Android Studio 2.0 you can do it with the new emulator:

New Android Emulator from Android Studio 2.0

Just click 3 "Take Screenshot". Standard location is the desktop.

Or

  1. Select "More"
  2. Under "Settings", specify the location for your screenshot
  3. Take your screenshot

UPDATE 22/07/2020

If you keep the emulator in Android Studio as possible since Android Studio 4.1 click here to save the screenshot in your standard location:

enter image description here

mingw-w64 threads: posix vs win32

Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.

Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:

As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the CreateThread function will not setup the stack correctly for the C runtime library. You should use _beginthreadex instead, which is (almost) completely compatible with CreateThread.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

if you wanna remove attributes for all files in all folders on whole flash drive do this:

attrib -r -s -h /S /D

this command will remove attrubutes for all files folders and subfolders:

-read only -system file -is hidden -Processes matching files and all subfolders. -Processes folders as well

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

no pg_hba.conf entry for host

Verify the postgres connection hostname/address in pgadmin and use the same in your connection parameter.

DBI connect('database=chaosLRdb;host="keep what is mentioned" ;port=5433','postgres',...)

What does %5B and %5D in POST requests stand for?

As per this answer over here: str='foo%20%5B12%5D' encodes foo [12]:

%20 is space
%5B is '['
and %5D is ']'

This is called percent encoding and is used in encoding special characters in the url parameter values.

EDIT By the way as I was reading https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI#Description, it just occurred to me why so many people make the same search. See the note on the bottom of the page:

Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.

function fixedEncodeURI (str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}

Hopefully this will help people sort out their problems when they stumble upon this question.

How to map and remove nil values in Ruby

You could use compact:

[1, nil, 3, nil, nil].compact
=> [1, 3] 

I'd like to remind people that if you're getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you've got code smell and need to rethink your logic.

For instance, if you're doing something that does this:

[1,2,3].map{ |i|
  if i % 2 == 0
    i
  end
}
# => [nil, 2, nil]

Then don't. Instead, prior to the map, reject the stuff you don't want or select what you do want:

[1,2,3].select{ |i| i % 2 == 0 }.map{ |i|
  i
}
# => [2]

I consider using compact to clean up a mess as a last-ditch effort to get rid of things we didn't handle correctly, usually because we didn't know what was coming at us. We should always know what sort of data is being thrown around in our program; Unexpected/unknown data is bad. Anytime I see nils in an array I'm working on, I dig into why they exist, and see if I can improve the code generating the array, rather than allow Ruby to waste time and memory generating nils then sifting through the array to remove them later.

'Just my $%0.2f.' % [2.to_f/100]

How to select a node of treeview programmatically in c#?

yourNode.Toggle(); //use that function on your node, it toggles it

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Is there a way to programmatically scroll a scroll view to a specific edit text?

reference : https://stackoverflow.com/a/6438240/2624806

Following worked far better.

mObservableScrollView.post(new Runnable() {
            public void run() { 
                mObservableScrollView.fullScroll([View_FOCUS][1]); 
            }
        });

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

Add borders to cells in POI generated Excel File

If you're using the org.apache.poi.ss.usermodel (not HSSF or XSSF) you can use:

style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);

all the border styles are here at the apache documentation

is there a post render callback for Angular JS directive?

I had the same problem and I believe the answer really is no. See Miško's comment and some discussion in the group.

Angular can track that all of the function calls it makes to manipulate the DOM are complete, but since those functions could trigger async logic that's still updating the DOM after they return, Angular couldn't be expected to know about it. Any callback Angular gives might work sometimes, but wouldn't be safe to rely on.

We solved this heuristically with a setTimeout, as you did.

(Please keep in mind that not everyone agrees with me - you should read the comments on the links above and see what you think.)

Difference between 2 dates in SQLite

If you want time in 00:00 format: I solved it like that:

select strftime('%H:%M',CAST ((julianday(FinishTime) - julianday(StartTime)) AS REAL),'12:00') from something

jQuery & CSS - Remove/Add display:none

To hide the div

$('.news').hide();

or

$('.news').css('display','none');

and to show the div:

$('.news').show();

or

$('.news').css('display','block');

How to copy selected lines to clipboard in vim

If vim is compiled with clipboard support, then you can use "*y meaning: yank visually selected text into register * ('*' is for clipboard)

If there is no clipboard support, I think only other way is to use Ctrl+Insert after visually selecting the text in vim.

How to get child element by class name?

Use YAHOO.util.Dom.getElementsByClassName() from here.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem when I have update data while the RecyclerView is scrolling. And I fixed it with the following solution:

  1. Stop scroll our RecyclerView before update data.
  2. Custom layout manager likes with the preceding answer.
  3. Use DiffUtils to ensure updating data is correct.

Load a HTML page within another HTML page

If you are looking for a popup in the page, that is not a new browser window, then I would take a look at the various "LightBox" implementations in Javascript.

Dark theme in Netbeans 7 or 8

u can use Dark theme Plugin

Tools > Plugin > Dark theme and Feel

and it is work :)

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

PDO Prepared Inserts multiple rows in single query

Here is my simple approach.

    $values = array();
    foreach($workouts_id as $value){
      $_value = "(".$value.",".$plan_id.")";
      array_push($values,$_value);
    }
    $values_ = implode(",",$values);

    $sql = "INSERT INTO plan_days(id,name) VALUES" . $values_."";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();

Select Multiple Fields from List in Linq

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

JAXB :Need Namespace Prefix to all the elements

To specify more than one namespace to provide prefixes, use something like:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "urn:oecd:ties:cbc:v1", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
    xmlns ={@XmlNs(prefix="cbc", namespaceURI="urn:oecd:ties:cbc:v1"), 
            @XmlNs(prefix="iso", namespaceURI="urn:oecd:ties:isocbctypes:v1"),
            @XmlNs(prefix="stf", namespaceURI="urn:oecd:ties:stf:v4")})

... in package-info.java

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

Try to open it in an incognito window. I hope this will help. Alternatively, you could modify application/.htaccess like so:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

Export DataTable to Excel File

Please try this, this will export your data table data's faster to excel.

Note: Range "FW", that I have hard coded is because I had 179 columns.

public void UpdateExcelApplication(SqlDataTable dataTable)
    {
        var objects = new string[dataTable.Rows.Count, dataTable.Columns.Count];

        var rowIndex = 0;

        foreach (DataRow row in dataTable.Rows)
        {
            var colIndex = 0;

            foreach (DataColumn column in dataTable.Columns)
            {
                objects[rowIndex, colIndex++] = Convert.ToString(row[column]);
            }

            rowIndex++;
        }

        var range = this.workSheet.Range[$"A3:FW{dataTable.Rows.Count + 2}"];
        range.Value = objects;

        this.workSheet.Columns.AutoFit();
        this.workSheet.Rows.AutoFit();
    }

java.io.IOException: Invalid Keystore format

go to build clean the project then rebuild your project it worked for me.

Corrupted Access .accdb file: "Unrecognized Database Format"

WE had this problem on one machine and not another...the solution is to look in control panel at the VERSION of the Access Database Engine 2007 component. If it is version 12.0.45, you need to run the service pack 3 http://www.microsoft.com/en-us/download/confirmation.aspx?id=27835

The above link will install version 12.0.66...and this fixes the problem...thought I would post it since I haven't seen this solution on any other forum.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Check if element found in array c++

Here is a simple generic C++11 function contains which works for both arrays and containers:

using namespace std;

template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };

Simple usage contains(arr, el) is somewhat similar to in keyword semantics in Python.

Here is a complete demo:

#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>

template<typename C, typename T>
bool contains(C&& c, T e) { 
    return std::find(std::begin(c), std::end(c), e) != std::end(c);
};

template<typename C, typename T>
void check(C&& c, T e) {
    std::cout << e << (contains(c,e) ? "" : " not") <<  " found\n";
}

int main() {
    int a[] = { 10, 15, 20 };
    std::array<int, 3> b { 10, 10, 10 };
    std::vector<int> v { 10, 20, 30 };
    std::string s { "Hello, Stack Overflow" };
    
    check(a, 10);
    check(b, 15);
    check(v, 20);
    check(s, 'Z');

    return 0;
}

Output:

10 found
15 not found
20 found
Z not found

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

syntax error when using command line in python

Come out of the "python interpreter."

  1. Check out your PATH variable c:\python27
  2. cd and your file location. 3.Now type Python yourfilename.py.

I hope this should work

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

How to import Maven dependency in Android Studio/IntelliJ?

  1. Uncheck "Offline work" in File>Settings>Gradle>Global Gradle Settings
  2. Resync the project, for example by restarting the Android Studio
  3. Once synced, you can check the option again to work offline.

Foreign key referencing a 2 columns primary key in SQL Server

Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:

ALTER TABLE dbo.Content
   ADD CONSTRAINT FK_Content_Libraries
   FOREIGN KEY(LibraryID, Application)
   REFERENCES dbo.Libraries(ID, Application)

Is that what you're using?? If (ID, Application) is indeed the primary key on dbo.Libraries, this statement should definitely work.

Luk: just to check - can you run this statement in your database and report back what the output is??

SELECT
    tc.TABLE_NAME,
    tc.CONSTRAINT_NAME, 
    ccu.COLUMN_NAME
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
      ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
    tc.TABLE_NAME IN ('Libraries', 'Content')

How to use getJSON, sending data with post method?

This is my "one-line" solution:

$.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }

In order to use jsonp, and POST method, this function adds the "callback" GET parameter to the URL. This is the way to use it:

$.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
   console.log(data.name);
});

The server must be prepared to handle the callback GET parameter and return the json string as:

jsonp000000 ({"name":"John", "age": 25});

in which "jsonp000000" is the callback GET value.

In PHP the implementation would be like:

print_r($_GET['callback']."(".json_encode($myarr).");");

I made some cross-domain tests and it seems to work. Still need more testing though.

JQuery .hasClass for multiple values in an if statement

Try this:

if ($('html').hasClass('class1 class2')) {

// do stuff 

}

How to edit data in result grid in SQL Server Management Studio

  1. To be clear: The option "Value for Edit Top Rows command" has nothing to do with the fact if a result set is editable or not. It is just a way to limit the result set.

  2. Editing the result set of a query based on one and only one table is obviously always possible.

  3. The result set of a query based on more than one table is under following condition possible: You can edit the fields in the result set at once if they belong to one and only one based table in the query! If the fields are Primary Key, then you have to fulfill refresh/"Execute SQL" (Ctrl+R) after each row update, in order to be able to edit a row next time. If the fields are not Primary Key, then you do not need to fulfill refresh/"Execute SQL" (Ctrl+R).

I have tested it on SQL Server 2008 - 2016!

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

C - The %x format specifier

%08x means that every number should be printed at least 8 characters wide with filling all missing digits with zeros, e.g. for '1' output will be 00000001

Use jQuery to change an HTML tag?

Is there a specific reason that you need to change the tag? If you just want to make the text bigger, changing the p tag's CSS class would be a better way to go about that.

Something like this:

$('#change').click(function(){
  $('p').addClass('emphasis');
});

How to increase memory limit for PHP over 2GB?

I would suggest you are looking at the problem in the wrong light. The questtion should be 'what am i doing that needs 2G memory inside a apache process with Php via apache module and is this tool set best suited for the job?'

Yes you can strap a rocket onto a ford pinto, but it's probably not the right solution.

Regardless, I'll provide the rocket if you really need it... you can add to the top of the script.

ini_set('memory_limit','2048M');

This will set it for just the script. You will still need to tell apache to allow that much for a php script (I think).

copying all contents of folder to another folder using batch file?

Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:

robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT

Here:

/COPYALL copies all file information
/E copies subdirectories including empty directories
/IS includes the same files
/IT includes modified files with the same name

For more parameters see the official documentation: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

Note: it can be necessary to run the command as administrator, because of the argument /COPYALL. If you can't: just get rid of it.

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Upload failed You need to use a different version code for your APK because you already have one with version code 2

In Android Studio 1.1.0, change versionCode in build.gradle for Module: app and don't necessarily change versionName:

android {
...
    defaultConfig {
...
        versionCode 3
        versionName "1.0"
    }
...
}

Python division

You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

>>> 1 / 2
0

You should make one of them a float:

>>> float(10 - 20) / (100 - 10)
-0.1111111111111111

or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.

>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111

List of <p:ajax> events

You might want to look at "JavaScript HTML DOM Events" for a general overview of events:

http://www.w3schools.com/jsref/dom_obj_event.asp

PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:

http://api.jquery.com/category/events/

http://api.jquery.com/category/events/form-events/

http://api.jquery.com/category/events/keyboard-events/

http://api.jquery.com/category/events/mouse-events/

http://api.jquery.com/category/events/browser-events/

Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).

Mouse Events

(Any HTML element can receive these events.)

click

dblclick

mousedown

mousemove

mouseover

mouseout

mouseup

Keyboard Events

(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)

keydown

keypress

keyup

Form Events

blur (In recent browsers, the domain of the event has been extended to include all element types.)

change (This event is limited to <input> elements, <textarea> boxes and <select> elements.)

focus (This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)

select (This event is limited to <input type="text"> fields and <textarea> boxes.)

submit (It can only be attached to <form> elements.)

Git: How to reset a remote Git repository to remove all commits?

First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:

$ git push origin +master

And optionally delete all other branches both locally and remotely:

$ git push origin :<branch>
$ git branch -d <branch>

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

Link to download apache http server for 64bit windows.

you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down

ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP

What is the best way to ensure only one instance of a Bash script is running?

I'd also recommend looking at chpst (part of runit):

chpst -L /tmp/your-lockfile.loc ./script.name.sh

Node.js fs.readdir recursive directory search

qwtel's answer variant, in TypeScript

import { resolve } from 'path';
import { readdir } from 'fs/promises';

async function* getFiles(dir: string): AsyncGenerator<string> {
    const entries = await readdir(dir, { withFileTypes: true });
    for (const entry of entries) {
        const res = resolve(dir, entry.name);
        if (entry.isDirectory()) {
            yield* getFiles(res);
        } else {
            yield res;
        }
    }
}

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

How to search JSON data in MySQL?

I think...

Search partial value:

SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])*key_word([^"])*"';

Search exact word:

SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

Element count of an array in C++

No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type. In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.

Here is an example of how to use this correctly:

int nonDynamicArray[ 4 ];

#define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )

I'll go one further here to show when to use this properly. You won't use it very often. It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later. It is a construct that is primarily useful for maintenance. The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add more commands to later. In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:

char        *commands[] = {  // <--- note intentional lack of explicit array size
    "open",
    "close",
    "abort",
    "crash"
};

#define kCommandsCount  ( sizeof(commands) / sizeof(commands[ 0 ]) )

void processCommand( char *command ) {
    int i;

    for ( i = 0; i < kCommandsCount; ++i ) {
        // if command == commands[ i ] do something (be sure to compare full string)
    }
}

How to create a hidden <img> in JavaScript?

I'm not sure I understand your question. But there are two approaches to making the image invisible...

Pure HTML

<img src="a.gif" style="display: none;" />

Or...

HTML + Javascript

<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>

<img id="myImage" src="a.gif" />

Disabling Chrome Autofill

If you are implementing a search box feature, try setting the type attribute to search as follows:

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

This is working for me on Chrome v48 and appears to be legitimate markup:

https://www.w3.org/wiki/HTML/Elements/input/search

AutoComplete TextBox in WPF

I know this is a very old question but I want to add an answer I have come up with.

First you need a handler for your normal TextChanged event handler for the TextBox:

private bool InProg;
internal void TBTextChanged(object sender, TextChangedEventArgs e)
            {
            var change = e.Changes.FirstOrDefault();
            if ( !InProg )
                {
                InProg = true;
                var culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
                var source = ( (TextBox)sender );
                    if ( ( ( change.AddedLength - change.RemovedLength ) > 0 || source.Text.Length > 0 ) && !DelKeyPressed )
                        {
                         if ( Files.Where(x => x.IndexOf(source.Text, StringComparison.CurrentCultureIgnoreCase) == 0 ).Count() > 0 )
                            {
                            var _appendtxt = Files.FirstOrDefault(ap => ( culture.CompareInfo.IndexOf(ap, source.Text, CompareOptions.IgnoreCase) == 0 ));
                            _appendtxt = _appendtxt.Remove(0, change.Offset + 1);
                            source.Text += _appendtxt;
                            source.SelectionStart = change.Offset + 1;
                            source.SelectionLength = source.Text.Length;
                            }
                        }
                InProg = false;
                }
            }

Then make a simple PreviewKeyDown handler:

    private static bool DelKeyPressed;
    internal static void DelPressed(object sender, KeyEventArgs e)
    { if ( e.Key == Key.Back ) { DelKeyPressed = true; } else { DelKeyPressed = false; } }

In this example "Files" is a list of directory names created on application startup.

Then just attach the handlers:

public class YourClass
  {
  public YourClass()
    {
    YourTextbox.PreviewKeyDown += DelPressed;
    YourTextbox.TextChanged += TBTextChanged;
    }
  }

With this whatever you choose to put in the List will be used for the autocomplete box. This may not be a great option if you expect to have an enormous list for the autocomplete but in my app it only ever sees 20-50 items so it cycles through very quick.

How to "grep" out specific line ranges of a file

Put this in a file and make it executable:

#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find start pattern!" 1>&2
    exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find end pattern!" 1>&2
    exit 1
fi

stop=$(( $stop + $start - 1))

sed "$start,$stop!d" < $3

Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):

  1. Starting grep pattern
  2. Stopping grep pattern
  3. File path

To use with your example, use arguments: 1234 5555 myfile.txt

Includes lines with starting and stopping pattern.

What is the difference between a stored procedure and a view?

  1. A VIEW is a dynamic query where you can use a "WHERE"-Clause
  2. A stored procedure is a fixed data selection, which returns a predefined result
  3. Nor a view, nor a stored procedure allocate memory. Only a materialized view
  4. A TABLE is just one ENTITY, a view can collect data from different ENTITIES or TABLES

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

How to write super-fast file-streaming code in C#?

No one suggests threading? Writing the smaller files looks like text book example of where threads are useful. Set up a bunch of threads to create the smaller files. this way, you can create them all in parallel and you don't need to wait for each one to finish. My assumption is that creating the files(disk operation) will take WAY longer than splitting up the data. and of course you should verify first that a sequential approach is not adequate.

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

Node.js Web Application examples/tutorials

The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.

screencast

How do I calculate a trendline for a graph?

Thank You so much for the solution, I was scratching my head.
Here's how I applied the solution in Excel.
I successfully used the two functions given by MUHD in Excel:
a = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
b = sum(y)/n - b(sum(x)/n)
(careful my a and b are the b and a in MUHD's solution).

- Made 4 columns, for example:
NB: my values y values are in B3:B17, so I have n=15;
my x values are 1,2,3,4...15.
1. Column B: Known x's
2. Column C: Known y's
3. Column D: The computed trend line
4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17)
5. Column F: x squared values
I then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares.
To compute a, enter the followin formula in any cell (F35 for me):
F35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15)
To compute b (in F36 for me):
F36=C18/15-F35*(B18/15)
Column D values, computing the trend line according to the y = ax + b:
D3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me).

Select the column datas (C2:D17) to make the graph.
HTH.

Creating and Update Laravel Eloquent

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link

Safari 3rd party cookie iframe trick no longer working?

I had the same problem and today I found a fix that works fine for me. If the user agent contains Safari and no cookies are set, I redirect the user to the OAuth Dialog:

<?php if ( ! count($_COOKIE) > 0 && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { ?>
<script type="text/javascript">
    window.top.location.href = 'https://www.facebook.com/dialog/oauth/?client_id=APP_ID&redirect_uri=MY_TAB_URL&scope=SCOPE';
</script>
<?php } ?>

After authentication and asking for permissions the OAuth Dialog will redirect to my URI in the top location. So setting cookies is possible. For all of our canvas and page tab apps I have already included the following script:

<script type="text/javascript">
    if (top.location.href==location.href) top.location.href = 'MY_TAB_URL';
</script>

So the user will be redirected again to the Facebook page tab with a valid cookie already set and the signed request is posted again.

How to view the assembly behind the code using Visual C++?

If you are talking about debugging to see the assembly code, the easiest way is Debug->Windows->Disassembly (or Alt-8). This will let you step into a called function and stay in Disassembly.

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

What's the reason I can't create generic array types in Java?

The reason this is impossible is that Java implements its Generics purely on the compiler level, and there is only one class file generated for each class. This is called Type Erasure.

At runtime, the compiled class needs to handle all of its uses with the same bytecode. So, new T[capacity] would have absolutely no idea what type needs to be instantiated.

PHP Call to undefined function

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload['helper'] = array('common','security','url');

common is the name of my controller.

Simple two column html layout without using tables

Well, if you want the super easiest method, just put

<div class="left">left</div>
<div class="right">right</div>

.left {
    float: left;    
}

though you may need more than that depending on what other layout requirements you have.

Setting equal heights for div's with jQuery

Here is what worked for me. It applies the same height to each column despite their parent div.

$(document).ready(function () {    
    var $sameHeightDivs = $('.column');
    var maxHeight = 0;
    $sameHeightDivs.each(function() {
        maxHeight = Math.max(maxHeight, $(this).outerHeight());
    });
    $sameHeightDivs.css({ height: maxHeight + 'px' });
});

Source

Gaussian fit for Python

Here is corrected code:

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

result:
enter image description here

Fastest check if row exists in PostgreSQL

SELECT 1 FROM user_right where userid = ? LIMIT 1

If your resultset contains a row then you do not have to insert. Otherwise insert your records.

How to negate 'isblank' function

The solution is isblank(cell)=false

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I successfully put a portable version of libreoffice on my host's webserver, which I call with PHP to do a commandline conversion from .docx, etc. to pdf. on the fly. I do not have admin rights on my host's webserver. Here is my blog post of what I did:

http://geekswithblogs.net/robertphyatt/archive/2011/11/19/converting-.docx-to-pdf-or-.doc-to-pdf-or-.doc.aspx

Yay! Convert directly from .docx or .odt to .pdf using PHP with LibreOffice (OpenOffice's successor)!

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

What is the proper way to check and uncheck a checkbox in HTML5?

<form name="myForm" method="post">
  <p>Activity</p> 
  skiing:  <input type="checkbox" name="activity" value="skiing"  checked="yes" /><br /> 
  skating: <input type="checkbox" name="activity" value="skating" /><br /> 
  running: <input type="checkbox" name="activity" value="running" /><br /> 
  hiking:  <input type="checkbox" name="activity" value="hiking"  checked="yes" />
</form>

How do you Encrypt and Decrypt a PHP String?

Below code work in php for all string with special character

   // Encrypt text --

    $token = "9611222007552";

      $cipher_method = 'aes-128-ctr';
      $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);  
      $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));  
      $crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
    echo    $crypted_token;
    //unset($token, $cipher_method, $enc_key, $enc_iv);

    // Decrypt text  -- 

    list($crypted_token, $enc_iv) = explode("::", $crypted_token);  
      $cipher_method = 'aes-128-ctr';
      $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
      $token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
    echo   $token;
    //unset($crypted_token, $cipher_method, $enc_key, $enc_iv);

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Generate JSON string from NSDictionary in iOS

Here is the Swift 4 version

extension NSDictionary{

func toString() throws -> String? {
    do {
        let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        return String(data: data, encoding: .utf8)
    }
    catch (let error){
        throw error
    }
}

}

Usage Example

do{
    let jsonString = try dic.toString()
    }
    catch( let error){
        print(error.localizedDescription)
    }

Or if you are sure it is valid dictionary then you can use

let jsonString = try? dic.toString()

How to sign in kubernetes dashboard?

The skip login has been disabled by default due to security issues. https://github.com/kubernetes/dashboard/issues/2672

in your dashboard yaml add this arg

- --enable-skip-login

to get it back

Passing by reference in C

Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.

IntelliJ cannot find any declarations

I too faced this issue. I've tried the solutions mentioned here. The issue seems not with the source folder.

For me the issue occurred when I installed a new version of IntelliJ, was using 2019 version moved to 2020 version. The project got opened in the new version but the declarations were missing.

I fixed this by :

 - File>Project Structure.  
 - Under Project Settings go to Modules. Here you should see the different project folders, for me it was not there. 
 - Click the + button on top and click Import Module.
 - Select the root pom.xml and wait for the indexing to complete.

After the indexing is done all the declarations were working.

MySql server startup error 'The server quit without updating PID file '

I had the same problem. The reason is quite simple. I installed 2 mysql server. One from Mac Port, the other from downloaded package. So I just follow the instruction here and uninstalled the one from package. How do you uninstall MySQL from Mac OS X? After that, mysql is working well.

Bootstrap datepicker hide after selection

If you're looking to override the behavior of the calendar in general, globally, try editing the Datepicker function (in my example it was line 82),

from

    this.autoclose = false;

to

    this.autoclose = true;

Worked fine for me, as I wanted to have all my calendar instances behave the same.

How can I solve the error LNK2019: unresolved external symbol - function?

Since I want my project to compile to a stand-alone EXE file, I linked the UnitTest project to the function.obj file generated from function.cpp and it works.

Right click on the 'UnitTest1' project ? Configuration Properties ? Linker ? Input ? Additional Dependencies ? add "..\MyProjectTest\Debug\function.obj".

Session 'app': Error Installing APK

Turning off the Instant run removed my error for Androdi Studio 2017.03.03 v2.3

enter image description here

WPF C# button style

In this day and age of mouse driven computers and tablets with touch screens etc, it is often forgotten to cater for input via keyboard only. A button should support a focus rectangle (the dotted rectangle when the button has focus) or another shape matching the button shape.

To add a focus rectangle to the button, use this XAML (from this site). Focus rectangle style:

<Style x:Key="ButtonFocusVisual">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate>
        <Border>
          <Rectangle Margin="2" StrokeThickness="1" Stroke="#60000000" StrokeDashArray="1 2" />
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Applying the style to the button:

<Style TargetType="Button">
  <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}" />
  ...

How do I drag and drop files into an application?

Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.

Making a <button> that's a link in HTML

The 3 easiest ways IMHO are

1: you create an image of a button and put a href around it. (Not a good way, you lose flexibility and will provide a lot of difficulties and problems.)

2 (The easiest one) -> JQuery

<input type="submit" someattribute="http://yoururl/index.php">

  $('button[type=submit] .default').click(function(){
     window.location = $(this).attr("someattribute");
     return false; //otherwise it will send a button submit to the server

   });  

3 (also easy but I prefer previous one):

<INPUT TYPE=BUTTON OnClick="somefunction("http://yoururl");return false" VALUE="somevalue">

$fn.somefunction= function(url) {
    window.location = url;
};

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

PHP import Excel into database (xls & xlsx)

This is best plugin with proper documentation and examples

https://github.com/PHPOffice/PHPExcel

Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

How to prevent Browser cache on Angular 2 site?

In each html template I just add the following meta tags at the top:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Centering FontAwesome icons vertically and horizontally

I have used transform to correct the offset. It works great with round icons like the life ring.

<span class="fa fa-life-ring"></span>

.fa {
    transform: translateY(-4%);
}

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

If you already have material-icons working in your web project, just need to update your reference in the html file and the used class for icons:

html reference:

Before

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

After

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />

material icons class:

After that just check wich className are you using:

Before:

<i className="material-icons">weekend</i>

After:

<i className="material-icons-outlined">weekend</i>

that works for me... Pura vida!

How to scroll to specific item using jQuery?

I agree with Kevin and others, using a plugin for this is pointless.

window.scrollTo(0, $("#element").offset().top);

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

Regex for Mobile Number Validation

Satisfies all your requirements if you use the trick told below

Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/

  1. ^ start of line
  2. A + followed by \d+ followed by a or - which are optional.
  3. Whole point two is optional.
  4. Negative lookahead to make sure 0s do not follow.
  5. Match \d+ 10 times.
  6. Line end.

DEMO Added multiline flag in demo to check for all cases

P.S. You really need to specify which language you use so as to use an if condition something like below:

// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times

if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )

Using Java to find substring of a bigger string using Regular Expression

Like this its work if you want to parse some string which is coming from mYearInDB.toString() =[2013] it will give 2013

Matcher n = MY_PATTERN.matcher("FOO[BAR]"+mYearInDB.toString());
while (n.find()) {
 extracredYear  = n.group(1);
 // s now contains "BAR"
    }
    System.out.println("Extrated output is : "+extracredYear);

Add text at the end of each line

If you'd like to add text at the end of each line in-place (in the same file), you can use -i parameter, for example:

sed -i'.bak' 's/$/:80/' foo.txt

However -i option is non-standard Unix extension and may not be available on all operating systems.

So you can consider using ex (which is equivalent to vi -e/vim -e):

ex +"%s/$/:80/g" -cwq foo.txt

which will add :80 to each line, but sometimes it can append it to blank lines.

So better method is to check if the line actually contain any number, and then append it, for example:

ex  +"g/[0-9]/s/$/:80/g" -cwq foo.txt

If the file has more complex format, consider using proper regex, instead of [0-9].

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

Python basics printing 1 to 100

Your count never equals the value 100 so your loop will continue until that is true

Replace your while clause with

def gukan(count):
    while count < 100:
      print(count)
      count=count+3;
gukan(0)

and this will fix your problem, the program is executing correctly given the conditions you have given it.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I've recently stumbled upon the following solution to this problem:

Source: Multiple versions of Chrome

...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):

  1. Install Chrome 2, you'll find it Application Data folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:

    C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
    

    and run Chrome

  2. Open registry and save

    [HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    

    keys, put them into one chrome2.reg file and copy this file next to chrome.exe (ChromeDir\Application)

  3. Rename Chrome folder to something else (e.g. Chrome2)

  4. Install Chrome 3, it will install to Chrome folder again and run Chrome

  5. Save the same keys (there are changes due to different version) and save it to the chrome3.reg file next to chrome.exe file of this new version again
  6. Rename the folder again (e.g. Chrome3)

    the result would be that there is no Chrome dir (only Chrome2 and Chrome3)

  7. Go to the Application folder of Chrome2, create chrome.bat file with this content:

    @echo off
    regedit /S chrome2.reg
    START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data"
    rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
    

    the first line is generic batch command, the second line will update registry with the content of chrome2.reg file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.

    Notice short name format passed as -user-data-dir parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)

  8. Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3

Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.

Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.

Bronislav Klucka

Error: Unable to run mksdcard SDK tool

For UBUNTU 15.04,15.10,16.04 LTS, Debian 8 & Debian 9 Try this command:

sudo apt-get install lib32stdc++6

Visual Studio 2010 shortcut to find classes and methods?

Ctrl+K,Ctrl+R opens the Object Browser in Visual Studio 2010. Find what you're looking for by searching and browsing and filtering the results. See also Ctrl+Alt+J. ^K ^R is better because it puts your caret right in the search box, ready to type your new search, even when the Object Browser is already open.

Set the Browse list on the top left to where you want to look to get started. From there you can use the search box (2nd text box from the top, goes all the way across the Object Browser window) or you can just go through everything from the tree on the left. Searches are temporary but the "selected components" set by the Browse list persists. Set a custom set with the little "..." button just to the right of the list.

Objects, packages, namespaces, types, etc. on the left; fields, methods, constants, etc. on the top right, docstrings on the lower right.

The display mode of a pane can be changed by right-clicking in the empty space of the window; tree organized by assembly/container or by namespace and other preferences.

Items can be right-clicked to find, copy and filter.

For keyboard navigation, use Ctrl+K,Ctrl+R from anywhere to start a new search, Enter to execute the search you just typed or pasted and Ctrl+F6 to make the Object Browser close. ALT+<-- to go back and ALT+--> to go forward through the search history. More can be set; search for "ObjectBrowser" in the keyboard shortcut config.

If the key shortcuts above don't work, Object Browser should be in the View menu somewhere with a different shortcut. If all else fails, search for "ObjectBrowser" under Tools->Options->Environment->Keyboard->"Show commands containing".

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to deal with a slow SecureRandom generator?

The problem you referenced about /dev/random is not with the SecureRandom algorithm, but with the source of randomness that it uses. The two are orthogonal. You should figure out which one of the two is slowing you down.

Uncommon Maths page that you linked explicitly mentions that they are not addressing the source of randomness.

You can try different JCE providers, such as BouncyCastle, to see if their implementation of SecureRandom is faster.

A brief search also reveals Linux patches that replace the default implementation with Fortuna. I don't know much more about this, but you're welcome to investigate.

I should also mention that while it's very dangerous to use a badly implemented SecureRandom algorithm and/or randomness source, you can roll your own JCE Provider with a custom implementation of SecureRandomSpi. You will need to go through a process with Sun to get your provider signed, but it's actually pretty straightforward; they just need you to fax them a form stating that you're aware of the US export restrictions on crypto libraries.

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

How to make a view with rounded corners?

Or you can use a android.support.v7.widget.CardView like so:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="@color/white"
    card_view:cardCornerRadius="4dp">

    <!--YOUR CONTENT-->
</android.support.v7.widget.CardView>

Can I style an image's ALT text with CSS?

You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:

_x000D_
_x000D_
    <div style="background-color:black; height: 50px; width: 50px; color:white;">_x000D_
    <img src="ouch" alt="here i am"/>_x000D_
    <div>
_x000D_
_x000D_
_x000D_

In the above example, the alt text will be black. However with the color:white the alt text is white.

git: undo all working dir changes including new files

Have a look at the git clean command.

git-clean - Remove untracked files from the working tree

Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.

Normally, only files unknown to git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.

How to apply two CSS classes to a single element

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]