Programs & Examples On #Forums

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

SQL Server® 2016, 2017 and 2019 Express full download

Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.

Git:nothing added to commit but untracked files present

You have two options here. You can either add the untracked files to your Git repository (as the warning message suggested), or you can add the files to your .gitignore file, if you want Git to ignore them.

To add the files use git add:

git add Optimization/language/languageUpdate.php
git add email_test.php

To ignore the files, add the following lines to your .gitignore:

/Optimization/language/languageUpdate.php
/email_test.php

Either option should allow the git pull to succeed afterwards.

How to find files modified in last x minutes (find -mmin does not work as expected)

Manual of find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

   -amin n
          File was last accessed n minutes ago.

   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.

   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.

   -cmin n
          File's status was last changed n minutes ago.

   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.

   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

For latest Windows 10 (HP & Intel motherboard/processor),

Follow the below steps, starting with :

Settings ->
Update & Security ->
Recovery ->
Advanced startUp -> Restart now

F10 (System Recovery) -> System Configuration tab -> Virtualization Technology

Enable

F10 to save and exit

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

How to use Visual Studio Code as Default Editor for Git

I set up Visual Studio Code as a default to open .txt file. And next I did use simple command: git config --global core.editor "'C:\Users\UserName\AppData\Local\Code\app-0.7.10\Code.exe\'". And everything works pretty well.

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

XAMPP: Couldn't start Apache (Windows 10)

In my case it was a simple case of removing IIS because Windows 10 comes with IIS (Internet Information Service) pre installed - that conflicts with XAMPP because these both servers try to use the port 80. If you don't want to use IIS and keep using XAMPP

  1. Go to run/search in Windows 10
  2. Search for 'optional features'
  3. On that list untick Internet Information Service (IIS)

Then restart.

how to create virtual host on XAMPP

Step 1) C:\WINDOWS\system32\drivers\etc\ Open the "hosts" file :

127.0.0.1       localhost
127.0.0.1       test.com
127.0.0.1       example.com

Step 2) xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/test/
    ServerName www.test.com
</VirtualHost>
<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/example/
    ServerName www.example.com
</VirtualHost>

Step 3) C:\xampp\apache\conf\httpd.conf. Scroll down to the Supplemental configuration section at the end, and locate the following section (around line 500), Remove the # from the beginning of the second line so the section now looks like this:

#Virtual hosts
Include conf/extra/httpd-vhosts.conf

Step 4) Restart XAMPP and now run in your browser :

www.example.com or www.test.com

Eclipse Java error: This selection cannot be launched and there are no recent launches

Check if the filename is same as the classname used by your program.

eg.:

class Dfs{ psvm(String[] args){}}

filename should be Dfs.java

Pandas: sum DataFrame rows for given columns

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Datatables: Cannot read property 'mData' of undefined

Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

connecting MySQL server to NetBeans

Follow these 2 steps:

STEP 1 :

Follow these steps using the Services Tab:

  1. Right click on Database
  2. Create new Connection

Customize the New COnnection as follows:

  1. Connector Name: MYSQL (Connector/J Driver)
  2. Host: localhost
  3. Port: 3306
  4. Database: mysql ( mysql is the default or enter your database name)
  5. Username: enter your database username
  6. Password: enter your database password
  7. JDBC URL: jdbc:mysql://localhost:3306/mysql
  8. CLick Finish button

NB: DELETE the ?zeroDateTimeBehaviour=convertToNull part in the URL. Instead of mysql in the URL, you should see your database name)


STEP 2 :

  1. Right click on MySQL Server at localhost:3306:[username](...)
  2. Select Properties... from the shortcut menu

In the "MySQL Server Properties" dialog select the "Admin Properties" tab Enter the following in the textboxes specified:

For Linux users :

  1. Path to start command: /usr/bin/mysql
  2. Arguments: /etc/init.d/mysql start
  3. Path to Stop command: /usr/bin/mysql
  4. Arguments: /etc/init.d/mysql stop

For MS Windows users :

NOTE: Optional:

In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.

Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a command-line tool and not ideal for use with the IDE.

Citations:
https://netbeans.org/kb/docs/ide/mysql.html?print=yes
http://javawebaction.blogspot.com/2013/04/how-to-register-mysql-database-server.html


We will use MySQL Workbench in this example. Please use the path of your installation if you have MySQL workbench and the path to MySQL.

  1. Path/URL to admin tool: C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\MySQLWorkbench.exe
  2. Arguments: (Leave blank)
  3. Path to start command: C:\mysql\bin\mysqld (OR C:\mysql\bin\mysqld.exe)
  4. Arguments: (Leave blank)
  5. Path to Stop command: C:\mysql\bin\mysqladmin (OR C:\mysql\bin\mysqladmin.exe )
  6. Arguments: -u root shutdown (Try -u root stop)

Possible exampes of MySQL bin folder locations for Windows Users:

  • C:\mysql\bin
  • C:\Program Files\MySQL\MySQL Server 5.1\bin\
  • Installation Folder: ~\xampp\mysql\bin

How can I change the width and height of slides on Slick Carousel?

I know there is already an answer to this but I just found a better solution using the variableWidth parameter, just set it to true in the settings of each breakpoint, like this:

$('#featured-articles').slick({
  arrows: true,
  autoplay: true,
  autoplaySpeed: 3000,
  dots: true,
  draggable: false,
  fade: true,
  infinite: false,
  responsive: [
  {
    breakpoint: 620,
    settings: {
        arrows: true,
        variableWidth: true
    }
  },
  {
    breakpoint: 345,
    settings: {
        arrows: true,
        variableWidth: true
    }
  }
  ]
});

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

first check your php version like this :

php -v

after you get version number for example i get 7.1 then install like that

sudo apt-get install  php7.1-sqlite     //for laravel testing with sqlite
sudo apt-get install  php-mysql         //for default mysql
sudo apt-get install  php7.1-mysql      //for version based mysql 
sudo apt-get install  php7.1-common     //for other necessary package for php

and need to restart apache2

sudo service apache2 restart

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

You could alter the init script for neo4j to do a ulimit -n 40000 before running neo4j.

However, I can't help but feel you are barking up the wrong tree. Does neo4j legitimately need more than 10,000 open file descriptors? This sounds very much like a bug in neo4j or the way you are using it. I would try to address that.

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Most of Time, it was occured due to AppPool Setting.

Check the following to resolve this

  1. Check Apppool service is running.
  2. Check Identity of AppPool.
  3. Enter the new password if it has changed for that identity.

The following Images show these setting in IIS

enter image description here

How to add multiple files to Git at the same time

It sounds like git is launching your editor (probably vi) so that you can type a commit message. If you are not familiar with vi, it is easy to learn the basics. Alternatives are:

  • Use git commit -a -m "my first commit message" to specify the commit message on the command line (using this will not launch an editor)

  • Set the EDITOR environment variable to an editor that you are familiar with

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

Don´t use USB3.0 ports ... try it on a usb 2.0 port

Also try to change transfer mode, like suggested here: https://android.stackexchange.com/a/49662

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Some basic differences can be written in short:

MVC:

Traditional MVC is where there is a

  1. Model: Acts as the model for data
  2. View : Deals with the view to the user which can be the UI
  3. Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.

MVP:

Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.

MVVM

The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

What is the iBeacon Bluetooth Profile

For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major 0, minor 0, and calibrated Tx Power of -59 RSSI, the transmitted BLE advertisement packet looks like this:

d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5

This packet can be broken down as follows:

d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0.  Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1.  Contains:  (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum

The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:

02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010  
   bit 0 (OFF) LE Limited Discoverable Mode
   bit 1 (ON) LE General Discoverable Mode
   bit 2 (OFF) BR/EDR Not Supported
   bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
   bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major 
00 00 # minor 
c5 # The 2's complement of the calibrated Tx Power

Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)

This blog has full details about the reverse engineering process.

How to get to Model or Viewbag Variables in a Script Tag

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);

How to access model hasMany Relation with where condition?

Just in case anyone else encounters the same problems.

Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

You can easily find out investigating the Laravel source:

// Illuminate\Database\Eloquent\Model.php
...
/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

This also explains why my code worked, whenever I loaded the data using the load() method before.

Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

Where to place the 'assets' folder in Android Studio?

Simply, double shift then type Assets Folder

choose it to be created in the correct place

XAMPP, Apache - Error: Apache shutdown unexpectedly

i also got the same error and i was uninstall vmware to fix that error.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME

Cannot hide status bar in iOS7

For Swift 2.0+ IOS 9

override func prefersStatusBarHidden() -> Bool {
return true
}

XAMPP - MySQL shutdown unexpectedly

No solution above worked for me. then I did below:

I deleted all the files inside C:\xampp\mysql\data\ directory except folders in this directory. It worked perfectly fine but my previous databases are not working now. So do above if you don't care it will delete all your previous databases in phpmyadmin.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

If you are installed Skype, Please check this option.

enter image description here

Another case is Windows 10

Check this:

  1. Go to Start, type in services.msc
  2. Scroll down in the Services window to find the World Wide Web Publishing Service.
  3. Right-click on it, and select Stop or Disable it if you just want to use XAMPP only.

enter image description here

What exactly is the function of Application.CutCopyMode property in Excel

There is a good explanation at https://stackoverflow.com/a/33833319/903783

The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.

WCF error - There was no endpoint listening at

I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

Apache shutdown unexpectedly

on your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Check if you did compress the driver or folder in where you put the .mdf file.

If so, plesae goto the driver or folder, change the compress option by

Properties -> Advanced and unticked the “Compress contents to save disk space” checkbox.

After above things, you should be able to start the service again.

How do you clear a slice in Go?

Setting the slice to nil is the best way to clear a slice. nil slices in go are perfectly well behaved and setting the slice to nil will release the underlying memory to the garbage collector.

See playground

package main

import (
    "fmt"
)

func dump(letters []string) {
    fmt.Println("letters = ", letters)
    fmt.Println(cap(letters))
    fmt.Println(len(letters))
    for i := range letters {
        fmt.Println(i, letters[i])
    }
}

func main() {
    letters := []string{"a", "b", "c", "d"}
    dump(letters)
    // clear the slice
    letters = nil
    dump(letters)
    // add stuff back to it
    letters = append(letters, "e")
    dump(letters)
}

Prints

letters =  [a b c d]
4
4
0 a
1 b
2 c
3 d
letters =  []
0
0
letters =  [e]
1
1
0 e

Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil will remove that aliasing.

This method changes the capacity to zero though.

How abstraction and encapsulation differ?

I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.

For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.

If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.

Node Version Manager install - nvm command not found

All answers to this questions are useful. Especially the answer given by Travis helped me. For Mac OS X users I would like to provide some steps which will help them to work with the fresh installation of Node Version Manager a.k.a. nvm.

Installing & using nvm on Mac OS X

Here are the steps for fresh installation of nvm and using it without any issue:

  • Install homebrew from here.
  • Using homebrew install nvm

    brew update brew install nvm

  • Create .nvm directory at ~/.nvm location.

    mkdir ~/.nvm

  • Now if you don't have .bash_profile file setup for OS X terminal then please create a .bash_profile at the root level:

    nano ~/.bash_profile

  • Paste below code in the .bash_profile and press CTRL + O and press enter to save .bash_profile file. Press CTRL + X to exit from editor:

    export NVM_DIR=~/.nvm source $(brew --prefix nvm)/nvm.sh

  • Now either quite (CMD + Q) the terminal or run below command to load .bash_profile settings:

    source ~/.bash_profile

  • Now run nvm ls command to get the list of all installed nodejs versions.

How to use cURL to get jSON data and decode the data?

Use this function: http://br.php.net/json_decode This will automatically create PHP arrays.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Check the properties of your projectm the platform target. Install the corresponding version of Crystal Reports:

To x86 > CRforVS_redist_install_32bit
To x64 > CRforVS_redist_install_64bit

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

If someone is using the new DataTables (which is awesome btw) and want to use array of objects then you can do so easily with the columns option. Refer to the following link for an excellent example on this.

DataTables with Array of Objects

I was struggling with this for the past 2 days and this solved it. I didn't wanted to switch to multi-dimensional arrays for other code reasons so was looking for a solution like this.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I am late, hope it will help someone ....This is a known issue with IIS 8.0

The solution is to delete the 3.x module and handler from IIS manager. You could delete them at the application or site level if you want to keep them in applicationHost.config. But I wanted to delete them from applicationHost.config. do the following steps:

In IIS manager, click the machine name node. In “Features View”, double-click “Modules”. Find “ServiceModel” and remove it. Image 1 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Go back to the machine name node’s “Features View”, double-click “Handler Mappings”. Find “svc-Integrated” and remove it. Image 2 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

I've deleted java files at windows/system32 and I also have removed c:\ProgramData\Oracle\Java\javapath from the PATH variable, because there was 3 symlinks to java 1.8 files.

I had JDK 1.7 in the %JAVA_HOME% variable and java1.7/bin in the PATH.

PS1: My problem was between Java 1.7 and Java 1.8.

PS2: I can't add this as a comment to Victor's answer because I haven't enough points.

Java SSLHandshakeException "no cipher suites in common"

Having had this exception myself, I delved into the JRE source code. It became apparent that the message is rather misleading. It could mean what it says, but it more generally means that the server doesn't have the data it needs to respond to the client in the requested way. This can happen, for example, if certificates are missing from the keystore, or haven't been generated with the an appropriate algoritm. Indeed, given the cipher suites that are installed by default, one would have to go to some lengths to really get this exception because of lack of common cipher suites. In my particular case I'd generated the certificates with the default algorithm of DSA, when what I needed to get the server to work with Firefox was RSA.

jQuery set checkbox checked

Dude try below code :

$("div.row-form input[type='checkbox']").attr('checked','checked')

OR

$("div.row-form #estado_cat").attr("checked","checked");

OR

$("div.row-form #estado_cat").attr("checked",true);

Android : Check whether the phone is dual SIM

I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.

managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();        
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
    if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
        indexSIMID=i;
}

I did not find this column in a single SIM phone (I checked on Xperia L).

So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.

Source file not compiled Dev C++

I guess you're using windows 7 with the Orwell Dev CPP

This version of Dev CPP is good for windows 8 only. However on Windows 7 you need the older version of it which is devcpp-4.9.9.2_setup.exe Download it from the link and use it. (Don't forget to uninstall any other version already installed on your pc) Also note that the older version does not work with windows 8.

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

Just check our own JSTL wiki page for the proper download links and crystal clear installation instructions.

Put your mouse above the [jstl] tag which you put on the question yourself until a black box shows up and click therein the info link.

enter image description here

Then scroll a bit down to JSTL versions information until you find download link to JSTL 1.2 (or 1.2.1).

enter image description here

Finally just drop exactly that file in webapp's /WEB-INF/lib.

enter image description here

This way the taglib declaration must not give any errors anymore and the JSTL tags and functions should just work.

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

Check your web descriptor (web.xml) or on your servlets (Where you annotate, check sor something like '@WebServlet("/servlet_name")') for any duplicates.If any, remove them.

DataTables fixed headers misaligned with columns in wide tables

I just figured out a way to fix the alignment issue. Changing the width of div containing the static header will fix its alignment. The optimal width I found is 98%. Please refer to the code.

The auto generated div:

<div class="dataTables_scrollHead" style="overflow: hidden; position: relative; border: 0px none; width: 100%;">

Width here is 100%, change it to 98% on initializing and reloading the data table.

jQuery('#dashboard').dataTable({
    "sEcho": "1",

    "aaSorting": [[aasortvalue, 'desc']],
    "bServerSide": true,
    "sAjaxSource": "NF.do?method=loadData&Table=dashboardReport",
    "bProcessing": true,
    "sPaginationType": "full_numbers",
    "sDom": "lrtip", // Add 'f' to add back in filtering
    "bJQueryUI": false,
    "sScrollX": "100%",
    "sScrollY": "450px",
    "iDisplayLength": '<%=recordCount%>',
    "bScrollCollapse": true,
    "bScrollAutoCss": true,
    "fnInitComplete": function () {
        jQuery('.dataTables_scrollHead').css('width', '98%'); //changing the width
    },
    "fnDrawCallback": function () {
        jQuery('.dataTables_scrollHead').css('width', '98%');//changing the width
    }
});

Transpose a range in VBA

You do not need to do this. Here is how to create a co-variance method:

http://www.youtube.com/watch?v=RqAfC4JXd4A

Alternatively you can use statistical analysis package that Excel has.

DataTable: How to get item value with row name and column name? (VB)

For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next

2D cross-platform game engine for Android and iOS?

You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.

If you're interested, I've written a bit about my experience using Haxe/NME: link

String comparison in bash. [[: not found

Specify bash instead of sh when running the script. I personally noticed they are different under ubuntu 12.10:

bash script.sh arg0 ... argn

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Using "setInterval" & "clearInterval" fixes the problem:

function drawMarkers(map, markers) {
    var _this = this,
        geocoder = new google.maps.Geocoder(),
        geocode_filetrs;

    _this.key = 0;

    _this.interval = setInterval(function() {
        _this.markerData = markers[_this.key];

        geocoder.geocode({ address: _this.markerData.address }, yourCallback(_this.markerData));

        _this.key++;

        if ( ! markers[_this.key]) {
            clearInterval(_this.interval);
        }

    }, 300);
}

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

If you can use a C++ compiler to build the object file that you want to contain your version string, then we can do exactly what you want! The only magic here is that C++ allows you to use expressions to statically initialize an array, while C doesn't. The expressions need to be fully computable at compile time, but these expressions are, so it's no problem.

We build up the version string one byte at a time, and get exactly what we want.

// source file version_num.h

#ifndef VERSION_NUM_H

#define VERSION_NUM_H


#define VERSION_MAJOR 1
#define VERSION_MINOR 4


#endif // VERSION_NUM_H

// source file build_defs.h

#ifndef BUILD_DEFS_H

#define BUILD_DEFS_H


// Example of __DATE__ string: "Jul 27 2012"
//                              01234567890

#define BUILD_YEAR_CH0 (__DATE__[ 7])
#define BUILD_YEAR_CH1 (__DATE__[ 8])
#define BUILD_YEAR_CH2 (__DATE__[ 9])
#define BUILD_YEAR_CH3 (__DATE__[10])


#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')


#define BUILD_MONTH_CH0 \
    ((BUILD_MONTH_IS_OCT || BUILD_MONTH_IS_NOV || BUILD_MONTH_IS_DEC) ? '1' : '0')

#define BUILD_MONTH_CH1 \
    ( \
        (BUILD_MONTH_IS_JAN) ? '1' : \
        (BUILD_MONTH_IS_FEB) ? '2' : \
        (BUILD_MONTH_IS_MAR) ? '3' : \
        (BUILD_MONTH_IS_APR) ? '4' : \
        (BUILD_MONTH_IS_MAY) ? '5' : \
        (BUILD_MONTH_IS_JUN) ? '6' : \
        (BUILD_MONTH_IS_JUL) ? '7' : \
        (BUILD_MONTH_IS_AUG) ? '8' : \
        (BUILD_MONTH_IS_SEP) ? '9' : \
        (BUILD_MONTH_IS_OCT) ? '0' : \
        (BUILD_MONTH_IS_NOV) ? '1' : \
        (BUILD_MONTH_IS_DEC) ? '2' : \
        /* error default */    '?' \
    )

#define BUILD_DAY_CH0 ((__DATE__[4] >= '0') ? (__DATE__[4]) : '0')
#define BUILD_DAY_CH1 (__DATE__[ 5])



// Example of __TIME__ string: "21:06:19"
//                              01234567

#define BUILD_HOUR_CH0 (__TIME__[0])
#define BUILD_HOUR_CH1 (__TIME__[1])

#define BUILD_MIN_CH0 (__TIME__[3])
#define BUILD_MIN_CH1 (__TIME__[4])

#define BUILD_SEC_CH0 (__TIME__[6])
#define BUILD_SEC_CH1 (__TIME__[7])


#if VERSION_MAJOR > 100

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 100) + '0'), \
    (((VERSION_MAJOR % 100) / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#elif VERSION_MAJOR > 10

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#else

#define VERSION_MAJOR_INIT \
    (VERSION_MAJOR + '0')

#endif

#if VERSION_MINOR > 100

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 100) + '0'), \
    (((VERSION_MINOR % 100) / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#elif VERSION_MINOR > 10

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#else

#define VERSION_MINOR_INIT \
    (VERSION_MINOR + '0')

#endif



#endif // BUILD_DEFS_H

// source file main.c

#include "version_num.h"
#include "build_defs.h"

// want something like: 1.4.1432.2234

const unsigned char completeVersion[] =
{
    VERSION_MAJOR_INIT,
    '.',
    VERSION_MINOR_INIT,
    '-', 'V', '-',
    BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3,
    '-',
    BUILD_MONTH_CH0, BUILD_MONTH_CH1,
    '-',
    BUILD_DAY_CH0, BUILD_DAY_CH1,
    'T',
    BUILD_HOUR_CH0, BUILD_HOUR_CH1,
    ':',
    BUILD_MIN_CH0, BUILD_MIN_CH1,
    ':',
    BUILD_SEC_CH0, BUILD_SEC_CH1,
    '\0'
};


#include <stdio.h>

int main(int argc, char **argv)
{
    printf("%s\n", completeVersion);
    // prints something similar to: 1.4-V-2013-05-09T15:34:49
}

This isn't exactly the format you asked for, but I still don't fully understand how you want days and hours mapped to an integer. I think it's pretty clear how to make this produce any desired string.

Returning an array using C

I am not saying that this is the best solution or a preferred solution to the given problem. However, it may be useful to remember that functions can return structs. Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it. This works for fixed length arrays.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    typedef
    struct 
    {
        char v[10];
    } CHAR_ARRAY;



    CHAR_ARRAY returnArray(CHAR_ARRAY array_in, int size)
    {
        CHAR_ARRAY returned;

        /*
        . . . methods to pull values from array, interpret them, and then create new array
        */

        for (int i = 0;  i < size; i++ )
            returned.v[i] = array_in.v[i] + 1;

        return returned; // Works!
    } 




    int main(int argc, char * argv[])
    {
        CHAR_ARRAY array = {1,0,0,0,0,1,1};

        char arrayCount = 7;

        CHAR_ARRAY returnedArray = returnArray(array, arrayCount); 

        for (int i = 0; i < arrayCount; i++)
            printf("%d, ", returnedArray.v[i]);  //is this correctly formatted?

        getchar();
        return 0;
    }

I invite comments on the strengths and weaknesses of this technique. I have not bothered to do so.

Twitter Bootstrap add active class to li

If you are using an MVC framework with routes and actions:

$(document).ready(function () {
    $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
});

As illustrated in this answer by Christian Landgren: https://stackoverflow.com/a/13375529/101662

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

Because it hasn't been mentioned yet, this was the solution for me:

I had this error with a DLL after creating a new configuration for my project. I had to go to Project Properties -> Configuration Properties -> General and change the Configuration Type to Dynamic Library (.dll).

So if you're still having trouble after trying everything else, it's worth checking to see if the configuration type is what you expect for your project. If it's not set correctly, the compiler will be looking for the wrong main symbol. In my case, it was looking for WinMain instead of DllMain.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

How should I pass multiple parameters to an ASP.Net Web API GET?

I found exellent solution on http://habrahabr.ru/post/164945/

public class ResourceQuery
{
   public string Param1 { get; set; }
   public int OptionalParam2 { get; set; }
}

public class SampleResourceController : ApiController
{
    public SampleResourceModel Get([FromUri] ResourceQuery query)
    {
        // action
    }
}

The mysqli extension is missing. Please check your PHP configuration

If your configuration files are okay but still having the same issue then install php7.x-mysql according to the version of the installed php.

For example in my case, I'm using php7.3 so I ran the following command to get it all set:

sudo apt install php7.3-mysql

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

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

I stopped MySQL sudo service mysql stop and then started xammp sudo /opt/lampp/lampp start and it worked!

Duplicate AssemblyVersion Attribute

I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]

scp from Linux to Windows

As @Hesham Eraqi suggested, it worked for me in this way (transfering from Ubuntu to Windows (I tried to add a comment in that answer but because of reputation, I couldn't)):

pscp -v -r -P 53670 [email protected]:/data/genetic_map/sample/P2_283/* \\Desktop-mojbd3n\d\cc_01-1940_data\

where:

-v: show verbose messages.
-r: copy directories recursively.
-P: connect to specified port.
53670: the port number to connect the Ubuntu server.
\\Desktop-mojbd3n\d\genetic_map_data\: I needed to transfer to an external HDD, thus I had to give permissions of sharing to this device.

Eclipse cannot load SWT libraries

I agree with Scott, what he listed worked. However just running it from any directory did not work. I had to cd to the /home/*/.swt/lib/linux/x86_64/ 0 files

directory first and then run the link command:

For 32 bit:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86/

And on Ubuntu 12.04 64 bit:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86_64/

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

How to set java.net.preferIPv4Stack=true at runtime?

System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:

    deployJava.runApplet({
        id: 'MyApplet',
        code: 'com.mkysoft.myapplet.SomeClass',
        archive: 'com.mkysoft.myapplet.jar'
    }, {
        java_version: "1.6*", // Target version
        cache_option: "no",
        cache_archive: "",
        codebase_lookup: true,
        java_arguments: "-Djava.net.preferIPv4Stack=true"
    },
       "1.6" // Minimum version
    );

You can find deployJava.js at https://www.java.com/js/deployJava.js

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Just a small hack. Update the URL in the file "hudson.model.UpdateCenter.xml" from https to http

<?xml version='1.1' encoding='UTF-8'?>
<sites>
  <site>
    <id>default</id>
    <url>http://updates.jenkins.io/update-center.json</url>
  </site>
</sites>

Nullable DateTime conversion

Cast the null literal: (DateTime?)null or (Nullable<DateTime>)null.

You can also use default(DateTime?) or default(Nullable<DateTime>)

And, as other answers have noted, you can also apply the cast to the DateTime value rather than to the null literal.

EDIT (adapted from my comment to Prutswonder's answer):

The point is that the conditional operator does not consider the type of its assignment target, so it will only compile if there is an implicit conversion from the type of its second operand to the type of its third operand, or from the type of its third operand to the type of its second operand.

For example, this won't compile:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;

Casting either the second or third operand to object, however, fixes the problem, because there is an implicit conversion from int to object and also from string to object:

object o = b ? "Forty-two" : (object)42;

or

object o = b ? (object)"Forty-two" : 42;

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

No matching bean of type ... found for dependency

Add annotation @Repository to the head of userDao Class.If userDao is a interface,add this annotation to the implements of the interface.

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

Include files from parent or other directory

I can't believe none of the answers pointed to the function dirname() (available since PHP 4).

Basically, it returns the full path for the referenced object. If you use a file as a reference, the function returns the full path of the file. If the referenced object is a folder, the function will return the parent folder of that folder.

https://www.php.net/manual/en/function.dirname.php

For the current folder of the current file, use $current = dirname(__FILE__);.

For a parent folder of the current folder, simply use $parent = dirname(__DIR__);.

Toggle display:none style with JavaScript

You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.

http://api.jquery.com/toggle/

EDIT: Adding the actual code:

Solution:

HTML snippet:

<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
    <li>Tag 1</li>
    <li>Tag 2</li>
    <li>Tag 3</li>
    <li>Tag 4</li>
    <li>Tag 5</li>
</ul>

Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js

$(function() {
    $('#showAll').click(function(){  //Adds click event listener  
        $('#tags').toggle('slow'); // Toggles visibility.  Use the 'slow' parameter to add a nice effect.
    });
});

You can test directly from this link: http://jsfiddle.net/vssJr/5/

Additional Comments on JQuery:

Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.

JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.

Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.

If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.

Missing artifact com.sun:tools:jar

I just posted over on this question about this same issue and how I resolved it, but I'll paste (and expand on) it here as well, since it seems more relevant.

I had the same issue when using Eclipse in Windows 7, even when I removed the JRE from the list of JREs in the Eclipse settings and just had the JDK there.

What I ended up having to do (as you mentioned in your question) was modify the command-line for the shortcut I use to launch Eclipse to add the -vm argument to it like so:

-vm "T:\Program Files\Java\jdk1.6.0_26\bin"

Of course, you would adjust that to point to the bin directory of your JDK install. What this does is cause Eclipse itself to be running using the JDK instead of JRE, and then it's able to find the tools.jar properly.

I believe this has to do with how Eclipse finds its default JRE when none is specified. I'm guessing it tends to prefer JRE over JDK (why, I don't know) and goes for the first compatible JRE it finds. And if it's going off of Windows registry keys like Vladiat0r's answer suggests, it looks for the HKLM\Software\JavaSoft\Java Runtime Environment key first instead of the HKLM\Software\JavaSoft\Java Development Kit key.

while EOF in JAVA?

while(inFile.hasNext())

This is correct in java programming language

When should the xlsm or xlsb formats be used?

Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.

1. From Doug Mahugh, August 22, 2006:

...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.

The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...

This article also refers to documentation about the BIN format, too lengthy to reproduce here.

2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:

Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:

File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support

apache mod_rewrite is not working or not enabled

Try setting: "AllowOverride All".

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

get the selected index value of <select> tag in php

Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value

<select name="gender">
<option value="default">Select </option>    
<option value="male">   Male   </option>
<option value="female"> Female </option>
</select>

OR

<select name="gender">
<option value="male" selected="selected">   Male   </option>
<option value="female"> Female </option>
</select>

When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.

Most important thing, AVOID SQL INJECTIONS:

//....
$fname   = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname   = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email   = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
  $email = mysql_real_escape_string($_POST['email']);
}
else
{
  //die ('invalid email address');
  // or whatever, a default value? $email = '';
}
$paswod  = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender  = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';

$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
  echo 'userid is already there';
}
else
{
 $sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
         VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';

Why do we always prefer using parameters in SQL statements?

You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:

Her daughter is named Help I'm trapped in a driver's license factory.


In your example, if you just use:

var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query

You are open to SQL injection. For example, say someone enters txtSalary:

1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.

When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.


The correct way is to use parameterized queries, eg (C#):

SqlCommand query =  new SqlCommand("SELECT empSalary FROM employee 
                                    WHERE salary = @sal;");
query.Parameters.AddWithValue("@sal", txtSalary.Text);

With that, you can safely execute the query.

For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see http://support.microsoft.com/kb/306843 For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say? http://www.microsoft.com/download/en/details.aspx?id=2868
  4. What account is the SQL Service running as ?

Fatal error: Call to undefined function pg_connect()

You have to follow these steps:

Open the php configuration file, which is located in the following directory

C: \ xampp \ php \ php.ini

Within that file search the extension section and uncomment the following lines

extension = php_pdo_pgsql.dll  
extension = php_pgsql.dll

and restart your apache

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

I use the following method in my project

-(NSArray*)networkErrorCodes
{
    static NSArray *codesArray;
    if (![codesArray count]){
        @synchronized(self){
            const int codes[] = {
                //kCFURLErrorUnknown,     //-998
                //kCFURLErrorCancelled,   //-999
                //kCFURLErrorBadURL,      //-1000
                //kCFURLErrorTimedOut,    //-1001
                //kCFURLErrorUnsupportedURL, //-1002
                //kCFURLErrorCannotFindHost, //-1003
                kCFURLErrorCannotConnectToHost,     //-1004
                kCFURLErrorNetworkConnectionLost,   //-1005
                kCFURLErrorDNSLookupFailed,         //-1006
                //kCFURLErrorHTTPTooManyRedirects,    //-1007
                kCFURLErrorResourceUnavailable,     //-1008
                kCFURLErrorNotConnectedToInternet,  //-1009
                //kCFURLErrorRedirectToNonExistentLocation,   //-1010
                kCFURLErrorBadServerResponse,               //-1011
                //kCFURLErrorUserCancelledAuthentication,     //-1012
                //kCFURLErrorUserAuthenticationRequired,      //-1013
                //kCFURLErrorZeroByteResource,        //-1014
                //kCFURLErrorCannotDecodeRawData,     //-1015
                //kCFURLErrorCannotDecodeContentData, //-1016
                //kCFURLErrorCannotParseResponse,     //-1017
                kCFURLErrorInternationalRoamingOff, //-1018
                kCFURLErrorCallIsActive,                //-1019
                //kCFURLErrorDataNotAllowed,              //-1020
                //kCFURLErrorRequestBodyStreamExhausted,  //-1021
                kCFURLErrorFileDoesNotExist,            //-1100
                //kCFURLErrorFileIsDirectory,             //-1101
                kCFURLErrorNoPermissionsToReadFile,     //-1102
                //kCFURLErrorDataLengthExceedsMaximum,     //-1103
            };
            int size = sizeof(codes)/sizeof(int);
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0;i<size;++i){
                [array addObject:[NSNumber numberWithInt:codes[i]]];
            }
            codesArray = [array copy];
        }
    }
    return codesArray;
}

Then I just check the error code and show alert if it is in the list

if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){ 
// Fire Alert View Here
}

But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.

In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.

Regards to martinezdelariva for a link to documentation.

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I have the same problem. This error occurs because conection pooling. When exists two or more users acess the system the connetion pooling reuse a connetion and the transation too. If the first user execute commit ou rollback the transaction is no longe usable.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

How to save/restore serializable object to/from file?

I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.

Binary

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

XML

Requires the System.Xml assembly to be included in your project.

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Json

You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
        writer = new StreamWriter(filePath, append);
        writer.Write(contentsToWriteToFile);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Example

// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);

// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I was also facing the same issue.

I was using the code below in .aspx page without writing authentication configuration in web.config file. After writing the settings in Web.config, I am able to run my code.

<% If Request.IsAuthenticated Then%>
     <table></table>
<%end if%> 

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

adb devices command not working

restarting the adb server as root worked for me. see:

derek@zoe:~/Downloads$ adb sideload angler-ota-mtc20f-5a1e93e9.zip 
loading: 'angler-ota-mtc20f-5a1e93e9.zip'
error: insufficient permissions for device
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX    no permissions

derek@zoe:~/Downloads$ adb kill-server
derek@zoe:~/Downloads$ sudo adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX    sideload

Receiving login prompt using integrated windows authentication

In my case the solution was (on top of adjustments suggested above) to restart my/users' local development computer / IIS (hosting server). My user has just been added to the newly created AD security group - and policy didn't apply to user AD account until I logged out/restarted my computer.

Hope this will help someone.

How would I run an async Task<T> method synchronously?

If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.

Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await operator.

Most of the time, you'll be using await on an expression of type Task. Task's implementation of the await pattern is "smart" in that it defers to the SynchronizationContext, which basically causes the following to happen:

  1. If the thread entering the await is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.
  2. If the thread entering the await is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.

That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.

.... backing up! ....

I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:

  1. [Top] WebRequest.GetResponse()
  2. YourCode.HelperMethod()
  3. YourCode.AnotherMethod()
  4. YourCode.EventHandlerMethod()
  5. [UI Code].Plumbing() - WPF or WinForms Code
  6. [Message Loop] - WPF or WinForms Message Loop

Then once the code has been transformed to use async, you'll typically end up with

  1. [Top] WebRequest.GetResponseAsync()
  2. YourCode.HelperMethodAsync()
  3. YourCode.AnotherMethodAsync()
  4. YourCode.EventHandlerMethodAsync()
  5. [UI Code].Plumbing() - WPF or WinForms Code
  6. [Message Loop] - WPF or WinForms Message Loop

Actually Answering

The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.

Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:

var customerList = TaskEx.RunEx(GetCustomers).Result;

The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

To prevent IE8 from going on an endless loop of refreshing and crashing it stops after two times and shows this url. There could be many issues that might be causing it to crash.

In my case an upgrade to jQuery v1.10.2 from v1.4.4 causing the issue, but it must have been mostly our code bad and was now more evident with the upgrade.

My observation was everything seems working fine on IE7/XP, IE8/Win7, IE9/Win7 and IE10/Win7 but was not working fine on IE8/XP and IE8/Server2003. The version of IE8 on Win7 and XP/Server 2003 are different. Here is the list of versions for each Operating System (http://support.microsoft.com/kb/969393).

Then looked at Event viewer on Win Server 2003 and it had something like faulting module mshtml.dll, version 8.0.6001.18975 and on Win XP it was faulting module mshtml.dll, version 8.0.6001.18702 even though the browser version is same on both which is 8.0.6001.18702.

Then further searching about this mshtml.dll, it looks like Microsoft keeps updating mshtml.dll which is the HTML component of the browser through patches. So then I realised its not the browser version that is important but mshtml.dll version instead.

So I went ahead and downloaded the latest Cumulative patch for IE8 from here (https://technet.microsoft.com/en-us/security/bulletin/ms13-059) which updated my mshtml.dll file (in system32 folder) to 8.0.6001.23515 and it started working fine , may be they fixed it some time back probably in this (http://technet.microsoft.com/en-us/security/bulletin/ms12-037)

See also:

http://support.microsoft.com/kb/980344 http://support.microsoft.com/kb/979665

But first things first always reset your browser so that you disable all plugins and rule out the possible cause by external plugins.

Force "portrait" orientation mode

According to Android's documentation, you should also often include screenSize as a possible configuration change.

android:configChanges="orientation|screenSize"

If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.

Also, if you all include value keyboardHidden in your examples, shouldn't you then also consider locale, mcc, fontScale, keyboard and others?..

How to access the SMS storage on Android?

For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.

How to express a NOT IN query with ActiveRecord/Rails?

Piggybacking off of jonnii:

Topic.find(:all, :conditions => ['forum_id not in (?)', @forums.pluck(:id)])

using pluck rather than mapping over the elements

found via railsconf 2012 10 things you did not know rails could do

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

How to put a tooltip on a user-defined function

I just create a "help" version of the function. Shows up right below the function in autocomplete - the user can select it instead in an adjacent cell for instructions.

Public Function Foo(param1 as range, param2 as string) As String

    Foo = "Hello world"

End Function

Public Function Foo_Help() as String

Foo_Help = "The Foo function was designed to return the Foo value for a specified range a cells given a specified constant." & CHR(10) & "Parameters:" & CHR(10)
& "  param1 as Range   :   Specifies the range of cells the Foo function should operate on." & CHR(10)
&"  param2 as String  :   Specifies the constant the function should use to calculate Foo"
&" contact the Foo master at [email protected] for more information."

END FUNCTION

The carriage returns improve readability with wordwrap on. 2 birds with one stone, now the function has some documentation.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

To answer this question, we have to look at how indexing a multidimensional array works in Numpy. Let's first say you have the array x from your question. The buffer assigned to x will contain 16 ascending integers from 0 to 15. If you access one element, say x[i,j], NumPy has to figure out the memory location of this element relative to the beginning of the buffer. This is done by calculating in effect i*x.shape[1]+j (and multiplying with the size of an int to get an actual memory offset).

If you extract a subarray by basic slicing like y = x[0:2,0:2], the resulting object will share the underlying buffer with x. But what happens if you acces y[i,j]? NumPy can't use i*y.shape[1]+j to calculate the offset into the array, because the data belonging to y is not consecutive in memory.

NumPy solves this problem by introducing strides. When calculating the memory offset for accessing x[i,j], what is actually calculated is i*x.strides[0]+j*x.strides[1] (and this already includes the factor for the size of an int):

x.strides
(16, 4)

When y is extracted like above, NumPy does not create a new buffer, but it does create a new array object referencing the same buffer (otherwise y would just be equal to x.) The new array object will have a different shape then x and maybe a different starting offset into the buffer, but will share the strides with x (in this case at least):

y.shape
(2,2)
y.strides
(16, 4)

This way, computing the memory offset for y[i,j] will yield the correct result.

But what should NumPy do for something like z=x[[1,3]]? The strides mechanism won't allow correct indexing if the original buffer is used for z. NumPy theoretically could add some more sophisticated mechanism than the strides, but this would make element access relatively expensive, somehow defying the whole idea of an array. In addition, a view wouldn't be a really lightweight object anymore.

This is covered in depth in the NumPy documentation on indexing.

Oh, and nearly forgot about your actual question: Here is how to make the indexing with multiple lists work as expected:

x[[[1],[3]],[1,3]]

This is because the index arrays are broadcasted to a common shape. Of course, for this particular example, you can also make do with basic slicing:

x[1::2, 1::2]

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

Error With Port 8080 already in use

I faced a similar problem , here's the solution.

Step 1 : Double click on the server listed in Eclipse. Here It will display Server Configuration.

Step 2 : Just change the port Number like from 8080 to 8085.

Step 3 : Save the changes.

Step 4 : re-start your server.

The server will start .Hope it'll help you.

What are the options for storing hierarchical data in a relational database?

This is really a square peg, round hole question.

If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.

The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.

Consider a Bill of Materials as a common hierarchical data structure.

class Component extends Vertex {
    long assetId;
    long partNumber;
    long material;
    long amount;
};

class PartOf extends Edge {
};

class AdjacentTo extends Edge {
};

Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.

Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.

Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"

Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.

Oracle "(+)" Operator

That's Oracle specific notation for an OUTER JOIN, because the ANSI-89 format (using a comma in the FROM clause to separate table references) didn't standardize OUTER joins.

The query would be re-written in ANSI-92 syntax as:

   SELECT ...
     FROM a
LEFT JOIN b ON b.id = a.id

This link is pretty good at explaining the difference between JOINs.


It should also be noted that even though the (+) works, Oracle recommends not using it:

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:

Select folder dialog WPF

If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Problem with Access strategies

As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties). By default, the placement of the @Id annotation gives the default access strategy. When placed on a field, Hibernate will assume field-based access. Placed on the identifier getter, Hibernate will use property-based access.

Field-based access

When using field-based access, adding other entity-level methods is much more flexible because Hibernate won’t consider those part of the persistence state

@Entity
public class Simple {

@Id
private Integer id;

@OneToMany(targetEntity=Student.class, mappedBy="college", 
fetch=FetchType.EAGER)
private List<Student> students;

//getter +setter
}

Property-based access

When using property-based access, Hibernate uses the accessors for both reading and writing the entity state

@Entity
public class Simple {

private Integer id;
private List<Student> students;

@Id
public Integer getId() {
    return id;
}

public void setId( Integer id ) {
    this.id = id;
}
@OneToMany(targetEntity=Student.class, mappedBy="college", 
fetch=FetchType.EAGER)
public List<Student> getStudents() {
   return students;
}
public void setStudents(List<Student> students) {
    this.students = students;
}

}

But you can't use both Field-based and Property-based access at the same time. It will show like that error for you

For more idea follow this

proper hibernate annotation for byte[]

i fixed My issue by adding the annotation of @Lob which will create the byte[] in oracle as blob , but this annotation will create the field as oid which not work properly , To make byte[] created as bytea i made customer Dialect for postgres as below

Public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
    public PostgreSQLDialectCustom() {
        System.out.println("Init PostgreSQLDialectCustom");
        registerColumnType( Types.BLOB, "bytea" );

      }

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
 }

Also need to override parameter for the Dialect

spring.jpa.properties.hibernate.dialect=com.ntg.common.DBCompatibilityHelper.PostgreSQLDialectCustom

more hint can be found her : https://dzone.com/articles/postgres-and-oracle

Efficient SQL test query or validation query that will work across all (or most) databases

I use this for Firebird

select 1 from RDB$RELATION_FIELDS rows 1

How can I put a ListView into a ScrollView without it collapsing?

Here's my solution. I'm fairly new to the Android platform, and I'm sure this is a bit hackish, especially in the part about calling .measure directly, and setting the LayoutParams.height property directly, but it works.

All you have to do is call Utility.setListViewHeightBasedOnChildren(yourListView) and it will be resized to exactly accommodate the height of its items.

public class Utility {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if (listItem instanceof ViewGroup) {
                listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
             }

             listItem.measure(0, 0);
             totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}

Difference in days between two dates in Java?

The diff / (24 * etc) does not take Timezone into account, so if your default timezone has a DST in it, it can throw the calculation off.

This link has a nice little implementation.

Here is the source of the above link in case the link goes down:

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  //assert: startDate must be before endDate  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

and

/** Using Calendar - THE CORRECT (& Faster) WAY**/  
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
  //assert: startDate must be before endDate  
  int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
  long endInstant = endDate.getTimeInMillis();  
  int presumedDays = 
    (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
  Calendar cursor = (Calendar) startDate.clone();  
  cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
  long instant = cursor.getTimeInMillis();  
  if (instant == endInstant)  
    return presumedDays;

  final int step = instant < endInstant ? 1 : -1;  
  do {  
    cursor.add(Calendar.DAY_OF_MONTH, step);  
    presumedDays += step;  
  } while (cursor.getTimeInMillis() != endInstant);  
  return presumedDays;  
}

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

Give hibernate.connection.url as "jdbc:oracle:thin:@127.0.0.1:1521:xe" then you can solve above issue. Because oracle's default SID is "xe" so we should give like this. When I gave like this data has been inserted into DB without any SQL exceptions, it's my real time experience.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

As Ponies says in a comment, you cannot mix OLAP functions with aggregate functions.

Perhaps it's easier to get the last completion date for each employee, and join that to a dataset containing the last completion date for each of the three targeted courses.

This is an untested idea that should hopefully put you down the right path:

  SELECT employee_number,
         course_code,
         MAX(course_completion_date) AS max_date,
         lcc.LAST_COURSE_COMPLETED
    FROM employee_course_completion ecc
         LEFT JOIN (
             SELECT employee_number,
                    MAX(course_completion_date) AS LAST_COURSE_COMPLETED
               FROM employee_course_completion
              WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
         ) lcc
         ON lcc.employee_number = ecc.employee_number
   WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code, lcc.LAST_COURSE_COMPLETED

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

In my case, the backup file was compressed, but the file extension didn't indicate this, didn't end in .zip, .tgz, etc. Once I decompressed my backup file I was able to import it.

is of a type that is invalid for use as a key column in an index

Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:

  1. use a hash of the key value
    • Create a column on nchar(40) (for a sha1 hash, for example),
    • put a unique key on the hash column.
    • generate the hash when saving or updating the record
  2. triggers to query the table for an existing match on insert or update.

Hashing comes with the caveat that one day, you might get a collision.

Triggers will scan the entire table.

Over to you...

How to get a list of MySQL views?

This will work.

    USE INFORMATION_SCHEMA;
    SELECT TABLE_SCHEMA, TABLE_NAME
    FROM information_schema.tables
    WHERE TABLE_TYPE LIKE 'VIEW';

Facebook Oauth Logout

@Christoph: just adding someting . i dont think so this is a correct way.to logout at both places at the same time.(<a href="/logout" onclick="FB.logout();">Logout</a>).

Just add id to the anchor tag . <a id='fbLogOut' href="/logout" onclick="FB.logout();">Logout</a>



$(document).ready(function(){

$('#fbLogOut').click(function(e){ 
     e.preventDefault();
      FB.logout(function(response) {
            // user is now logged out
            var url = $(this).attr('href');
            window.location= url;


        });
});});

Map enum in JPA with fixed values?

My own solution to solve this kind of Enum JPA mapping is the following.

Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:

public interface IDbValue<T extends java.io.Serializable> {

    T getDbVal();

}

Step 2 - Implement a custom generic JPA converter as follows:

import javax.persistence.AttributeConverter;

public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
        implements AttributeConverter<E, T> {

    private final Class<E> clazz;

    public EnumDbValueConverter(Class<E> clazz){
        this.clazz = clazz;
    }

    @Override
    public T convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getDbVal();
    }

    @Override
    public E convertToEntityAttribute(T dbData) {
        if (dbData == null) {
            return null;
        }
        for (E e : clazz.getEnumConstants()) {
            if (dbData.equals(e.getDbVal())) {
                return e;
            }
        }
        // handle error as you prefer, for example, using slf4j:
        // log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
        return null;
    }

}

This class will convert the enum value E to a database field of type T (e.g. String) by using the getDbVal() on enum E, and vice versa.

Step 3 - Let the original enum implement the interface we defined in step 1:

public enum Right implements IDbValue<Integer> {
    READ(100), WRITE(200), EDITOR (300);

    private final Integer dbVal;

    private Right(Integer dbVal) {
        this.dbVal = dbVal;
    }

    @Override
    public Integer getDbVal() {
        return dbVal;
    }
}

Step 4 - Extend the converter of step 2 for the Right enum of step 3:

public class RightConverter extends EnumDbValueConverter<Integer, Right> {
    public RightConverter() {
        super(Right.class);
    }
}

Step 5 - The final step is to annotate the field in the entity as follows:

@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;

Conclusion

IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.

For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:

  • implement the interface IDbValue on your enum;
  • extend the EnumDbValueConverter with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);
  • annotate the enum attribute with @Convert from javax.persistence package.

Hope this helps.

Calculating the angle between the line defined by two points

Had a need for similar functionality myself, so after much hair pulling I came up with the function below

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 * 
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

Python progression path - From apprentice to guru

Understand Introspection

  • write a dir() equivalent
  • write a type() equivalent
  • figure out how to "monkey-patch"
  • use the dis module to see how various language constructs work

Doing these things will

  • give you some good theoretical knowledge about how python is implemented
  • give you some good practical experience in lower-level programming
  • give you a good intuitive feel for python data structures

How to check for an undefined or null variable in JavaScript?

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

For Java, from a command line:

java -version

will indicate whether it's 64-bit or not.

Output from the console on my Ubuntu box:

java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)

IE will indicate 64-bit versions in the About dialog, I believe.

jQuery vs. javascript?

Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.

If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.

XSD - how to allow elements in any order any number of times?

This is what finally worked for me:

<xsd:element name="bar">
  <xsd:complexType>
    <xsd:sequence>
      <!--  Permit any of these tags in any order in any number     -->
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element name="child1" type="xsd:string" />
        <xsd:element name="child2" type="xsd:string" />
        <xsd:element name="child3" type="xsd:string" />
      </xsd:choice>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

PHP Configuration: It is not safe to rely on the system's timezone settings

I happened to have to set up Apache & PHP on two laptops recently. After much weeping and gnashing of teeth, I noticed in phpinfo's output that (for whatever reason: not paying attention during PHP install, bad installer) Apache expected php.ini to be somewhere where it wasn't.

Two choices:

  1. put it where Apache thinks it should be or
  2. point Apache at the true location of your php.ini

... and restart Apache. Timezone settings should be recognized at that point.

How to write console output to a txt file

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

SQL Server 2008: TOP 10 and distinct together

I think the problem is that you want one result for each p.id?

But you are getting "duplicate" results for some p.id's, is that right?

The DISTINCT keyword applies to the entire result set, so applies to pl.nm, pl.val, pl.txt_val, not just p.id.

You need something like

SELECT TOP 10 p.id, max( p1.nm ), max (p1.val), ...
FROM ...
GROUP BY p.id

Won't need the distinct keyword then.

MySQL "NOT IN" query

Unfortunately it seems to be a issue with MySql usage of "NOT IN" clause, the screen-shoot below shows the sub-query option returning wrong results:

mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name           | Value                        |
+-------------------------+------------------------------+
| innodb_version          | 1.1.8                        |
| protocol_version        | 10                           |
| slave_type_conversions  |                              |
| version                 | 5.5.21                       |
| version_comment         | MySQL Community Server (GPL) |
| version_compile_machine | x86_64                       |
| version_compile_os      | Linux                        |
+-------------------------+------------------------------+
7 rows in set (0.07 sec)

mysql> select count(*) from TABLE_A where TABLE_A.Pkey not in (select distinct TABLE_B.Fkey from TABLE_B );
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.07 sec)

mysql> select count(*) from TABLE_A left join TABLE_B on TABLE_A.Pkey = TABLE_B.Fkey where TABLE_B.Pkey is null;
+----------+
| count(*) |
+----------+
|      139 |
+----------+
1 row in set (0.06 sec)

mysql> select count(*) from TABLE_A where NOT EXISTS (select * FROM TABLE_B WHERE TABLE_B.Fkey = TABLE_A.Pkey );
+----------+
| count(*) |
+----------+
|      139 |
+----------+
1 row in set (0.06 sec)

mysql> 

Eclipse 3.5 Unable to install plugins

There is no need of doing such hectic stuffs. Find in your system where there is "SDK Manager".(incase of windows). Suppose your sdk manager is in E:\Android-9. Go to that path double click the SDK manager ;it will automatically start to download from https://dl-ssl.google.com/../..

Initially you will se it is failing. On the window that appears there will be 'settings' menu. Click on that set the proxy and port. and it will start downloading.

The solution in one sentence is "Don't use eclipse for the download;directly use Android sdk manager and your problem is resolved". Let me know if you have any futhur queries on this issue.

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

How can I simulate a click to an anchor tag?

well, you can very quickly test the click dispatch via jQuery like so

$('#link-id').click();

If you're still having problem with click respecting the target, you can always do this

$('#link-id').click( function( event, anchor )
{
  window.open( anchor.href, anchor.target, '' );
  event.preventDefault();
  return false;
});

How can I make my layout scroll both horizontally and vertically?

I was able to find a simple way to achieve both scrolling behaviors.

Here is the xml for it:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:scrollbars="vertical">

    <HorizontalScrollView 
        android:layout_width="320px" android:layout_height="fill_parent">

        <TableLayout
            android:id="@+id/linlay" android:layout_width="320px"
            android:layout_height="fill_parent" android:stretchColumns="1"
            android:background="#000000"/>

    </HorizontalScrollView>

</ScrollView>

Distinct() with lambda?

This will do what you want but I don't know about performance:

var distinctValues =
    from cust in myCustomerList
    group cust by cust.CustomerId
    into gcust
    select gcust.First();

At least it's not verbose.

SSIS Connection Manager Not Storing SQL Password

It happened with me as well and fixed in following way:

Created expression based connection string and saved password in a variable and used it.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?

And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.

How to get the size of a JavaScript object?

I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.

<html>
<script>
var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size
}

function scaffold()
{
  console.log("processing Scaffold...");
  a = new Array
}

function start()
{
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){
    a[i]={"some" : "thing"}
  }
  console.log("done...")
}

function tearDown()
{
  console.log("processing teardown");
  a.length=0
}

</script>
<body>
    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>
    <br/>
</body>
</html>

Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc. Hope this helps.

Referencing system.management.automation.dll in Visual Studio

I couldn't get the SDK to install properly (some of the files seemed unsigned, something like that). I found another solution here and that seems to work okay for me. It doesn't require installation of new files at all. Basically, what you do is:

Edit the .csproj file in a text editor, and add:

<Reference Include="System.Management.Automation" />

to the relevant section.

Hope this helps.

Alternative to mysql_real_escape_string without connecting to DB

From further research, I've found:

http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html

Security Fix:

An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.

This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.

Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().

However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.

Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.

To set this mode for the current connection, enter the following SQL statement:

SET sql_mode='NO_BACKSLASH_ESCAPES';

You can also set the mode globally for all clients:

SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';

This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)

See also Bug#8303.

A cycle was detected in the build path of project xxx - Build Path Problem

Mark circular dependencies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error.

In Eclipse go to:

Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies

When to use RDLC over RDL reports?

I have always thought the different between RDL and RDLC is that RDL are used for SQL Server Reporting Services and RDLC are used in Visual Studio for client side reporting. The implemenation and editor are almost identical. RDL stands for Report Defintion Language and RDLC Report Definition Language Client-side.

I hope that helps.

JavaScript for detecting browser language preference

If you have control of a backend and are using django, a 4 line implementation of Dan's idea is:

def get_browser_lang(request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
    return JsonResponse({'response': request.META['HTTP_ACCEPT_LANGUAGE']})
else:
    return JsonResponse({'response': settings.DEFAULT_LANG})

then in urls.py:

url(r'^browserlang/$', views.get_browser_lang, name='get_browser_lang'),

and on the front end:

$.get(lg('SERVER') + 'browserlang/', function(data){
    var lang_code = data.response.split(',')[0].split(';')[0].split('-')[0];
});

(you have to set DEFAULT_LANG in settings.py of course)

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I got the same problem and I just added the content of ~/.ssh/id_rsa.pub to my account in GitHub. After that just try again git push origin master, it should work.

Hibernate: "Field 'id' doesn't have a default value"

Please check whether the Default value for the column id in particular table.if not make it as default

How can I close a window with Javascript on Mozilla Firefox 3?

function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();

Inline elements shifting when made bold on hover

I had a problem similar to yours. I wanted my links to get bold when you hover over them but not only in the menu but also in the text. As you cen guess it would be a real chore figuring out all the different widths. The solution is pretty simple:

Create a box that contains the link text in bold but coloured like your background and but your real link above it. Here's an example from my page:

CSS:

.hypo { font-weight: bold; color: #FFFFE0; position: static; z-index: 0; }
.hyper { position: absolute; z-index: 1; }

Of course you need to replace #FFFFE0 by the background colour of your page. The z-indices don't seem to be necessary but I put them anyway (as the "hypo" element will occur after the "hyper" element in the HTML-Code). Now, to put a link on your page, include the following:

HTML:

You can find foo <a href="http://bar.com" class="hyper">here</a><span class="hypo">here</span>

The second "here" will be invisible and hidden below your link. As this is a static box with your link text in bold, the rest of your text won't shift any longer as it is already shifted before you hover over the link.

Hope I was able to help :).

So long

How to return XML in ASP.NET?

Seems like at least 10 questions rolled into one here, a couple points.

Response.Clear - it really depends on what else is going on in the app - if you have httpmodules early in the pipeline that might be writing stuff you don't want - then clear it. Test it and find out. Fiddler or Wireshark useful for this.

Content Type to text/xml - yup - good idea - read up on HTTP spec as to why this is important. IMO anyone doing web work should have read the 1.0 and 1.1 spec at least once.

Encoding - how is your xml encoded - if it is utf-8, then say so, if not, say something else appropriate, just make sure they all match.

Page - personally, would use ashx or httpmodule, if you are using page, and want it a bit faster, get rid of autoeventwireup and bind the event handlers manually.

Would probably be a bit of a waste of memory to dump the xml into a string first, but it depends a lot on the size of the xml as to whether you would ever notice.

As others have suggested, saving the xml to the output stream probably the fastest, I would normally do that, but if you aren't sure, test it, don't rely on what you read on the interweb. Don't just believe anything I say.

For another approach, if the xml doesn't change that much, you could just write it to the disk and serve the file directly, which would likely be quite performant, but like everything in programming, it depends...

How to create a generic array in Java?

You can do this:

E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];

This is one of the suggested ways of implementing a generic collection in Effective Java; Item 26. No type errors, no need to cast the array repeatedly. However this triggers a warning because it is potentially dangerous, and should be used with caution. As detailed in the comments, this Object[] is now masquerading as our E[] type, and can cause unexpected errors or ClassCastExceptions if used unsafely.

As a rule of thumb, this behavior is safe as long as the cast array is used internally (e.g. to back a data structure), and not returned or exposed to client code. Should you need to return an array of a generic type to other code, the reflection Array class you mention is the right way to go.


Worth mentioning that wherever possible, you'll have a much happier time working with Lists rather than arrays if you're using generics. Certainly sometimes you don't have a choice, but using the collections framework is far more robust.

Connection pooling options with JDBC: DBCP vs C3P0

Dbcp is production ready if configured properly.

It is for example used on a commerce Website of 350000 visitors/ day and with pools of 200 connections.

It handles very well timeouts provided you configure it correctly.

Version 2 is on progress and it has a background which makes it reliable since Many Production problems have been tackled.

We use it for our batch server solution and it has been running hundreds of batches That work on millions of lines in database.

Performance tests run by tomcat jdbc pool show it has better performance than cp30.

Stop UIWebView from "bouncing" vertically?

Brad's method worked for me. If you use it you might want to make it a little safer.

id scrollView = [yourWebView.subviews objectAtIndex:0];
if( [scrollView respondsToSelector:@selector(setAllowsRubberBanding:)] )
{
    [scrollView performSelector:@selector(setAllowsRubberBanding:) withObject:NO];
}

If apple changes something then the bounce will come back - but at least your app won't crash.

How to store file name in database, with other info while uploading image to server using PHP?

Your part:

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

";

Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.

What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".

Try adding do

$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");

and change the if($result) to $realresult

I suspect your query is failing, perhaps you have additional columns or something?

Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.

What does 'const static' mean in C and C++?

It's missing an 'int'. It should be:

const static int foo = 42;

In C and C++, it declares an integer constant with local file scope of value 42.

Why 42? If you don't already know (and it's hard to believe you don't), it's a refernce to the Answer to Life, the Universe, and Everything.

How do I base64 encode a string efficiently using Excel VBA?

You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)      

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument 
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.Text 

  Set objNode = Nothing
  Set objXML = Nothing
End Function

Where does Console.WriteLine go in ASP.NET?

if you happened to use NLog in your ASP.net project, you can add a Debugger target:

<targets>
    <target name="debugger" xsi:type="Debugger"
            layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>

and writes logs to this target for the levels you want:

<rules>
    <logger name="*" minlevel="Trace" writeTo="debugger" />

now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).

Where do I find the current C or C++ standard documents?

PDF versions of the standard

As of 1st September 2014, the best locations by price for C and C++ standards documents in PDF are:

You cannot usually get old revisions of a standard (any standard) directly from the standards bodies shortly after a new edition of the standard is released. Thus, standards for C89, C90, C99, C++98, C++03 will be hard to find for purchase from a standards body. If you need an old revision of a standard, check Techstreet as one possible source. For example, it can still provide the Canadian version CAN/CSA-ISO/IEC 9899:1990 standard in PDF, for a fee.

Non-PDF electronic versions of the standard

Print versions of the standard

Print copies of the standards are available from national standards bodies and ISO but are very expensive.

If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt's book The Annotated ANSI Standard at Amazon, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).

The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):

Standards committee draft versions (free)

The working drafts for future standards are often available from the committee websites:

If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:

For C:

(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")

For C++:

Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.

Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.


It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version.


The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers:


The current draft of the standard is maintained as LaTeX sources on Github. These sources can be converted to HTML using cxxdraft-htmlgen. The following sites maintain HTML pages so generated:

Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.

How do I monitor the computer's CPU, memory, and disk usage in Java?

Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"

You can use the class MProcess,

/*
 *Md. Mukit Hasan
 *CSE-JU,35
 **/
import java.io.*;

public class MProcessor {

public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }

}

Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.

--Mukit Hasan

What are some resources for getting started in operating system development?

As mentioned above, the OSDev Wiki is (by far) the best source for OS development. For those of you who speak German, the lowlevel.eu Wiki is also great. Something relatively unknown Incitatus OS, a simple kernel with a tiny set of userspace apps. It's great to use for getting into the complicated topic of OS development.

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

Without seeing more of the surrounding code I can't give a definite answer, but I have two theories.

  1. You're not using UIViewController's designated initializer initWithNibName:bundle:. Try using it instead of just init.

  2. Also, self may be one of the tab bar controller's view controllers. Always present view controllers from the topmost view controller, which means in this case ask the tab bar controller to present the overlay view controller on behalf of the view controller. You can still keep any callback delegates to the real view controller, but you must have the tab bar controller present and dismiss.

How to give a Blob uploaded as FormData a file name?

Adding this here as it doesn't seem to be here.

Aside from the excellent solution of form.append("blob",blob, filename); you can also turn the blob into a File instance:

var blob = new Blob([JSON.stringify([0,1,2])], {type : 'application/json'});
var fileOfBlob = new File([blob], 'aFileName.json');
form.append("upload", fileOfBlob);

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}

MySQL match() against() - order by relevance and column?

This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:

SELECT pages.*,
       MATCH (head, body) AGAINST ('some words') AS relevance,
       MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC

-- alternatively:
ORDER BY title_relevance + relevance DESC

An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.

Getting a link to go to a specific section on another page

I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID attribute. To support older browsers, you'll need to change:

<div id="timeline" name="timeline" ...>

To the old format:

<a name="timeline" />

You'll then be able to navigate to /academics/page.html#timeline and jump right to that section.

Also, check out this similar question.

How to set environment via `ng serve` in Angular 6

You can use command ng serve -c dev for development environment ng serve -c prod for production environment

while building also same applies. You can use ng build -c dev for dev build

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

I was solved this problem too: Just reinstall node to LTS version by nvm:

nvm install --lts

nvm use --lts

Then rm -rf node_modules And npm i

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Getting scroll bar width using JavaScript

I think this will be simple and fast -

var scrollWidth= window.innerWidth-$(document).width()

How do you remove an array element in a foreach loop?

foreach($display_related_tags as $key => $tag_name)
{
    if($tag_name == $found_tag['name'])
        unset($display_related_tags[$key];
}

Android 8: Cleartext HTTP traffic not permitted

It could be useful for someone.

We recently had the same issue for Android 9, but we only needed to display some Urls within WebView, nothing very special. So adding android:usesCleartextTraffic="true" to Manifest worked, but we didn't want to compromise security of the whole app for this. So the fix was in changing links from http to https

Android EditText Max Length

If you used maxLength = 6 , some times what you are entering those characters are added in top of the keyboard called suggestions. So when you deleting entered letters that time it will delete suggestions first and then actual text inside EditText. For that you need to remove the suggestions.just add

android:inputType="textNoSuggestions"` 

or

android:inputType="textFilter"

It will remove those suggestions.

Reset C int array to zero : the fastest way?

memset (from <string.h>) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.

memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements

By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm>):

std::fill(myarray, myarray+N, 0);

which may be optimized automatically into a memset; I'm quite sure that it will work as fast as memset for ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.

milliseconds to time in javascript

Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return hrs + ':' + mins + ':' + secs + '.' + ms;
}

If you want it formatted as hh:mm:ss.sss then use:

_x000D_
_x000D_
function msToTime(s) {_x000D_
_x000D_
  // Pad to 2 or 3 digits, default is 2_x000D_
  function pad(n, z) {_x000D_
    z = z || 2;_x000D_
    return ('00' + n).slice(-z);_x000D_
  }_x000D_
_x000D_
  var ms = s % 1000;_x000D_
  s = (s - ms) / 1000;_x000D_
  var secs = s % 60;_x000D_
  s = (s - secs) / 60;_x000D_
  var mins = s % 60;_x000D_
  var hrs = (s - mins) / 60;_x000D_
_x000D_
  return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);_x000D_
}_x000D_
_x000D_
console.log(msToTime(55018))
_x000D_
_x000D_
_x000D_

Using some recently added language features, the pad function can be more concise:

_x000D_
_x000D_
function msToTime(s) {_x000D_
    // Pad to 2 or 3 digits, default is 2_x000D_
  var pad = (n, z = 2) => ('00' + n).slice(-z);_x000D_
  return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);_x000D_
}_x000D_
_x000D_
// Current hh:mm:ss.sss UTC_x000D_
console.log(msToTime(new Date() % 8.64e7))
_x000D_
_x000D_
_x000D_

Error while trying to run project: Unable to start program. Cannot find the file specified

I had this issue on VS2008: I removed the .suo; .ncb; and user project file, then restarted the solution and it fixed the problem for me.

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

Get Path from another app (WhatsApp)

protected void onCreate(Bundle savedInstanceState) { /* * Your OnCreate */ Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType();

//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}

How do I find the stack trace in Visual Studio?

For Visual Studio 2019, the shortcut (while debugging and stopped at a breakpoint) is:

Ctrl+Alt+C and now you can also use Ctrl+L

The screenshot is pretty old. Here is one for Visual Studio 2019 (under the debug menu):

Visual Studio 2019 Call Stack Menu Option

How to clamp an integer to some range?

Whatever happened to my beloved readable Python language? :-)

Seriously, just make it a function:

def addInRange(val, add, minval, maxval):
    newval = val + add
    if newval < minval: return minval
    if newval > maxval: return maxval
    return newval

then just call it with something like:

val = addInRange(val, 7, 0, 42)

Or a simpler, more flexible, solution where you do the calculation yourself:

def restrict(val, minval, maxval):
    if val < minval: return minval
    if val > maxval: return maxval
    return val

x = restrict(x+10, 0, 42)

If you wanted to, you could even make the min/max a list so it looks more "mathematically pure":

x = restrict(val+7, [0, 42])

SameSite warning Chrome 77

This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.

It has nothing to do with your code. It is something their web servers will have to support.

Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site

February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.

For the full Chrome release schedule, see here.

I solved same problem by adding in response header

response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");

SameSite prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.

SameSite cookies explained here

Please refer this before applying any option.

Hope this helps you.

How to disable editing of elements in combobox for c#?

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

How can I remove Nan from list Python/NumPy

Another way to do it would include using filter like this:

countries = list(filter(lambda x: str(x) != 'nan', countries))

How can I scale an image in a CSS sprite

Old post, but here's what I did using background-size:cover; (hat tip to @Ceylan Pamir)...

EXAMPLE USAGE
Horizontal circle flipper (hover on front side image, flips to back with different image).

EXAMPLE SPRITE
480px x 240px

EXAMPLE FINAL SIZE
Single image @ 120px x 120px

GENERIC CODE
.front {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:0px 0px;}

.back {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:-120px 0px;}

ABBREVIATED CASE FIDDLE
http://jsfiddle.net/zuhloobie/133esq63/2/

How do I check if an object has a specific property in JavaScript?

Showing how to use this answer

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

We can use indexOf as well, I prefer includes

AngularJS: How to make angular load script inside ng-include?

I tried using Google reCAPTCHA explicitly. Here is the example:

// put somewhere in your index.html
<script type="text/javascript">
var onloadCallback = function() {
  grecaptcha.render('your-recaptcha-element', {
    'sitekey' : '6Ldcfv8SAAAAAB1DwJTM6T7qcJhVqhqtss_HzS3z'
  });
};

//link function of Angularjs directive
link: function (scope, element, attrs) {
  ...
  var domElem = '<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>';
  $('#your-recaptcha-element').append($compile(domElem)(scope));
}

Set up adb on Mac OS X

Download Andriod Platform Tools for macOS from:

https://developer.android.com/studio/releases/platform-tools

Extract to your somewhere e.g ~/installs/platform-tools

Add that folder to path by running:

echo 'export PATH=$PATH:~/installs/platform-tools' >> ~/.zshrc

Either restart terminal or run:

source ~/.zshrc

Assuming that you are using zsh.

How to get the selected value from RadioButtonList?

Technically speaking the answer is correct, but there is a potential problem remaining. string test = rb.SelectedValue is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.

string test = rb.SelectedValue;  //May work fine
SomeMethod(rb.SelectedValue);

where SomeMethod is expecting a string may not.

Sadly the rb.SelectedValue.ToString(); can save a few unexpected issues.

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

How to display list items on console window in C#

Actually you can do it pretty simple, since the list have a ForEach method and since you can pass in Console.WriteLine as a method group. The compiler will then use an implicit conversion to convert the method group to, in this case, an Action<int> and pick the most specific method from the group, in this case Console.WriteLine(int):

  var list = new List<int>(Enumerable.Range(0, 50));

  list.ForEach(Console.WriteLine);

Works with strings too =)

To be utterly pedantic (and I'm not suggesting a change to your answer - just commenting for the sake of interest) Console.WriteLine is a method group. The compiler then uses an implicit conversion from the method group to Action<int>, picking the most specific method (Console.WriteLine(int) in this case).

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

Extract month and year from a zoo::yearmon object

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

To sum up based on answers here and elsewhere:

  1. Check the .NET version of the app pool (e.g. 2.0 vs 4.0)
  2. Check that all IIS referenced modules are installed. In this case it was the AJAX extensions (probably not the case these days), but URL Rewrite is a common one.

How to find the extension of a file in C#?

string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);

The above method works fine with the firefox and IE , i am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png

but when i try to find the extension of file from googlechrome , i failed.

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

Attaching click event to a JQuery object not yet added to the DOM

Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.

I bound the table id to .delegate() and used a selector that describes the inputs.

e.g.

HTML

<table id="#mytable">
  <!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
  <tr><td><input name="qty_001" /></td></tr>
  <tr><td><input name="qty_002" /></td></tr>
  <tr><td><input name="qty_003" /></td></tr>
</table>

jQuery

$('#mytable').delegate('click', 'name^=["qty_"]', function() {
    console.log("you clicked cell #" . $(this).attr("name"));
});

How to join multiple lines of file names into one with custom delimiter?

This replaces the last comma with a newline:

ls -1 | tr '\n' ',' | sed 's/,$/\n/'

ls -m includes newlines at the screen-width character (80th for example).

Mostly Bash (only ls is external):

saveIFS=$IFS; IFS=$'\n'
files=($(ls -1))
IFS=,
list=${files[*]}
IFS=$saveIFS

Using readarray (aka mapfile) in Bash 4:

readarray -t files < <(ls -1)
saveIFS=$IFS
IFS=,
list=${files[*]}
IFS=$saveIFS

Thanks to gniourf_gniourf for the suggestions.

Add space between HTML elements only using CSS

If you want to align various items and you like to have same margin around all sides, you can use the following. Each element withing container, regardless of type, will receive the same surrounding margin.

enter image description here

.container {
  display: flex;
}
.container > * {
  margin: 5px;
}

If you wish to align items in a row, but have the first element touch the leftmost edge of container, and have all other elements be equally spaced, you can use this:

enter image description here

.container {
  display: flex;
}
.container > :first-child {
  margin-right: 5px;
}
.container > *:not(:first-child) {
  margin: 5px;
}

How to beautify JSON in Python?

A minimal in-python solution that colors json data supplied via the command line:

import sys
import json
from pygments import highlight, lexers, formatters

formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)

Inspired by pjson mentioned above. This code needs pygments to be installed.

Output example:

enter image description here

parsing a tab-separated file in Python

Like this:

>>> s='1\t2\t3\t4\t5'
>>> [x for x in s.split('\t')]
['1', '2', '3', '4', '5']

For a file:

# create test file:
>>> with open('tabs.txt','w') as o:
...    s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
...    print >>o, s

#read that file:
>>> with open('tabs.txt','r') as f:
...    LoL=[x.strip().split('\t') for x in f]
... 
>>> LoL
[['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 
 ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'], 
 ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'], 
 ['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
>>> LoL[2][3]
23

If you want the input transposed:

>>> with open('tabs.txt','r') as f:
...    LoT=zip(*(line.strip().split('\t') for line in f))
... 
>>> LoT[2][3]
'32'

Or (better still) use the csv module in the default distribution...

How to unapply a migration in ASP.NET Core with EF Core

To completely remove all migrations and start all over again, do the following:

dotnet ef database update 0
dotnet ef migrations remove

default select option as blank

If you are using Angular (2+), (or any other framework), you could add some logic. The logic would be: only display an empty option if the user did not select any other yet. So after the user selected an option, the empty option disappears.

For Angular (9) this would look something like this:

<select>
    <option *ngIf="(hasOptionSelected$ | async) === false"></option>
    <option *ngFor="let option of (options$ | async)[value]="option.id">{{ option.title }}</option>
</select>

Correct file permissions for WordPress

For those who have their wordpress root folder under their home folder:

** Ubuntu/apache

  1. Add your user to www-data group:

CREDIT Granting write permissions to www-data group

You want to call usermod on your user. So that would be:

sudo usermod -aG www-data yourUserName

** Assuming www-data group exists

  1. Check your user is in www-data group:

    groups yourUserName

You should get something like:

youUserName : youUserGroupName www-data

** youUserGroupName is usually similar to you user name

  1. Recursively change group ownership of the wp-content folder keeping your user ownership

    chown yourUserName:www-data -R youWebSiteFolder/wp-content/*

  2. Change directory to youWebSiteFolder/wp-content/

    cd youWebSiteFolder/wp-content

  3. Recursively change group permissions of the folders and sub-folders to enable write permissions:

    find . -type d -exec chmod -R 775 {} \;

** mode of `/home/yourUserName/youWebSiteFolder/wp-content/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)

  1. Recursively change group permissions of the files and sub-files to enable write permissions:

    find . -type f -exec chmod -R 664 {} \;

The result should look something like:

WAS:
-rw-r--r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html
CHANGED TO:
-rw-rw-r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html

Equivalent to:

chmod -R ug+rw foldername

Permissions will be like 664 for files or 775 for directories.

P.s. if anyone encounters error 'could not create directory' when updating a plugin, do:
server@user:~/domainame.com$ sudo chown username:www-data -R wp-content
when you are at the root of your domain.
Assuming: wp-config.php has
FTP credentials on LocalHost
define('FS_METHOD','direct');

Extract parameter value from url using regular expressions

Why dont you take the string and split it

Example on the url

var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"

you can do a split as

var params = url.split("?")[1].split("&");

You will get array of strings with params as name value pairs with "=" as the delimiter.

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Shortcut to comment out a block of code with sublime text

Ctrl-/ will insert // style commenting, for javascript, etc
Ctrl-/ will insert <!-- --> comments for HTML,
Ctrl-/ will insert # comments for Ruby,
..etc

But does not work perfectly on HTML <script> tags.

HTML <script> ..blah.. </script> tags:
Ctrl-/ twice (ie Ctrl-/Ctrl-/) will effectively comment out the line:

  • The first Ctrl-/ adds // to the beginning of the line,
    which comments out the script tag, but adds "//" text to your webpage.
  • The second Ctrl-/ then surrounds that in <!-- --> style comments, which accomplishes the task.

Ctrl--Shift-/ does not produce multi-line comments on HTML (or even single line comments), but does
add /* */ style multi-line comments in Javascript, text, and other file formats.

--

[I added as a new answer since I could not add comments.
I included this info because this is the info I was looking for, and this is the only related StackOverflow page from my search results.
I since discovered the / / trick for HTML script tags and decided to share this additional information, since it requires a slight variation of the usual catch-all (and reported above)
/ and Ctrl--Shift-/ method of commenting out one's code in sublime.]

How to debug SSL handshake using cURL?

curl probably does have some options for showing more information but for things like this I always use openssl s_client

With the -debug option this gives lots of useful information

Maybe I should add that this also works with non HTTP connections. So if you are doing "https", try the curl commands suggested below. If you aren't or want a second option openssl s_client might be good

Multiple INSERT statements vs. single INSERT with multiple VALUES

Addition: SQL Server 2012 shows some improved performance in this area but doesn't seem to tackle the specific issues noted below. This should apparently be fixed in the next major version after SQL Server 2012!

Your plan shows the single inserts are using parameterised procedures (possibly auto parameterised) so parse/compile time for these should be minimal.

I thought I'd look into this a bit more though so set up a loop (script) and tried adjusting the number of VALUES clauses and recording the compile time.

I then divided the compile time by the number of rows to get the average compile time per clause. The results are below

Graph

Up until 250 VALUES clauses present the compile time / number of clauses has a slight upward trend but nothing too dramatic.

Graph

But then there is a sudden change.

That section of the data is shown below.

+------+----------------+-------------+---------------+---------------+
| Rows | CachedPlanSize | CompileTime | CompileMemory | Duration/Rows |
+------+----------------+-------------+---------------+---------------+
|  245 |            528 |          41 |          2400 | 0.167346939   |
|  246 |            528 |          40 |          2416 | 0.162601626   |
|  247 |            528 |          38 |          2416 | 0.153846154   |
|  248 |            528 |          39 |          2432 | 0.157258065   |
|  249 |            528 |          39 |          2432 | 0.156626506   |
|  250 |            528 |          40 |          2448 | 0.16          |
|  251 |            400 |         273 |          3488 | 1.087649402   |
|  252 |            400 |         274 |          3496 | 1.087301587   |
|  253 |            400 |         282 |          3520 | 1.114624506   |
|  254 |            408 |         279 |          3544 | 1.098425197   |
|  255 |            408 |         290 |          3552 | 1.137254902   |
+------+----------------+-------------+---------------+---------------+

The cached plan size which had been growing linearly suddenly drops but CompileTime increases 7 fold and CompileMemory shoots up. This is the cut off point between the plan being an auto parametrized one (with 1,000 parameters) to a non parametrized one. Thereafter it seems to get linearly less efficient (in terms of number of value clauses processed in a given time).

Not sure why this should be. Presumably when it is compiling a plan for specific literal values it must perform some activity that does not scale linearly (such as sorting).

It doesn't seem to affect the size of the cached query plan when I tried a query consisting entirely of duplicate rows and neither affects the order of the output of the table of the constants (and as you are inserting into a heap time spent sorting would be pointless anyway even if it did).

Moreover if a clustered index is added to the table the plan still shows an explicit sort step so it doesn't seem to be sorting at compile time to avoid a sort at run time.

Plan

I tried to look at this in a debugger but the public symbols for my version of SQL Server 2008 don't seem to be available so instead I had to look at the equivalent UNION ALL construction in SQL Server 2005.

A typical stack trace is below

sqlservr.exe!FastDBCSToUnicode()  + 0xac bytes  
sqlservr.exe!nls_sqlhilo()  + 0x35 bytes    
sqlservr.exe!CXVariant::CmpCompareStr()  + 0x2b bytes   
sqlservr.exe!CXVariantPerformCompare<167,167>::Compare()  + 0x18 bytes  
sqlservr.exe!CXVariant::CmpCompare()  + 0x11f67d bytes  
sqlservr.exe!CConstraintItvl::PcnstrItvlUnion()  + 0xe2 bytes   
sqlservr.exe!CConstraintProp::PcnstrUnion()  + 0x35e bytes  
sqlservr.exe!CLogOp_BaseSetOp::PcnstrDerive()  + 0x11a bytes    
sqlservr.exe!CLogOpArg::PcnstrDeriveHandler()  + 0x18f bytes    
sqlservr.exe!CLogOpArg::DeriveGroupProperties()  + 0xa9 bytes   
sqlservr.exe!COpArg::DeriveNormalizedGroupProperties()  + 0x40 bytes    
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x18a bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!COptExpr::DeriveGroupProperties()  + 0x146 bytes   
sqlservr.exe!CQuery::PqoBuild()  + 0x3cb bytes  
sqlservr.exe!CStmtQuery::InitQuery()  + 0x167 bytes 
sqlservr.exe!CStmtDML::InitNormal()  + 0xf0 bytes   
sqlservr.exe!CStmtDML::Init()  + 0x1b bytes 
sqlservr.exe!CCompPlan::FCompileStep()  + 0x176 bytes   
sqlservr.exe!CSQLSource::FCompile()  + 0x741 bytes  
sqlservr.exe!CSQLSource::FCompWrapper()  + 0x922be bytes    
sqlservr.exe!CSQLSource::Transform()  + 0x120431 bytes  
sqlservr.exe!CSQLSource::Compile()  + 0x2ff bytes   

So going off the names in the stack trace it appears to spend a lot of time comparing strings.

This KB article indicates that DeriveNormalizedGroupProperties is associated with what used to be called the normalization stage of query processing

This stage is now called binding or algebrizing and it takes the expression parse tree output from the previous parse stage and outputs an algebrized expression tree (query processor tree) to go forward to optimization (trivial plan optimization in this case) [ref].

I tried one more experiment (Script) which was to re-run the original test but looking at three different cases.

  1. First Name and Last Name Strings of length 10 characters with no duplicates.
  2. First Name and Last Name Strings of length 50 characters with no duplicates.
  3. First Name and Last Name Strings of length 10 characters with all duplicates.

Graph

It can clearly be seen that the longer the strings the worse things get and that conversely the more duplicates the better things get. As previously mentioned duplicates don't affect the cached plan size so I presume that there must be a process of duplicate identification when constructing the algebrized expression tree itself.

Edit

One place where this information is leveraged is shown by @Lieven here

SELECT * 
FROM (VALUES ('Lieven1', 1),
             ('Lieven2', 2),
             ('Lieven3', 3))Test (name, ID)
ORDER BY name, 1/ (ID - ID) 

Because at compile time it can determine that the Name column has no duplicates it skips ordering by the secondary 1/ (ID - ID) expression at run time (the sort in the plan only has one ORDER BY column) and no divide by zero error is raised. If duplicates are added to the table then the sort operator shows two order by columns and the expected error is raised.

Can I get Unix's pthread.h to compile in Windows?

pthread.h is a header for the Unix/Linux (POSIX) API for threads. A POSIX layer such as Cygwin would probably compile an app with #include <pthreads.h>.

The native Windows threading API is exposed via #include <windows.h> and it works slightly differently to Linux's threading.

Still, there's a replacement "glue" library maintained at http://sourceware.org/pthreads-win32/ ; note that it has some slight incompatibilities with MinGW/VS (e.g. see here).

Setting background images in JFrame

Try this :

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        f.pack();
        f.setVisible(true);
    }

}

By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

How to get MAC address of client using PHP?

First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:

public function win_os(){ 
    ob_start();
    system('ipconfig-a');
    $mycom=ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); // Find the position of Physical text
    $mac=substr($mycom,($pmac+36),17); // Get Physical Address

    return $mac;
   }

And your OS Linux Ubuntu or Linux then this code use:

public function unix_os(){
    ob_start();
    system('ifconfig -a');
    $mycom = ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    //Find the position of Physical text 
    $pmac = strpos($mycom, $findme); 
    $mac = substr($mycom, ($pmac + 37), 18);

    return $mac;
    }

This code may be work OS X.

"use database_name" command in PostgreSQL

You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"

user_name=# CREATE DATABASE testdatabase; 
user_name=# \c testdatabase 

At this point you might see the following output

You are now connected to database "testdatabase" as user "user_name".
testdatabase=#

Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.

How do I copy SQL Azure database to my local development server?

I just wanted to add a simplified version of dumbledad's answer, since it is the correct one.

  1. Export the Azure SQL Database to a BACPAC file on blob storage.
  2. From inside SQL Management studio, right-click your database, click "import data-tier application".
  3. You'll be prompted to enter the information to get to the BACPAC file on your Azure blob storage.
  4. Hit next a couple times and... Done!

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

python: how to get information about a function?

You can use pydoc.

Open your terminal and type python -m pydoc list.append

The advantage of pydoc over help() is that you do not have to import a module to look at its help text. For instance python -m pydoc random.randint.

Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b (python 3)

For more information python -m pydoc

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to use curl in a shell script?

url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi

Hide div after a few seconds

Using the jQuery timer will also allow you to have a name associated with the timers that are attached to the object. So you could attach several timers to an object and stop any one of them.

$("#myid").oneTime(1000, "mytimer1" function() {
  $("#something").hide();
}).oneTime(2000, "mytimer2" function() {
  $("#somethingelse").show();  
});

$("#myid").stopTime("mytimer2");

The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.

http://www.jslint.com/lint.html

How to URL encode a string in Ruby

I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.

ERB::Util.url_encode didn't work for my use:

helper.send(:url_encode, "http://example.com/?a=\11\15")
# => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"

Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape is better than using URI::Escape#escape. However, they both are behaving the same to me:

URI.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
URI::Parser.new.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Where do I find the current C or C++ standard documents?

C99 is available online. Quoted from www.open-std.org:

The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.

Need a row count after SELECT statement: what's the optimal SQL approach?

Just to add this because this is the top result in google for this question. In sqlite I used this to get the rowcount.

WITH temptable AS
  (SELECT one,two
   FROM
     (SELECT one, two
      FROM table3
      WHERE dimension=0
      UNION ALL SELECT one, two
      FROM table2
      WHERE dimension=0
      UNION ALL SELECT one, two
      FROM table1
      WHERE dimension=0)
   ORDER BY date DESC)
SELECT *
FROM temptable
LEFT JOIN
  (SELECT count(*)/7 AS cnt,
                        0 AS bonus
   FROM temptable) counter
WHERE 0 = counter.bonus

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

What's the difference between passing by reference vs. passing by value?

Here is an example that demonstrates the differences between pass by value - pointer value - reference:

void swap_by_value(int a, int b){
    int temp;

    temp = a;
    a = b;
    b = temp;
}   
void swap_by_pointer(int *a, int *b){
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}    
void swap_by_reference(int &a, int &b){
    int temp;

    temp = a;
    a = b;
    b = temp;
}

int main(void){
    int arg1 = 1, arg2 = 2;

    swap_by_value(arg1, arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 1 2

    swap_by_pointer(&arg1, &arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 2 1

    arg1 = 1;                               //reset values
    arg2 = 2;
    swap_by_reference(arg1, arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 2 1
}

The “passing by reference” method has an important limitation. If a parameter is declared as passed by reference (so it is preceded by the & sign) its corresponding actual parameter must be a variable.

An actual parameter referring to “passed by value” formal parameter may be an expression in general, so it is allowed to use not only a variable but also a literal or even a function invocation's result.

The function is not able to place a value in something other than a variable. It cannot assign a new value to a literal or force an expression to change its result.

PS: You can also check Dylan Beattie answer in the current thread that explains it in plain words.

How do I get monitor resolution in Python?

Using Linux Instead of regexp take the first line and take out the current resolution values.

Current resolution of display :0

>>> screen = os.popen("xrandr -q -d :0").readlines()[0]
>>> print screen
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 1920 x 1920
>>> width = screen.split()[7]
>>> print width
1920
>>> height = screen.split()[9][:-1]
>>> print height
1080
>>> print "Current resolution is %s x %s" % (width,height)
Current resolution is 1920 x 1080

This was done on xrandr 1.3.5, I don't know if the output is different on other versions, but this should make it easy to figure out.

Getting pids from ps -ef |grep keyword

Try

ps -ef | grep "KEYWORD" | awk '{print $2}'

That command should give you the PID of the processes with KEYWORD in them. In this instance, awk is returning what is in the 2nd column from the output.

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

How can I print literal curly-brace characters in a string and also use .format on it?

If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).

How do I programmatically set device orientation in iOS 7?

If you have a UIViewController that should stay in Portrait mode, simply add this override and you're all set.

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
}

The best part is there is no animation when this view is shown, it's just already in the correct orientation.

How to use MySQLdb with Python and Django in OSX 10.6?

pip install mysql-python

raised an error:

EnvironmentError: mysql_config not found

sudo apt-get install python-mysqldb

fixed the problem.

Number of lines in a file in Java

I have implemented another solution to the problem, I found it more efficient in counting rows:

try
(
   FileReader       input = new FileReader("input.txt");
   LineNumberReader count = new LineNumberReader(input);
)
{
   while (count.skip(Long.MAX_VALUE) > 0)
   {
      // Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
   }

   result = count.getLineNumber() + 1;                                    // +1 because line index starts at 0
}

Odd behavior when Java converts int to byte?

A quick algorithm that simulates the way that it work is the following:

public int toByte(int number) {
    int tmp = number & 0xff
    return (tmp & 0x80) == 0 ? tmp : tmp - 256;
}

How this work ? Look to daixtr answer. A implementation of exact algorithm discribed in his answer is the following:

public static int toByte(int number) {
    int tmp = number & 0xff;
    if ((tmp & 0x80) == 0x80) {
        int bit = 1;
        int mask = 0;
        for(;;) {
            mask |= bit;
            if ((tmp & bit) == 0) {
                bit <<=1;
                continue;
            }
            int left = tmp & (~mask);
            int right = tmp & mask;
            left = ~left;
            left &= (~mask);
            tmp = left | right;
            tmp = -(tmp & 0xff);
            break;
        }
    }
    return tmp;
}

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

Remove non-ASCII characters from CSV

As an alternative to sed or perl you may consider to use ed(1) and POSIX character classes.

Note: ed(1) reads the entire file into memory to edit it in-place, so for really large files you should use sed -i ..., perl -i ...

# see:
# - http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
# - http://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes

# test
echo $'aaa \177 bbb \200 \214 ccc \254 ddd\r\n' > testfile
ed -s testfile <<< $',l' 
ed -s testfile <<< $'H\ng/[^[:graph:][:space:][:cntrl:]]/s///g\nwq'
ed -s testfile <<< $',l'

Fragment MyFragment not attached to Activity

I had a similar error message "Fragment MyFragment not attached to Context" in Xamarine Android.

this error messege getting because of this resource calling

button.Text = Resources.GetString(Resource.String.please_wait)

I did fix that by using in Xamarine Android.

if (Context != null && IsAdded){ 
    button.Text = Resources.GetString(Resource.String.please_wait);
}

HTML button onclick event

<body>
"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

Yarn: How to upgrade yarn version using terminal?

npm install --global yarn
npm upgrade --global yarn 

This should work.

How to make this Header/Content/Footer layout using CSS?

Using flexbox, this is easy to achieve.

Set the wrapper containing your 3 compartments to display: flex; and give it a height of 100% or 100vh. The height of the wrapper will fill the entire height, and the display: flex; will cause all children of this wrapper which has the appropriate flex-properties (for example flex:1;) to be controlled with the flexbox-magic.

Example markup:

<div class="wrapper">
    <header>I'm a 30px tall header</header>
    <main>I'm the main-content filling the void!</main>
    <footer>I'm a 30px tall footer</footer>
</div>

And CSS to accompany it:

.wrapper {
    height: 100vh;
    display: flex;

    /* Direction of the items, can be row or column */
    flex-direction: column;
}

header,
footer {
    height: 30px;
}

main {
    flex: 1;
}

Here's that code live on Codepen: http://codepen.io/enjikaka/pen/zxdYjX/left

You can see more flexbox-magic here: http://philipwalton.github.io/solved-by-flexbox/

Or find a well made documentation here: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

--[Old answer below]--

Here you go: http://jsfiddle.net/pKvxN/

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Layout</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  header {
    height: 30px;
    background: green;
  }
  footer {
    height: 30px;
    background: red;
  }
</style>
</head>
<body>
  <header>
    <h1>I am a header</h1>
  </header>
  <article>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor.
    </p>
  </article>
  <footer>
    <h4>I am a footer</h4>
  </footer>
</body>
</html>

That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)

.NET console application as Windows service

I hear your point at wanting one assembly to stop repeated code but, It would be simplest and reduce code repetition and make it easier to reuse your code in other ways in future if...... you to break it into 3 assemblies.

  1. One library assembly that does all the work. Then have two very very slim/simple projects:
  2. one which is the commandline
  3. one which is the windows service.

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Splitting String and put it on int array

You are doing Integer division, so you will lose the correct length if the user happens to put in an odd number of inputs - that is one problem I noticed. Because of this, when I run the code with an input of '1,2,3,4,5,6,7' my last value is ignored...

C++11 reverse range-based for-loop

Actually Boost does have such adaptor: boost::adaptors::reverse.

#include <list>
#include <iostream>
#include <boost/range/adaptor/reversed.hpp>

int main()
{
    std::list<int> x { 2, 3, 5, 7, 11, 13, 17, 19 };
    for (auto i : boost::adaptors::reverse(x))
        std::cout << i << '\n';
    for (auto i : x)
        std::cout << i << '\n';
}

Disable activity slide-in animation when launching new activity?

Just specify Intent.FLAG_ACTIVITY_NO_ANIMATION flag when starting

Difference between Java SE/EE/ME?

The SE(JDK) has all the libraries you will ever need to cut your teeth on Java. I recommend the Netbeans IDE as this comes bundled with the SE(JDK) straight from Oracle. Don't forget to set "path" and "classpath" variables especially if you are going to try command line. With a 64 bit system insert the "System Path" e.g. C:\Program Files (x86)\Java\jdk1.7.0 variable before the C:\Windows\system32; to direct the system to your JDK.

hope this helps.

I get exception when using Thread.sleep(x) or wait()

Have a look at this excellent brief post on how to do this properly.

Essentially: catch the InterruptedException. Remember that you must add this catch-block. The post explains this a bit further.

__init__ and arguments in Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

regex pattern to match the end of a string

Use following pattern:

/([^/]+)$

How to convert date format to milliseconds?

date.setTime(milliseconds);

this is for set milliseconds in date

long milli = date.getTime();

This is for get time in milliseconds.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

POI setting Cell Background to a Custom Color

You can set custom color using this-

check out this - click hear

XSSFWorkbook workbook = new XSSFWorkbook();

IndexedColorMap colorMap = workbook.getStylesSource().getIndexedColors();
Font tableHeadOneFontStyle = workbook.createFont();
        tableHeadOneFontStyle.setBold( true );
        tableHeadOneFontStyle.setColor( IndexedColors.BLACK.getIndex() );

XSSFCellStyle tableHeaderOneColOneStyle = workbook.createCellStyle();
        tableHeaderOneColOneStyle.setFont( tableHeadOneFontStyle );
        tableHeaderOneColOneStyle
                .setFillForegroundColor( new XSSFColor( new java.awt.Color( 255, 231, 153 ), colorMap ) );
        tableHeaderOneColOneStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND );
        tableHeaderOneColOneStyle = setLeftRightBorderColor( tableHeaderOneColOneStyle );
        tableHeaderOneColOneStyle = alignCenter( tableHeaderOneColOneStyle );

What is the difference between localStorage, sessionStorage, session and cookies?

These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

Local Storage does the same thing, but persists even when the browser is closed and reopened.

You can set and retrieve stored data as follows:

sessionStorage.setItem('key', 'value');

var data = sessionStorage.getItem('key');

Similarly for localStorage.

What is the opposite of :hover (on mouse leave)?

Just use CSS transitions instead of animations.

A {
    color: #999;
    transition: color 1s ease-in-out;
}

A:hover {
    color: #000;
}

Live demo

How to suppress "unused parameter" warnings in C?

I got the same problem. I used a third-part library. When I compile this library, the compiler (gcc/clang) will complain about unused variables.

Like this

test.cpp:29:11: warning: variable 'magic' set but not used [-Wunused-but-set-variable] short magic[] = {

test.cpp:84:17: warning: unused variable 'before_write' [-Wunused-variable] int64_t before_write = Thread::currentTimeMillis();

So the solution is pretty clear. Adding -Wno-unused as gcc/clang CFLAG will suppress all "unused" warnings, even thought you have -Wall set.

In this way, you DO NOT NEED to change any code.

Vertical Alignment of text in a table cell

valign="top" should do the work.

_x000D_
_x000D_
<tr>_x000D_
  <td valign="top">Description</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

Running Tensorflow in Jupyter Notebook

You will need to add a "kernel" for it. Run your enviroment:

>activate tensorflow

Then add a kernel by command (after --name should follow your env. with tensorflow):

>python -m ipykernel install --user --name tensorflow --display-name "TensorFlow-GPU"

After that run jupyter notebook from your tensorflow env.

>jupyter notebook

And then you will see the following enter image description here

Click on it and then in the notebook import packages. It will work out for sure.

matplotlib savefig() plots different from show()

Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.

If you create a figure from scratch you can give it a size option while creation:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3, 6))

plt.plot(range(10)) #plot example
plt.show() #for control

fig.savefig('temp.png', dpi=fig.dpi)

figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.

As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().

Alternatively the figure size can be changed after creation with:

fig.set_size_inches(3, 6, forward=True)

forward allows to change the size on the fly.

If you have trouble with too large borders in the created image you can adjust those either with:

plt.tight_layout()
#or:
plt.tight_layout(pad=2)

or:

fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)

The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

Init function in javascript and how it works

In simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.

i.e.

(function(a,b){
//Do your code here
})(1,2);

It same like as

var test = function(x,y) {
  // Do your code here
}
test(1,2);

Difference between static class and singleton pattern?

We have our DB framework that makes connections to Back end.To Avoid Dirty reads across Multiple users we have used singleton pattern to ensure we have single instance available at any point of time.

In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for a business contracts or IoC purposes, this is where I use the Singleton pattern without a static class

Singleton provides a way to maintain state in stateless scenarios

Hope that helps you..

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

Failure during conversion to COFF: file invalid or corrupt

I am using Visual Studio 2010.

This happened to me when I installed .NET 4.5. Uninstall of .NET 4.5 and install of .NET 4.0 helped me and error messages disappeared.

jquery - return value using ajax result on success

Although all the approaches regarding the use of async: false are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

1st: Return whole ajax response in a function and then make use of done function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;
        }
    });
 }

CALL THE ABOVE LIKE SO:

getAjax(youUrl, yourData).done(function(response){
    console.log(response);
});

FOR MULTIPLE AJAX CALLS MAKE USE OF $.when :

$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
    console.log(response);
});

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

        $.ajax({
            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);
            }
        });

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE: In the exmple above jquery cookies library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

String split on new line, tab and some number of spaces

If you look at the documentation for str.split:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

In other words, if you're trying to figure out what to pass to split to get '\n\tName: Jane Smith' to ['Name:', 'Jane', 'Smith'], just pass nothing (or None).

This almost solves your whole problem. There are two parts left.

First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:

s.split(None, 1)

Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:

key, value = s.split(None, 1)
key = key[:-1]

There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.

Onchange open URL via select - jQuery

You can use this simple code snippet using jQuery to redirect from a drop down menu.

<select id="dynamic-select">
    <option value="" selected>Pick a Website</option>
    <option value="http://www.google.com/">Google</option>
    <option value="http://www.youtube.com/">YouTube</option>
    <option value="http://www.stackoverflow.com/">Stack Overflow</option>
</select>

<script>
    $('#dynamic-select').bind('change', function () { // bind change event to select
        var url = $(this).val(); // get selected value
        if (url != '') { // require a URL
            window.location = url; // redirect
        }
        return false;
    });
</script>

Android intent for playing video?

following code works just fine for me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

How can I close a dropdown on click outside?

You can use mouseleave in your view like this

Test with angular 8 and work perfectly

<ul (mouseleave)="closeDropdown()"> </ul>

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

How to fix Error: laravel.log could not be opened?

Delete "/var/www/laravel/app/storage/logs/laravel.log" and try again:

rm storage/logs/laravel.log

document.getElementById('btnid').disabled is not working in firefox and chrome

I've tried all the possibilities. Nothing worked for me except the following. var element = document.querySelectorAll("input[id=btn1]"); element[0].setAttribute("disabled",true);

How to upgrade rubygems

Install rubygems-update

gem install rubygems-update
update_rubygems
gem update --system

run this commands as root or use sudo.

Twitter Bootstrap scrollable table rows and fixed header

<table class="table table-striped table-condensed table-hover rsk-tbl vScrollTHead">
            <thead>
            <tr>
                <th>Risk Element</th>
                <th>Description</th>
                <th>Risk Value</th>
                <th>&nbsp;</th>
            </tr>
            </thead>
        </table>
<div class="vScrollTable">
            <table class="table table-striped table-condensed table-hover rsk-tbl vScrollTBody">
                <tbody>
                <tr class="">
                    <td>JEWELLERY</td>
                    <td>Jewellery business</td>

                </tr><tr class="">
                    <td>NGO</td>
                    <td>none-governmental organizations</td>
                    </tr>
                </tbody>
            </table>
        </div>





.vScrollTBody{
  height:15px;
}

.vScrollTHead {
  height:15px;
}

.vScrollTable{
  height:100px;
  overflow-y:scroll;
}

having two tables for head and body worked for me

Reading *.wav files in Python

Per the documentation, scipy.io.wavfile.read(somefile) returns a tuple of two items: the first is the sampling rate in samples per second, the second is a numpy array with all the data read from the file:

from scipy.io import wavfile
samplerate, data = wavfile.read('./output/audio.wav')

How to make a whole 'div' clickable in html and css without JavaScript?

It is possible to make a link fill the entire div which gives the appearance of making the div clickable.

CSS:

#my-div {
    background-color: #f00;
    width: 200px;
    height: 200px;
}
a.fill-div {
    display: block;
    height: 100%;
    width: 100%;
    text-decoration: none;
}

HTML:

<div id="my-div">
    <a href="#" class="fill-div"></a>
</div>

Using C++ base class constructors?

You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:

class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

How to Resize a Bitmap in Android?

profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How do you serialize a model instance in Django?

There is a good answer for this and I'm surprised it hasn't been mentioned. With a few lines you can handle dates, models, and everything else.

Make a custom encoder that can handle models:

from django.forms import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model

class ExtendedEncoder(DjangoJSONEncoder):

    def default(self, o):

        if isinstance(o, Model):
            return model_to_dict(o)

        return super().default(o)

Now use it when you use json.dumps

json.dumps(data, cls=ExtendedEncoder)

Now models, dates and everything can be serialized and it doesn't have to be in an array or serialized and unserialized. Anything you have that is custom can just be added to the default method.

You can even use Django's native JsonResponse this way:

from django.http import JsonResponse

JsonResponse(data, encoder=ExtendedEncoder)

how to break the _.each function in underscore.js

You can have a look to _.some instead of _.each. _.some stops traversing the list once a predicate is true. Result(s) can be stored in an external variable.

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

See http://underscorejs.org/#some

What are the differences between JSON and JSONP?

Basically, you're not allowed to request JSON data from another domain via AJAX due to same-origin policy. AJAX allows you to fetch data after a page has already loaded, and then execute some code/call a function once it returns. We can't use AJAX but we are allowed to inject <script> tags into our own page and those are allowed to reference scripts hosted at other domains.

Usually you would use this to include libraries from a CDN such as jQuery. However, we can abuse this and use it to fetch data instead! JSON is already valid JavaScript (for the most part), but we can't just return JSON in our script file, because we have no way of knowing when the script/data has finished loading and we have no way of accessing it unless it's assigned to a variable or passed to a function. So what we do instead is tell the web service to call a function on our behalf when it's ready.

For example, we might request some data from a stock exchange API, and along with our usual API parameters, we give it a callback, like ?callback=callThisWhenReady. The web service then wraps the data with our function and returns it like this: callThisWhenReady({...data...}). Now as soon as the script loads, your browser will try to execute it (as normal), which in turns calls our arbitrary function and feeds us the data we wanted.

It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.

jQuery actually supports this seamlessly for you by creating a uniquely named function for you and passing that off, which will then in turn run the code you wanted.

setTimeout or setInterval?

The setInterval makes it easier to cancel future execution of your code. If you use setTimeout, you must keep track of the timer id in case you wish to cancel it later on.

var timerId = null;
function myTimeoutFunction()
{
    doStuff();
    timerId = setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

// later on...
clearTimeout(timerId);

versus

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);

// later on...
clearInterval(timerId);

In Jinja2, how do you test if a variable is undefined?

From the Jinja2 template designer documentation:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}

How to create a String with carriage returns?

The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")

Casting interfaces for deserialization in JSON.NET

Two things you might try:

Implement a try/parse model:

public class Organisation {
  public string Name { get; set; }

  [JsonConverter(typeof(RichDudeConverter))]
  public IPerson Owner { get; set; }
}

public interface IPerson {
  string Name { get; set; }
}

public class Tycoon : IPerson {
  public string Name { get; set; }
}

public class Magnate : IPerson {
  public string Name { get; set; }
  public string IndustryName { get; set; }
}

public class Heir: IPerson {
  public string Name { get; set; }
  public IPerson Benefactor { get; set; }
}

public class RichDudeConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return (objectType == typeof(IPerson));
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    // pseudo-code
    object richDude = serializer.Deserialize<Heir>(reader);

    if (richDude == null)
    {
        richDude = serializer.Deserialize<Magnate>(reader);
    }

    if (richDude == null)
    {
        richDude = serializer.Deserialize<Tycoon>(reader);
    }

    return richDude;
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    // Left as an exercise to the reader :)
    throw new NotImplementedException();
  }
}

Or, if you can do so in your object model, implement a concrete base class between IPerson and your leaf objects, and deserialize to it.

The first can potentially fail at runtime, the second requires changes to your object model and homogenizes the output to the lowest common denominator.

When to use LinkedList over ArrayList in Java?

My rule of thumb is if I need a Collection (i.e. doesn't need to be a List) then use ArrayList if you know the size in advance, or can know the size confidently, or know that it won't vary much. If you need random access (i.e. you use get(index)) then avoid LinkedList. Basically, use LinkedList only if you don't need index access and don't know the (approximate) size of the collection you're allocating. Also if you're going to be making lots of additions and removals (again through the Collection interface) then LinkedList may be preferable.

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

How to remove folders with a certain name

Combining multiple answers, here's a command that works on both Linux and MacOS

rm -rf $(find . -type d -name __pycache__)

Vertically center text in a 100% height div?

This answer is no longer the best answer ... see the flexbox answer below instead!


To get it perfectly centered (as mentioned in david's answer) you need to add a negative top margin. If you know (or force) there to only be a single line of text, you can use:

margin-top: -0.5em;

for example:

http://jsfiddle.net/45MHk/623/

//CSS:
html, body, div {
    height: 100%;
}

#parent
{
    position:relative;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
    /* adjust top up half the height of a single line */
    margin-top: -0.5em;
    /* force content to always be a single line */
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
    text-overflow: ellipsis;
}

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

The originally accepted answer will not vertically center on the middle of the text (it centers based on the top of the text). So, if you parent is not very tall, it will not look centered at all, for example:

http://jsfiddle.net/45MHk/

//CSS:
#parent
{
    position:relative;
    height: 3em;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
}? 

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>?

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Explode string by one or more spaces or tabs

I think you want preg_split:

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Android: How to rotate a bitmap on a center point

matrix.reset();
matrix.setTranslate( anchor.x, anchor.y );
matrix.postRotate((float) rotation , 0,0);
matrix.postTranslate(positionOfAnchor.x, positionOfAnchor.x);
c.drawBitmap(bitmap, matrix, null); 

How to style CSS role

Sure you can do in this mode:

 #content[role="main"]{
       //style
    }

http://www.w3.org/TR/selectors/#attribute-selectors

How can I give an imageview click effect like a button on Android?

If you want ripple when tapped, it can be given by this code :

<ImageView
    ...
    android:background="?attr/selectableItemBackgroundBorderless"
    android:clickable="true"
    ...
</ImageView>

Similarly, you can implement click effect for TextView

<TextView
    ...
    android:background="?attr/selectableItemBackgroundBorderless"
    android:clickable="true"
    ...
</TextView>

Convert list to dictionary using linq and not worrying about duplicates

In case we want all the Person (instead of only one Person) in the returning dictionary, we could:

var _people = personList
.GroupBy(p => p.FirstandLastName)
.ToDictionary(g => g.Key, g => g.Select(x=>x));

android: changing option menu items programmatically

If I have to change the contents of my options menu I perform it during the onMenuOpened(). This allows me to check the running state at the very moment that the user is accessing the menu.

public boolean onMenuOpened(int featureid, Menu menu)
    {
        menu.clear();
        if (!editable)
        {
            MenuItem itemAdd = menu.add(0, REASSIGN, Menu.NONE, context.getString(R.string.reassign));
            MenuItem itemMod = menu.add(1, EDIT, Menu.NONE, context.getString(R.string.modify));
            MenuItem itemDel = menu.add(2, DELETE, Menu.NONE, context.getString(R.string.delete));
            itemAdd.setShortcut('0', 'a');
            itemMod.setShortcut('1', 'm');
            itemDel.setShortcut('2', 'd');
        }
        else
        {
            MenuItem itemSave = menu.add(3, SAVE, Menu.NONE, context.getString(R.string.savechanges));
            itemSave.setShortcut('0', 'S');
        }


        return true;
    }

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

How to reduce the space between <p> tags?

A more real-world example:

p { margin: 10px 0;}

How to convert hashmap to JSON object in Java

You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.

Example:

GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);

You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.

However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).

More information about Gson here.

Remember that the object must implement the Serializable interface.

Installing a plain plugin jar in Eclipse 3.5

in Eclipse 4.4.1

  1. copy jar in "C:\eclipse\plugins"
  2. edit file "C:\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info"
  3. add jar info. example: com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
  4. restart Eclipse.

What's the best way to send a signal to all members of a process group?

brad's answer is what I'd recommend too, except that you can do away with awk altogether if you use the --ppid option to ps.

for child in $(ps -o pid -ax --ppid $PPID) do ....... done

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

How can I see what has changed in a file before committing to git?

git diff

Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

How to access Anaconda command prompt in Windows 10 (64-bit)

I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.

What are the Ruby File.open modes and options?

opt is new for ruby 1.9. The various options are documented in IO.new : www.ruby-doc.org/core/IO.html

"Repository does not have a release file" error

You need to update your repository targets to the Eoan Ermine (19.10) release of Ubuntu. This can be done like so:

sudo sed -i -e 's|disco|eoan|g' /etc/apt/sources.list
sudo apt update

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

How do I create batch file to rename large number of files in a folder?

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=Vacation2010
SET new=December
for /f "tokens=*" %%f in ('dir /b *.jpg') do (
  SET newname=%%f
  SET newname=!newname:%old%=%new%!
  move "%%f" "!newname!"
)

What this does is it loops over all .jpg files in the folder where the batch file is located and replaces the Vacation2010 with December inside the filenames.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

Ctrl+click doesn't work in Eclipse Juno

This bug is really annoying..

The only thing that did the trick for me is deleting the project from the workspace, then deleting the .project and .classpath files and then re import it back to the workspace.

Hope it will help others.

How do I retrieve my MySQL username and password?

Do it without down time

Run following command in the Terminal to connect to the DBMS (you need root access):

sudo mysql -u root -p;

run update password of the target user (for my example username is mousavi and it's password must be 123456):

UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi';  

at this point you need to do a flush to apply changes:

FLUSH PRIVILEGES;

Done! You did it without any stop or restart mysql service.

Permutations between two lists of unequal length

Without itertools as a flattened list:

[(list1[i], list2[j]) for i in range(len(list1)) for j in range(len(list2))]

or in Python 2:

[(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))]

Convert String to java.util.Date

java.time

While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");

        String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
        System.out.println("output here: " + dateTime);

Output is:

output here: 2010-04-29T13:00:14

What went wrong in your code?

The combination of uppercase HH and aaa in your format pattern strings does not make much sense since HH is for hour of day, rendering the AM/PM marker from aaa superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat or the modern DateTimeFormatter:

'aaa' should not be used, if you use 'aaa' then specify 'hh'

Lowercase hh is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.

Other tips

  • In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
  • Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
  • If you wanted to use the outdated DateFormat, its parse method returns a Date, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

How to calculate a mod b in Python?

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);
    d.findElement(By.className('fc-time')).then(function(result){
        s.mouseMove(result,l).click().perform();
    });

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

mysql update query with sub query

You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as; eav_attributes

Then you can use those to set whichever role to any other role for all products like so;

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

The above will set all your 'base' roles to the 'small' image of the same product.

How to update record using Entity Framework Core?

To update an entity with Entity Framework Core, this is the logical process:

  1. Create instance for DbContext class
  2. Retrieve entity by key
  3. Make changes on entity's properties
  4. Save changes

Update() method in DbContext:

Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.

Update method doesn't save changes in database; instead, it sets states for entries in DbContext instance.

So, We can invoke Update() method before to save changes in database.

I'll assume some object definitions to answer your question:

  1. Database name is Store

  2. Table name is Product

Product class definition:

public class Product
{
    public int? ProductID { get; set; }
    
    public string ProductName { get; set; }
    
    public string Description { get; set; }
    
    public decimal? UnitPrice { get; set; }
}

DbContext class definition:

public class StoreDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Your Connection String");

        base.OnConfiguring(optionsBuilder);
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>(entity =>
        {
            // Set key for entity
            entity.HasKey(p => p.ProductID);
        });
        
        base.OnModelCreating(modelBuilder);
    }
}

Logic to update entity:

using (var context = new StoreDbContext())
{
        // Retrieve entity by id
        // Answer for question #1
        var entity = context.Products.FirstOrDefault(item => item.ProductID == id);
        
        // Validate entity is not null
        if (entity != null)
        {
            // Answer for question #2

            // Make changes on entity
            entity.UnitPrice = 49.99m;
            entity.Description = "Collector's edition";
            
            /* If the entry is being tracked, then invoking update API is not needed. 
              The API only needs to be invoked if the entry was not tracked. 
              https://www.learnentityframeworkcore.com/dbcontext/modifying-data */
            // context.Products.Update(entity);
            
            // Save changes in database
            context.SaveChanges();
        }
}

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Your error is quite literally saying "you're trying to use Windows Authentication, but your login isn't from a trusted domain". Which is odd, because you're connecting to the local machine.

Perhaps you're logged into Windows using a local account rather than a domain account? Ensure that you're logging in with a domain account that is also a SQL Server principal on your SQL2008 instance.

Check whether IIS is installed or not?

go to Start->Run type inetmgr and press OK. If you get an IIS configuration screen. It is installed, otherwise it isn't.

You can also check ControlPanel->Add Remove Programs, Click Add Remove Windows Components and look for IIS in the list of installed components.

EDIT


To Reinstall IIS.

Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Uncheck IIS box

Click next and follow prompts to UnInstall IIS. Insert your windows disc into the appropriate drive.

Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Check IIS box

Click next and follow prompts to Install IIS.

C: scanf to array

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

This would require a sort (O(n log n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:

var maxObject = list.OrderByDescending(item => item.Height).First();

Note that this has the advantage of enumerating the list sequence just once. While it might not matter if list is a List<T> that doesn't change in the meantime, it could matter for arbitrary IEnumerable<T> objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own MaxObject extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):

static class EnumerableExtensions {
    public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector)
      where U : IComparable<U> {
       if (source == null) throw new ArgumentNullException("source");
       bool first = true;
       T maxObj = default(T);
       U maxKey = default(U);
       foreach (var item in source) {
           if (first) {
                maxObj = item;
                maxKey = selector(maxObj);
                first = false;
           } else {
                U currentKey = selector(item);
                if (currentKey.CompareTo(maxKey) > 0) {
                    maxKey = currentKey;
                    maxObj = item;
                }
           }
       }
       if (first) throw new InvalidOperationException("Sequence is empty.");
       return maxObj;
    }
}

and use it with:

var maxObject = list.MaxObject(item => item.Height);

WCF error - There was no endpoint listening at

I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.

Show Console in Windows Application?

Actually AllocConsole with SetStdHandle in a GUI application might be a safer approach. The problem with the "console hijacking" already mentioned, is that the console might not be a foreground window at all, (esp. considering the influx of new window managers in Vista/Windows 7) among other things.

How to iterate over rows in a DataFrame in Pandas

There is a way to iterate throw rows while getting a DataFrame in return, and not a Series. I don't see anyone mentioning that you can pass index as a list for the row to be returned as a DataFrame:

for i in range(len(df)):
    row = df.iloc[[i]]

Note the usage of double brackets. This returns a DataFrame with a single row.

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

Accessing SQL Database in Excel-VBA

@firedrawndagger: to list field names/column headers iterate through the recordset Fields collection and insert the name:

Dim myRS as ADODB.Recordset
Dim fld as Field
Dim strFieldName as String 

For Each fld in myRS.Fields
    Activesheet.Selection = fld.Name
    [Some code that moves to next column]
Next

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

What exactly does the .join() method do?

join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring() + strid

Use of Java's Collections.singletonList()?

To answer your immutable question:

Collections.singletonList will create an immutable List. An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you try to alter the contents.

A singleton List contains only that item and cannot be altered.

Verify ImageMagick installation

You can easily check for the Imagick class in PHP.

if( class_exists("Imagick") )
{
    //Imagick is installed
}

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

jQuery UI Tabs - How to Get Currently Selected Tab Index

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.

Responsive Bootstrap Jumbotron Background Image

The below code works for all the screens :

.jumbotron {
   background: url('backgroundimage.jpg') no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   background-size: cover;
   -o-background-size: cover;
}

The cover property will resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.

Adding to the classpath on OSX

If your shell is tcsh or csh, you can set it in /etc/profile. Open terminal, "vim /etc/profile" and add the following line:

setenv CLASSPATH (insert your classpath here)

How do I create a SQL table under a different schema?

Try running CREATE TABLE [schemaname].[tableName]; GO;

This assumes the schemaname exists in your database. Please use CREATE SCHEMA [schemaname] if you need to create a schema as well.

EDIT: updated to note SQL Server 11.03 requiring this be the only statement in the batch.

How do I run a node.js app as a background service?

I use tmux for a multiple window/pane development environment on remote hosts. It's really simple to detach and keep the process running in the background. Have a look at tmux

Creating a segue programmatically

I thought I would add another possibility. One of the things you can do is you can connect two scenes in a storyboard using a segue that is not attached to an action, and then programmatically trigger the segue inside your view controller. The way you do this, is that you have to drag from the file's owner icon at the bottom of the storyboard scene that is the segueing scene, and right drag to the destination scene. I'll throw in an image to help explain.

enter image description here

A popup will show for "Manual Segue". I picked Push as the type. Tap on the little square and make sure you're in the attributes inspector. Give it an identifier which you will use to refer to it in code.

enter image description here

Ok, next I'm going to segue using a programmatic bar button item. In viewDidLoad or somewhere else I'll create a button item on the navigation bar with this code:

UIBarButtonItem *buttonizeButton = [[UIBarButtonItem alloc] initWithTitle:@"Buttonize"
                                                                    style:UIBarButtonItemStyleDone
                                                                   target:self
                                                                   action:@selector(buttonizeButtonTap:)];
self.navigationItem.rightBarButtonItems = @[buttonizeButton];

Ok, notice that the selector is buttonizeButtonTap:. So write a void method for that button and within that method you will call the segue like this:

-(void)buttonizeButtonTap:(id)sender{
    [self performSegueWithIdentifier:@"Associate" sender:sender];
    }

The sender parameter is required to identify the button when prepareForSegue is called. prepareForSegue is the framework method where you will instantiate your scene and pass it whatever values it will need to do its work. Here's what my method looks like:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"Associate"])
    {
        TranslationQuizAssociateVC *translationQuizAssociateVC = [segue destinationViewController];
        translationQuizAssociateVC.nodeID = self.nodeID; //--pass nodeID from ViewNodeViewController
        translationQuizAssociateVC.contentID = self.contentID;
        translationQuizAssociateVC.index = self.index;
        translationQuizAssociateVC.content = self.content;
    }
}

Ok, just tested it and it works. Hope it helps you.

What is Persistence Context?

In layman terms we can say that Persistence Context is an environment where entities are managed, i.e it syncs "Entity" with the database.

How to get the azure account tenant Id?

My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.

So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!

How to find my Microsoft 365, Azure or SharePoint Online tenant ID?

Raising a number to a power in Java

You should use below method-

Math.pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

"Register" an .exe so you can run it from any command line in Windows

Let's say my exe is C:\Program Files\AzCopy\azcopy.exe

Command/CMD/Batch

SET "PATH=C:\Program Files\AzCopy;%PATH%"

PowerShell

$env:path = $env:path + ";C:\Program Files\AzCopy"

I can now simply type and use azcopy from any location from any shell inc command prompt, powershell, git bash etc

How to use Console.WriteLine in ASP.NET (C#) during debug?

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

HTML Code for text checkbox '?'

As this has already been properly answered, I'd just add the following site as a reference:

Unicode Table

You can search for "check", for example.

Find the greatest number in a list of numbers

You can use the inbuilt function max() with multiple arguments:

print max(1, 2, 3)

or a list:

list = [1, 2, 3]
print max(list)

or in fact anything iterable.