Programs & Examples On #Egovernment

A fast way to delete all rows of a datatable at once

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

first I had to delete my registry by using npm config delete registry and register new value using npm config set registry "http://registry.npmjs.org"

configure: error: C compiler cannot create executables

First get the gcc path using

Command: which gcc

Output: /usr/bin/gcc

I had the same issue, Please set the gcc path in below command and install

CC=/usr/bin/gcc rvm install 1.9.3

Later if you get "Ruby was built without documentation" run below command

rvm docs generate-ri

DD/MM/YYYY Date format in Moment.js

This worked for me

var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP

moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

How do I ignore files in a directory in Git?

A leading slash indicates that the ignore entry is only to be valid with respect to the directory in which the .gitignore file resides. Specifying *.o would ignore all .o files in this directory and all subdirs, while /*.o would just ignore them in that dir, while again, /foo/*.o would only ignore them in /foo/*.o.

.htaccess rewrite subdomain to directory

write .htaccess

RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

Detect backspace and del on "input" event?

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

RESTful URL design for search

Although having the parameters in the path has some advantages, there are, IMO, some outweighing factors.

  • Not all characters needed for a search query are permitted in a URL. Most punctuation and Unicode characters would need to be URL encoded as a query string parameter. I'm wrestling with the same problem. I would like to use XPath in the URL, but not all XPath syntax is compatible with a URI path. So for simple paths, /cars/doors/driver/lock/combination would be appropriate to locate the 'combination' element in the driver's door XML document. But /car/doors[id='driver' and lock/combination='1234'] is not so friendly.

  • There is a difference between filtering a resource based on one of its attributes and specifying a resource.

    For example, since

    /cars/colors returns a list of all colors for all cars (the resource returned is a collection of color objects)

    /cars/colors/red,blue,green would return a list of color objects that are red, blue or green, not a collection of cars.

    To return cars, the path would be

    /cars?color=red,blue,green or /cars/search?color=red,blue,green

  • Parameters in the path are more difficult to read because name/value pairs are not isolated from the rest of the path, which is not name/value pairs.

One last comment. I prefer /garages/yyy/cars (always plural) to /garage/yyy/cars (perhaps it was a typo in the original answer) because it avoids changing the path between singular and plural. For words with an added 's', the change is not so bad, but changing /person/yyy/friends to /people/yyy seems cumbersome.

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

CSS strikethrough different color from text?

I've used an empty :after element and decorated one border on it. You can even use CSS transforms to rotate it for a slanted line. Result: pure CSS, no extra HTML elements! Downside: doesn't wrap across multiple lines, although IMO you shouldn't use strikethrough on large blocks of text anyway.

_x000D_
_x000D_
s,_x000D_
strike {_x000D_
  text-decoration: none;_x000D_
  /*we're replacing the default line-through*/_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  /* keeps it from wrapping across multiple lines */_x000D_
}_x000D_
_x000D_
s:after,_x000D_
strike:after {_x000D_
  content: "";_x000D_
  /* required property */_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  border-top: 2px solid red;_x000D_
  height: 45%;_x000D_
  /* adjust as necessary, depending on line thickness */_x000D_
  /* or use calc() if you don't need to support IE8: */_x000D_
  height: calc(50% - 1px);_x000D_
  /* 1px = half the line thickness */_x000D_
  width: 100%;_x000D_
  transform: rotateZ(-4deg);_x000D_
}
_x000D_
<p>Here comes some <strike>strike-through</strike> text!</p>
_x000D_
_x000D_
_x000D_

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

How can I start PostgreSQL server on Mac OS X?

Homebrew is the way!!

To start the service:

brew services start postgresql

To list it:

brew services list | grep postgres

To stop the service:

brew services stop postgresql

Enterprise app deployment doesn't work on iOS 7.1

Open up terminal and run the command: curl -i https:// (.ipa file path not plist)

This will tell you whether or not the installer can see the IPA file. If you run the curl command with the '-i' you'll see the full response and it's probably not the IPA file. This is the response the installer sees, so if it's not returning HTTP 200 and an IPA you'll need to return it on your end.

The ITMS installer doesn't save any context from Safari. If you authenticated into a secure portal in Safari, the authentication cookies aren't pass to the the installer. i.e. The installer needs to be able to see the app without authentication and this could be the reason you are getting 'Cannot connect to server'.

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

Best cross-browser method to capture CTRL+S with JQuery?

@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.

Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.

Linux / Bash, using ps -o to get process by specific name?

Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do

pgrep -x PROCESS_NAME

-x          Require an exact match of the process name, or argument list if -f is given.
             The default is to match any substring.

This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.

https connection using CURL from command line

you could use this

curl_setopt($curl->curl, CURLOPT_SSL_VERIFYPEER, false);

Order by descending date - month, day and year

I'm guessing EventDate is a char or varchar and not a date otherwise your order by clause would be fine.

You can use CONVERT to change the values to a date and sort by that

SELECT * 
FROM 
     vw_view 
ORDER BY 
   CONVERT(DateTime, EventDate,101)  DESC

The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.

This means you should either exclude the bad rows or let the bad rows go to the bottom of the results

To exclude the bad rows just add WHERE IsDate(EventDate) = 1

To let let the bad dates go to the bottom you need to use CASE

e.g.

ORDER BY 
    CASE
       WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
       ELSE null
    END DESC

When use ResponseEntity<T> and @RestController for Spring RESTful applications

A proper REST API should have below components in response

  1. Status Code
  2. Response Body
  3. Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location)

The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.

So if you want to provide the location of resource then using ResponseEntity would be better else it can be avoided.

Consider an example where a API is modified to provide all the options mentioned

// Step 1 - Without any options provided
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public @ResponseBody Spittle spittleById(@PathVariable long id) {
  return spittleRepository.findOne(id);
}

// Step 2- We need to handle exception scenarios, as step 1 only caters happy path.
@ExceptionHandler(SpittleNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Error spittleNotFound(SpittleNotFoundException e) {
  long spittleId = e.getSpittleId();
  return new Error(4, "Spittle [" + spittleId + "] not found");
}

// Step 3 - Now we will alter the service method, **if you want to provide location**
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
public ResponseEntity<Spittle> saveSpittle(
    @RequestBody Spittle spittle,
    UriComponentsBuilder ucb) {

  Spittle spittle = spittleRepository.save(spittle);
  HttpHeaders headers = new HttpHeaders();
  URI locationUri =
  ucb.path("/spittles/")
      .path(String.valueOf(spittle.getId()))
      .build()
      .toUri();
  headers.setLocation(locationUri);
  ResponseEntity<Spittle> responseEntity =
      new ResponseEntity<Spittle>(
          spittle, headers, HttpStatus.CREATED)
  return responseEntity;
}

// Step4 - If you are not interested to provide the url location, you can omit ResponseEntity and go with
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Spittle saveSpittle(@RequestBody Spittle spittle) {
  return spittleRepository.save(spittle);
}

How to Create a real one-to-one relationship in SQL Server

Set the foreign key as a primary key, and then set the relationship on both primary key fields. That's it! You should see a key sign on both ends of the relationship line. This represents a one to one.

enter image description here

Check this : SQL Server Database Design with a One To One Relationship

Read from file in eclipse

Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.

Removing all unused references from a project in Visual Studio projects

In VB2008, it works this way:

Project>Add References

Then click on the Recent tab where you can see list of references used recently. Locate the one you do not want and delet it. Then you close without adding anything.

Error: No module named psycopg2.extensions

It seems that you need gcc-4.0, and it would be helpful to specify your OS type and version.

Maybe this question will help you a bit: Installing GCC to Mac OS X Leopard without installing Xcode

Update

I'm a Windows user, so I can't test your setup, but a quick google pointed to some more links:

Timing Delays in VBA

Have you tried to use Sleep?

There's an example HERE (copied below):

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub Form_Activate()    

frmSplash.Show
DoEvents
Sleep 1000
Unload Me
frmProfiles.Show

End Sub

Notice it might freeze the application for the chosen amount of time.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

Create a global variable in TypeScript

I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

If someone posts an pure TypeScript solution, I will accept that.

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

Restart container within pod

We use a pretty convenient command line to force re-deployment of fresh images on integration pod.
We noticed that our alpine containers all run their "sustaining" command on PID 5. Therefore, sending it a SIGTERM signal takes the container down. imagePullPolicy being set to Always has the kubelet re-pull the latest image when it brings the container back.

kubectl exec -i [pod name] -c [container-name] -- kill -15 5

How do I check which version of NumPy I'm using?

You can get numpy version using Terminal or a Python code.

In a Terminal (bash) using Ubuntu:

pip list | grep numpy

In python 3.6.7, this code shows the numpy version:

import numpy
print (numpy.version.version)

If you insert this code in the file shownumpy.py, you can compile it:

python shownumpy.py

or

python3 shownumpy.py

I've got this output:

1.16.1

jQuery Dialog Box

<script type="text/javascript">
// Increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 1000;
$(function() {
    $('#dialog1').dialog({
        autoOpen: false,
        show: 'blind',
        hide: 'explode'
    });

    $('#Wizard1_txtEmailID').click(function() {
        $('#dialog1').dialog('open');
        return false;
    });
    $('#Wizard1_txtEmailID').click(function() {
        $('#dialog2').dialog('close');
        return false;
    });
    //mouseover
    $('#Wizard1_txtPassword').click(function() {
        $('#dialog1').dialog('close');
        return false;
    });

});



/////////////////////////////////////////////////////
 <div id="dialog1" title="Email ID">
                                                                                                                <p>
                                                                                                                    (Enter your Email ID here.)
                                                                                                                    <br />
                                                                                                                </p>
                                                                                             </div>
 ////////////////////////////////////////////////////////

<div id="dialog2" title="Password">
                                                                                                                <p>
                                                                                                                    (Enter your Passowrd here.)
                                                                                                                    <br />
                                                                                                                </p>
                                                                                              </div>

ReactJS - Get Height of an element

You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.

How to play a sound in C#, .NET

You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.

Automatically set appsettings.json for dev and release environments in asp.net core?

You may use conditional compilation:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
#if SOME_BUILD_FLAG_A
    .AddJsonFile($"appsettings.flag_a.json", optional: true)
#else
    .AddJsonFile($"appsettings.no_flag_a.json", optional: true)
#endif
    .AddEnvironmentVariables();
    this.configuration = builder.Build();
}

How to append output to the end of a text file

Use the >> operator to append text to a file.

Remove Datepicker Function dynamically

Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...

$("#ddlSearchType").change(function () { 
  if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date")                   { 
    $("#txtSearch").addClass("mydate");
    $(".mydate").datepicker()
  } else { 
    $("#txtSearch").removeClass("mydate");
  } 
}); 

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Using an integer as a key in an associative array in JavaScript

As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

You can create your object:

var object = {};

And add the values as array works:

object[1] = value;
object[2] = value;

This will give you:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:

for(key in object)
{
   value = object[key] ;
}

I have tested and works.

Should I use 'has_key()' or 'in' on Python dicts?

has_key is a dictionary method, but in will work on any collection, and even when __contains__ is missing, in will use any other method to iterate the collection to find out.

How do I search an SQL Server database for a string?

For getting a table by name in SQL Server:

SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'

For finding a stored procedure by name:

SELECT name
FROM sys.objects
WHERE name = 'spName'

To get all stored procedures related to a table:

----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Try this....

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p?

Will defiantly work

@Autowired - No qualifying bean of type found for dependency

  • One reason BeanB may not exist in the context
  • Another cause for the exception is the existence of two bean
  • Or definitions in the context bean that isn’t defined is requested by name from the Spring context

see more this url:

http://www.baeldung.com/spring-nosuchbeandefinitionexception

SQL Server dynamic PIVOT query?

Dynamic SQL PIVOT

Different approach for creating columns string

create table #temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    select date, amount, category from #temp
) src
pivot 
(
    max(amount) for category in (' + @cols + ')
) piv'

execute(@query)
drop table #temp

Result

date                    ABC     DEF     GHI
2012-01-01 00:00:00.000 1000.00 NULL    NULL
2012-02-01 00:00:00.000 NULL    500.00  800.00
2012-02-10 00:00:00.000 NULL    700.00  NULL
2012-03-01 00:00:00.000 1100.00 NULL    NULL

How to print a stack trace in Node.js?

you can use node-stack-trace module which is a power full module to track call stacks.

nuget 'packages' element is not declared warning

You will see it only when the file is open. When you'll close the file in Visual Studio the warnings goes away

http://nuget.codeplex.com/discussions/261638

Clean up a fork and restart it from the upstream

How to do it 100% through the Sourcetree GUI

(Not everyone likes doing things through the git command line interface)

Once this has been set up, you only need to do steps 7-13 from then on.

Fetch > checkout master branch > reset to their master > Push changes to server

Steps

  1. In the menu toolbar at the top of the screen: "Repository" > "Repository settings"

"Repository" highlighted in the top menu bar

  1. "Add"

"Add" button at the bottom of the dialog

  1. Go back to GitHub and copy the clone URL.

"Clone or Download" button on the Github website followed by the git url

  1. Paste the url into the "URL / Path" field then give it a name that makes sense. I called it "master". Do not check the "Default remote" checkbox. You will not be able to push directly to this repository.

"Remote name" and "URL / Path" fields highlighted in the"Remote details" dialog

  1. Press "OK" and you should see it appear in your list of repositories now.

"master" repository added to the list of repositories in the "Repository settings" dialog

  1. Press "OK" again and you should see it appear in your list of "Remotes".

"master" repository highlighted in remotes list in side bar

  1. Click the "Fetch" button (top left of the Source tree header area)

"Fetch" button in the header area

  1. Make sure the "Fetch from all remotes" checkbox is checked and press "ok"

"Fetch from all remotes" checkbox highlighted in the "Fetch" dialog

  1. Double click on your "master" branch to check it out if it is not checked out already.

  2. Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.

Example of a commit with a "master/master" tag on it

  1. Right click on the commit > "Reset current branch to this commit".

  2. In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).

"Using mode" field highlighted in the "Reset to commit" dialog. It is set to "discard all working copy changes"

  1. Click the "Push" button (top left of the Source tree header area) to upload the changes to your copy of the repo.

"Push" button in the header area

Your Done!

Why can I not create a wheel in python?

Update your pip first:

pip install --upgrade pip

for Python 3:

pip3 install --upgrade pip

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

How to clear basic authentication details in chrome

Things changed a lot since the answer was posted. Now you will see a small key symbol on the right hand side of the URL bar.
Click the symbol and it will take you directly to the saved password dialog where you can remove the password.

Successfully tested in Chrome 49

How do I merge a git tag onto a branch

Just complementing the answer.

Merging the last tag on a branch:

git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))

Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

mysqld: Can't change dir to data. Server doesn't start

I have met same problem. In my case I had no ..\data dir in my C:\mysql\ so I just executed mysqld --initialize command from c:\mysql\bin\ directory and I got the data directory in c:\mysql\data. Afterwards I could use mysqld.exe --console command to test the server startup.

Convert row names into first column

A one line option is :

df$names <- rownames(df)

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

How to control border height?

You could create an image of whatever height you wish, and then position that with the CSS background(-position) property like:

#somid { background: url(path/to/img.png) no-repeat center top;

Instead of center topyou can also use pixel or % like 50% 100px.

http://www.w3.org/TR/CSS2/colors.html#propdef-background-position

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

Add item to array in VBScript

Slight change to the FastArray from above:

'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
 If i>ub Then 
    ReDim Preserve a(Int((ub+10)*1.1))
    ub = UBound(a)
 End If
 a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"

MsgBox s

There is no point in checking UBound(a) in every cycle of the for if we know exactly when it changes.

I've changed it so that it checks does UBound(a) just before the for starts and then only every time the ReDim is called

On my computer the old method took 7.52 seconds for an imax of 10 millions.

The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)

How to access first element of JSON object array?

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }

console.log(Object.keys(req)[0]);

Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

How to get text of an element in Selenium WebDriver, without including child element text?

def get_true_text(tag):
    children = tag.find_elements_by_xpath('*')
    original_text = tag.text
    for child in children:
        original_text = original_text.replace(child.text, '', 1)
    return original_text

How to remove specific element from an array using python

There is an alternative solution to this problem which also deals with duplicate matches.

We start with 2 lists of equal length: emails, otherarray. The objective is to remove items from both lists for each index i where emails[i] == '[email protected]'.

This can be achieved using a list comprehension and then splitting via zip:

emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']

from operator import itemgetter

res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))

print(emails)      # ['[email protected]', '[email protected]']
print(otherarray)  # ['some', 'details']

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Your C# action "Save" doesn't execute because your AJAX url is pointing to "/Home/SaveDetailedInfo" and not "/Home/Save".

To call another action from within an action you can maybe try this solution: link

Here's another better solution : link

[HttpPost]
public ActionResult SaveDetailedInfo(Option[] Options)
{
    return Json(new { status = "Success", message = "Success" });
}

[HttpPost]
public ActionResult Save()
{ 
    return RedirectToAction("SaveDetailedInfo", Options);
}

AJAX:

Initial ajax call url: "/Home/Save"
on success callback: 
   make new ajax url: "/Home/SaveDetailedInfo"

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

how to change background image of button when clicked/focused?

You can also create shapes directly inside the item tag, in case you want to add some more details to your view, like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#81ba73" />
            <corners android:radius="6dp" />
        </shape>
        <ripple android:color="#c62828"/>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="#788e73" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#add8a3" />
            <corners android:radius="6dp" />
        </shape>
    </item>
</selector>

Beware that Android will cycle through the items from top to bottom, therefore, you must place the item without condition on the bottom of the list (so it acts like a default/fallback).

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

Find running median from a stream of integers

There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.

The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:

For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,

Step 1: Add next item to one of the heaps

   if next item is smaller than maxHeap root add it to maxHeap,
   else add it to minHeap

Step 2: Balance the heaps (after this step heaps will be either balanced or
   one of them will contain 1 more item)

   if number of elements in one of the heaps is greater than the other by
   more than 1, remove the root element from the one containing more elements and
   add to the other one

Then at any given time you can calculate median like this:

   If the heaps contain equal amount of elements;
     median = (root of maxHeap + root of minHeap)/2
   Else
     median = root of the heap with more elements

Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.

How to convert list of key-value tuples into dictionary?

Another way using dictionary comprehensions,

>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}

read input separated by whitespace(s) or newline...?

the user pressing enter or spaces is the same.

int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line.  Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
    cin >> list[i];
}

Phone validation regex

  ^[0-9\-\+]{9,15}$ 

would match 0+0+0+0+0+0, or 000000000, etc.

  (\-?[0-9]){7}

would match a specific number of digits with optional hyphens in any position among them.

What is this +077 format supposed to be?

It's not a valid format. No country codes begin with 0.

The digits after the + should usually be a country code, 1 to 3 digits long.

Allowing for "+" then country code CC, then optional hyphen, then "0" plus two digits, then hyphens and digits for next seven digits, try:

  ^\+CC\-?0[1-9][0-9](\-?[0-9]){7}$

Oh, and {3,3} is redundant, simplifes to {3}.

View not attached to window manager crash

Override onDestroy of the Activity and Dismiss your Dialog & make it null

protected void onDestroy ()
    {
        if(mProgressDialog != null)
            if(mProgressDialog.isShowing())
                mProgressDialog.dismiss();
        mProgressDialog= null;
    }

How to add hyperlink in JLabel?

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

Move an item inside a list?

A slightly shorter solution, that only moves the item to the end, not anywhere is this:

l += [l.pop(0)]

For example:

>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]

jquery draggable: how to limit the draggable area?

Use the "containment" option:

jQuery UI API - Draggable Widget - containment

The documentation says it only accepts the values: 'parent', 'document', 'window', [x1, y1, x2, y2] but I seem to remember it will accept a selector such as '#container' too.

Flutter Countdown Timer

Countdown timer in one line

CountdownTimer(Duration(seconds: 5), Duration(seconds: 1)).listen((data){
})..onData((data){
  print('data $data');
})..onDone((){
  print('onDone.........');
});

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

Adding a css class to select using @Html.DropDownList()

There are some options in constructors look, if you don't have dropdownList and you wanna insert CSS class you can use like

@Html.DropDownList("Country", null, "Choose-Category", new {@class="form-control"})

in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class if you don't wanna select any default option so simple replace "Choose-Category" with ""

Material Design not styling alert dialogs

when initializing dialog builder, pass second parameter as the theme. It will automatically show material design with API level 21.

AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);

or,

AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

How to disable HTML button using JavaScript?

to disable

document.getElementById("btnPlaceOrder").disabled = true; 

to enable

document.getElementById("btnPlaceOrder").disabled = false; 

Can I return the 'id' field after a LINQ insert?

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

Import multiple csv files into pandas and concatenate into one DataFrame

import pandas as pd
import glob

path = r'C:\DRO\DCL_rawdata_files' # use your path
file_path_list = glob.glob(path + "/*.csv")

file_iter = iter(file_path_list)

list_df_csv = []
list_df_csv.append(pd.read_csv(next(file_iter)))

for file in file_iter:
    lsit_df_csv.append(pd.read_csv(file, header=0))
df = pd.concat(lsit_df_csv, ignore_index=True)

Create a button with rounded border

Use OutlineButton instead of FlatButton.

new OutlineButton(
  child: new Text("Button text"),
  onPressed: null,
  shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
)

Making button go full-width?

The question was raised years ago, with the older version it was a little hard to get...but now this question has a very easy answer.

<div class="btn btn-outline-primary btn-block">Button text here</div>

Gets last digit of a number

here is your method

public int lastDigit(int number)
{
    //your code goes here. 
    int last =number%10;
    return last;
}

What is pipe() function in Angular

Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

How can I issue a single command from the command line through sql plus?

@find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof

select sysdate from dual;

UITableview: How to Disable Selection for Some Rows but Not Others

I like Brian Chapados answer above. However, this means that you may have logic duplicated in both cellForRowAtIndexPath and then in willSelectRowAtIndexPath which can easily get out of sync. Instead of duplicating the logic, just check the selectionStyle:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectionStyle == UITableViewCellSelectionStyleNone)
        return nil;

    else
        return indexPath;
}

Android Failed to install HelloWorld.apk on device (null) Error

Just try the following steps,

  1. Go to Home screen before you start to run the application.
  2. No need to uninstall every time. Just uninstall your application once properly.

    Go to Setting -> Manage Application -> click menu -> filter -> Third party application. Check whether your application is there or not.

  3. After modifying your application just save it. Right click your project and select "Run as Android application".
  4. Note: once again, before running your application check whether or not your emulator is showing the home screen.

going to home screen: from eclipse go to menus: window->android virtual device->start

How to access html form input from asp.net code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

The selected answer led me to fix my problem. But I need to do a few things more:

Even with "Debug" selected in the dropdown:

enter image description here

And in the project Properties > Build:

enter image description here

The Visual Studio was not loading symbols to a specific project. So in that dropdown I select "Configuration Manager" and saw that the settings to my web project was incorrect:

enter image description here

enter image description here

Then I set that to "Debug" and it started to generate the .pdb file. BUT I need to manually copy the PDB and DLL and put in the folder that VS was looking (here is where the selected answer helped me):

enter image description here

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to both read and write a file in C#

Don't forget the easy route:

    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"C:\words.txt");
        File.WriteAllText(@"C:\words.txt", text + "DERP");
    }

How to set a DateTime variable in SQL Server 2008?

2011-01-15 = 2011-16 = 1995. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.

You need to use SET @test = '2011-02-15'

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

Best C/C++ Network Library

Aggregated List of Libraries

Saving and loading objects and using pickle

The following works for me:

class Fruits: pass

banana = Fruits()

banana.color = 'yellow'
banana.value = 30

import pickle

filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()

file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()

print(object_file.color, object_file.value, sep=', ')
# yellow, 30

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I did the below changes and works fine for me.

Just add the attribute <iframe src="URL" target="_parent" />

_parent: this would open embedded page in same window.

_blank: In different tab

How to split strings over multiple lines in Bash?

This probably doesn't really answer your question but you might find it useful anyway.

The first command creates the script that's displayed by the second command.

The third command makes that script executable.

The fourth command provides a usage example.

john@malkovich:~/tmp/so$ echo $'#!/usr/bin/env python\nimport textwrap, sys\n\ndef bash_dedent(text):\n    """Dedent all but the first line in the passed `text`."""\n    try:\n        first, rest = text.split("\\n", 1)\n        return "\\n".join([first, textwrap.dedent(rest)])\n    except ValueError:\n        return text  # single-line string\n\nprint bash_dedent(sys.argv[1])'  > bash_dedent
john@malkovich:~/tmp/so$ cat bash_dedent 
#!/usr/bin/env python
import textwrap, sys

def bash_dedent(text):
    """Dedent all but the first line in the passed `text`."""
    try:
        first, rest = text.split("\n", 1)
        return "\n".join([first, textwrap.dedent(rest)])
    except ValueError:
        return text  # single-line string

print bash_dedent(sys.argv[1])
john@malkovich:~/tmp/so$ chmod a+x bash_dedent
john@malkovich:~/tmp/so$ echo "$(./bash_dedent "first line
>     second line
>     third line")"
first line
second line
third line

Note that if you really want to use this script, it makes more sense to move the executable script into ~/bin so that it will be in your path.

Check the python reference for details on how textwrap.dedent works.

If the usage of $'...' or "$(...)" is confusing to you, ask another question (one per construct) if there's not already one up. It might be nice to provide a link to the question you find/ask so that other people will have a linked reference.

Pass array to MySQL stored routine

You can pass a string with your list and use a prepared statements to run a query, e.g. -

DELIMITER $$

CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END
$$

DELIMITER ;

How to use:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

Uncaught TypeError: Cannot read property 'value' of undefined

You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

How to put text over images in html?

You need to use absolutely-positioned CSS over a relatively-positioned img tag. The article Text Blocks Over Image gives a step-by-step example for placing text over an image.

HTML <input type='file'> File Selection Event

When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick

Update query PHP MySQL

you must write single quotes then double quotes then dot before name of field and after like that

mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

Pass table as parameter into sql server UDF

You can, however no any table. From documentation:

For Transact-SQL functions, all data types, including CLR user-defined types and user-defined table types, are allowed except the timestamp data type.

You can use user-defined table types.

Example of user-defined table type:

CREATE TYPE TableType 
AS TABLE (LocationName VARCHAR(50))
GO 

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

So what you can do is to define your table type, for example TableType and define the function which takes the parameter of this type. An example function:

CREATE FUNCTION Example( @TableName TableType READONLY)
RETURNS VARCHAR(50)
AS
BEGIN
    DECLARE @name VARCHAR(50)

    SELECT TOP 1 @name = LocationName FROM @TableName
    RETURN @name
END

The parameter has to be READONLY. And example usage:

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

SELECT dbo.Example(@myTable)

Depending on what you want achieve you can modify this code.

EDIT: If you have a data in a table you may create a variable:

DECLARE @myTable TableType

And take data from your table to the variable

INSERT INTO @myTable(field_name)
SELECT field_name_2 FROM my_other_table

How can I give an imageview click effect like a button on Android?

I did as follows in XML - with 0 padding around the image and ripple ontop of the image:

<ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/my_image"
    android:clickable="true"
    android:focusable="true"
    android:src="?android:attr/selectableItemBackground" />

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

Calculate text width with JavaScript

Rewritten my answer from scratch (thanks for that minus). Now function accepts a text and css rules to be applied (and doesn't use jQuery anymore). So it will respect paddings too. Resulting values are being rounded (you can see Math.round there, remove if you want more that precise values)

_x000D_
_x000D_
function getSpan(){
    const span = document.createElement('span')
    span.style.position = 'fixed';
    span.style.visibility = 'hidden';
    document.body.appendChild(span);
    return span;
}

function textWidth(str, css) {
    const span = getSpan();
    Object.assign(span.style, css || {});
    span.innerText = str;
    const w = Math.round(span.getBoundingClientRect().width);
    
    span.remove();
    
    return w;
}


const testStyles = [
  {fontSize: '10px'},
  {fontSize: '12px'},
  {fontSize: '60px'},
  {fontSize: '120px'},
  {fontSize: '120px', padding: '10px'},
  {fontSize: '120px', fontFamily: 'arial'},
  {fontSize: '120px', fontFamily: 'tahoma'},
  {fontSize: '120px', fontFamily: 'tahoma', padding: '5px'},
];

const ul = document.getElementById('output');
testStyles.forEach(style => {
  const li = document.createElement('li');
  li.innerText = `${JSON.stringify(style)} > ${textWidth('abc', style)}`;
  ul.appendChild(li);
});
_x000D_
<ul id="output"></ul>
_x000D_
_x000D_
_x000D_

How to resize an image to a specific size in OpenCV?

You can use CvInvoke.Resize for Emgu.CV 3.0

e.g

CvInvoke.Resize(inputImage, outputImage, new System.Drawing.Size(100, 100), 0, 0, Inter.Cubic);

Details are here

How to crop a CvMat in OpenCV?

To create a copy of the crop we want, we can do the following,

// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;

// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);

// Display diff
cv::imshow( "Original Image",  img );
cv::imshow( "Cropped Image",  croppedImg);
cv::waitKey();

Focus Input Box On Load

very simple one line solution:

<body onLoad="document.getElementById('myinputbox').focus();">

How to align an image dead center with bootstrap

I created this and added to Site.css.

.img-responsive-center {
    display: block;
    height: auto;
    max-width: 100%;
    margin-left:auto;
    margin-right:auto;
}

typeof !== "undefined" vs. != null

You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:

(function($, Backbone, _, undefined) {
    //undefined is undefined here.
})(jQuery, Backbone, _);

If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:

if(window.neverDefined === undefined) {
    //Code works
}

Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.

On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I print the type or class of a variable in Swift?

Not exactly what you are after, but you can also check the type of the variable against Swift types like so:

let object: AnyObject = 1

if object is Int {
}
else if object is String {
}

For example.

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

How do I skip an iteration of a `foreach` loop?

You can use the continue statement.

For example:

foreach(int number in numbers)
{
    if(number < 0)
    {
        continue;
    }
}

Clear text area

This works:

$('#textareaName').val('');

Open fancybox from function

You don't have to add you own click event handler at all. Just initialize the element with fancybox:

$(function() {
    $('a[href="#modalMine"]').fancybox({
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true  // as MattBall already said, remove the comma
    });
});

Done. Fancybox already binds a click handler that opens the box. Have a look at the HowTo section.


Later if you want to open the box programmatically, raise the click event on that element:

$('a[href="#modalMine"]').click();

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

Find and replace in file and overwrite file doesn't work, it empties the file

To change multiple files (and saving a backup of each as *.bak):

perl -p -i -e "s/\|/x/g" *  

will take all files in directory and replace | with x this is called a “Perl pie” (easy as a pie)

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

As it turns out, my suspicions were right. The audience aud claim in a JWT is meant to refer to the Resource Servers that should accept the token.

As this post simply puts it:

The audience of a token is the intended recipient of the token.

The audience value is a string -- typically, the base address of the resource being accessed, such as https://contoso.com.

The client_id in OAuth refers to the client application that will be requesting resources from the Resource Server.

The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id and client_secret along with any user credentials that may be required. The Authorization Server validates the client using the client_id and client_secret and returns a JWT.

The JWT will contain an aud claim that specifies which Resource Servers the JWT is valid for. If the aud contains www.myfunwebapp.com, but the client app tries to use the JWT on www.supersecretwebapp.com, then access will be denied because that Resource Server will see that the JWT was not meant for it.

Invalid column name sql error

Change this line:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";

to this:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

Your insert command is expecting text, and you need single quotes (') between the actual value so SQL can understand it as text.

EDIT: For those of you who aren't happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.

Export MySQL data to Excel in PHP

Just Try With The Following :

PHP Part :

<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server    
$DB_Username = "username"; //MySQL Username     
$DB_Password = "password";             //MySQL Password     
$DB_DBName = "databasename";         //MySQL Database Name  
$DB_TBLName = "tablename"; //MySQL Table Name   
$filename = "excelfilename";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/    
//create MySQL connection   
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }   
?>

I think this may help you to resolve your problem.

Counting how many times a certain char appears in a string before any other char appears

You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.

int count = test.Split('$').Length - 1;

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

Bootstrap dropdown menu not working (not dropping down when clicked)

i faced the same problem , the solution worked for me , hope it will work for you too.

<script src="content/js/jquery.min.js"></script>
<script src="content/js/bootstrap.min.js"></script>
<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

Please include the "jquery.min.js" file before "bootstrap.min.js" file, if you shuffle the order it will not work.

Is it possible to write to the console in colour in .NET?

Just to add to the answers above that all use Console.WriteLine: to change colour on the same line of text, write for example:

Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();

Cannot make file java.io.IOException: No such file or directory

Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.

Permissions app

How to make a input field readonly with JavaScript?

You can get the input element and then set its readOnly property to true as follows:

document.getElementById('InputFieldID').readOnly = true;

Specifically, this is what you want:

<script type="text/javascript">
  function onLoadBody() {
    document.getElementById('control_EMAIL').readOnly = true;
  } 
</script>

Call this onLoadBody() function on body tag like:

<body onload="onLoadBody">

View Demo: jsfiddle.

How can I convert a dictionary into a list of tuples?

d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

Java: Identifier expected

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then "run" the class from your IDE

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

Execute JavaScript code stored as a string

Using both eval and creating a new Function to execute javascript comes with a lot of security risks.

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

I prefer this method to execute the Javascript I receive as a string.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

Convert blob to base64

this worked for me:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(blob);
};

Remove all whitespace from C# string with regex

Regex.Replace does not modify its first argument (recall that strings are immutable in .NET) so the call

Regex.Replace(LastName, @"\s+", "");

leaves the LastName string unchanged. You need to call it like this:

LastName = Regex.Replace(LastName, @"\s+", "");

All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.

One liner to check if element is in the list

I would use:

if (Stream.of("a","b","c").anyMatch("a"::equals)) {
    //Code to execute
};

or:

Stream.of("a","b","c")
    .filter("a"::equals)
    .findAny()
    .ifPresent(ignore -> /*Code to execute*/);

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

UPDATE
as you can see correct solution in Learning answer, In SQL server management 2014 you can
1.click on "Edit Top 200 Rows"
and then
2.clicking on "Show SQL Pane (ctrl+3)"
and
3.removing TOP (200) from select query


Refer to Shen Lance answer there is not a way to edit Result of select query. and the other answers is only for normal select and only for 200 records.

HTML: Select multiple as dropdown

It's quite unpractical to make multiple select with size 1. think about it. I made a fiddle here: https://jsfiddle.net/wqd0yd5m/2/

<select name="test" multiple>
    <option>123</option>
    <option>456</option>
    <option>789</option>
</select>

Try to explore other options such as using checkboxes to achieve your goal.

Can a normal Class implement multiple interfaces?

An interface can extend other interfaces. Also an interface cannot implement any other interface. When it comes to a class, it can extend one other class and implement any number of interfaces.

class A extends B implements C,D{...}

SQL Server Management Studio – tips for improving the TSQL coding process

Using bookmarks is great way to keep your sanity if you're working with or troubleshooting a really long procedure. Let's say you're working with a derived field in an outer query and it's definition is another 200 lines down inside the inner query. You can bookmark both locations and then quickly go back and forth between the two.

Using stored procedure output parameters in C#

Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:

DECLARE @NewId int
EXEC    @return_value = [dbo].[usp_InsertContract]
            N'Gary',
            @NewId OUTPUT
SELECT  @NewId

See what it returns. This may give you some hints of why your out param is not filled.

ImportError: No module named 'django.core.urlresolvers'

In my case the problem was that I had outdated django-stronghold installed (0.2.9). And even though in the code I had:

from django.urls import reverse

I still encountered the error. After I upgraded the version to django-stronghold==0.4.0 the problem disappeard.

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

UTF-8 encoding problem in Spring MVC

I've resolved this issue by inferring the produced return type into the first GET requestMethod. The important part here is the

produces="application/json;charset=UTF-8

So every one how use /account/**, Spring will return application/json;charset=UTF-8 content type.

@Controller
@Scope("session") 
@RequestMapping(value={"/account"}, method = RequestMethod.GET,produces="application/json;charset=UTF-8")
public class AccountController {

   protected final Log logger = LogFactory.getLog(getClass());

   ....//More parameters and method here...

   @RequestMapping(value={"/getLast"}, method = RequestMethod.GET)
   public @ResponseBody String getUltimo(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{

      ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
      try {
        Account account = accountDao.getLast();
        return writer.writeValueAsString(account);
      }
      catch (Exception e) {
        return errorHandler(e, response, writer);
      }
}

So, you do not have to set up for each method in your Controller, you can do it for the entire class. If you need more control over a specific method, you just only have to infer the produces return content type.

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

Column count doesn't match value count at row 1

You should also look at new triggers.

MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:

use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;

delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row 
begin 
  insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//

/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

Get url parameters from a string in .NET

You can use the following workaround for it to work with the first parameter too:

var param1 =
    HttpUtility.ParseQueryString(url.Substring(
        new []{0, url.IndexOf('?')}.Max()
    )).Get("param1");

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none
    

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

get the margin size of an element with jquery

The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop'), etc. - note they will have 'px' on the end if you have specified them that way.

Use parseInt() around the result to turn it in to the number value.

NB. As noted by Omaty, the order of the shorthand 'margin' tag is: top right bottom left - the above list was not written in a way intended to be the list order, just a list of that specified in the tag.

Request Permission for Camera and Library in iOS 10 - Info.plist

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

Swift 4.0 and 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

Laravel Eloquent get results grouped by days

this way work properly and I used it in many projects! for example I get data of views the last 30 days:

$viewsData = DB::table('page_views')
    ->where('page_id', $page->id)
    ->whereDate('created_at', '>=', now()->subDays(30))
    ->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
    ->groupBy('date')
    ->get();

If you want to get the number of views based on different IPs, you can use the DISTINCT like below :

$viewsData = DB::table('page_views')
    ->where('page_id', $page->id)
    ->whereDate('created_at', '>=', now()->subDays(30))
    ->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
    ->groupBy('date')
    ->get();

You can easily customize it by manipulating the columns name

How do I manage MongoDB connections in a Node.js web application?

If you have Express.js, you can use express-mongo-db for caching and sharing the MongoDB connection between requests without a pool (since the accepted answer says it is the right way to share the connection).

If not - you can look at its source code and use it in another framework.

How to Pass Parameters to Activator.CreateInstance<T>()

Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.

There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.

Details about the issue on this article.

Graph is taken from the article and represents time taken in ms per 1000 calls.

Performance comparison

Can I get image from canvas element and use it in img src tag?

I'm getting SecurityError: The operation is insecure.

when using canvas.toDataURL('image/jpg'); in safari browser

EditorFor() and html properties

I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
   int maxLength = 100;
   if (ViewData["size"] != null)
   {
       size = (int)ViewData["size"];
   }
   if (ViewData["maxLength"] != null)
   {
       maxLength = (int)ViewData["maxLength"];
   }
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>

In my view, I use

<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>

Works like a charm for me!

htaccess <Directory> deny from all

You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

#place this in /system/.htaccess as you had before
deny from all

How can I force a hard reload in Chrome for Android

The only reliable way I've found that doesn't require plugging the phone in to a PC is as follows:

1. Force stop the Chrome app.

This must be done first, and you cannot re-open Chrome until you finish these steps. There are several ways to force stop. Most home launchers will let you get to "App info" by holding down your finger on the chrome icon and selecting an "i" icon. Alternately, you may be able to go to Android settings and simply search for "Chrome".

Once in "App info", select "Force stop" as shown below:


2. Clear Chrome's cache

Select "Storage" from the same screen:


Finally, select "Clear cache".

When you return to the Chrome app, the page should reload itself and serve a non-cached version.

Additionally, I found a site that makes it easy to test if you've cleared your cache: https://refreshyourcache.com/en/cache-test/
I am in no way affiliated with it. Note that the method to clear the cache mentioned on that site is in fact outdated and no longer valid.

Internet Explorer cache location

If you want to find the folder in a platform independent way, you should query the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache

What do &lt; and &gt; stand for?

In HTML, the less-than sign is used at the beginning of tags. if you use this bracket "<test1>" in content, your bracket content will be unvisible, html renderer is assuming it as a html tag, changing chars with it's ASCI numbers prevents the issue.

with html friendly name:

  &lt;test1&gt; 

or with asci number:

 &#60;test1&#62;

or comple asci:

&#60;&#116;&#101;&#115;&#116;&#49;&#62;

result: <test1>

asci referance: https://www.w3schools.com/charsets/ref_html_ascii.asp

unsigned int vs. size_t

In short, size_t is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.

Sizes should never be negative, and indeed size_t is an unsigned type. Also, because size_t is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.

So, you ask, why not just use an unsigned int? It may not be able to hold big enough numbers. In an implementation where unsigned int is 32 bits, the biggest number it can represent is 4294967295. Some processors, such as the IP16L32, can copy objects larger than 4294967295 bytes.

So, you ask, why not use an unsigned long int? It exacts a performance toll on some platforms. Standard C requires that a long occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.

Using size_t avoids this performance toll. According to this fantastic article, "Type size_t is a typedef that's an alias for some unsigned integer type, typically unsigned int or unsigned long, but possibly even unsigned long long. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."

How to get the HTML for a DOM element in javascript

define function outerHTML based on support for element.outerHTML:

var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
    var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
  } else { // when .outerHTML is not supported
    var outerHTML = function(el){
      var clone = el.cloneNode(true);
      temp_container.appendChild(clone);
      outerhtml = temp_container.innerHTML;
      temp_container.removeChild(clone);
      return outerhtml;
    };
  };

MIN and MAX in C

I don't think that they are standardised macros. There are standardised functions for floating point already, fmax and fmin (and fmaxf for floats, and fmaxl for long doubles).

You can implement them as macros as long as you are aware of the issues of side-effects/double-evaluation.

#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)

In most cases, you can leave it to the compiler to determine what you're trying to do and optimise it as best it can. While this causes problems when used like MAX(i++, j++), I doubt there is ever much need in checking the maximum of incremented values in one go. Increment first, then check.

Comparing double values in C#

// number of digits to be compared    
public int n = 12 
// n+1 because b/a tends to 1 with n leading digits
public double MyEpsilon { get; } = Math.Pow(10, -(n+1)); 

public bool IsEqual(double a, double b)
{
    // Avoiding division by zero
    if (Math.Abs(a)<= double.Epsilon || Math.Abs(b) <= double.Epsilon)
        return Math.Abs(a - b) <=  double.Epsilon;

    // Comparison
    return Math.Abs(1.0 - a / b) <=  MyEpsilon;
}

Explanation

The main comparison function done using division a/b which should go toward 1. But why division? it simply puts one number as reference defines the second one. For example

a = 0.00000012345
b = 0.00000012346
a/b = 0.999919002
b/a = 1.000081004
(a/b)-1 = 8.099789405475458e-5?
1-(b/a) = 8.100445524503848e-5?

or

a=12345*10^8
b=12346*10^8 
a/b = 0.999919002
b/a = 1.000081004
(a/b)-1 = 8.099789405475458e-5?
1-(b/a) = 8.100445524503848e-5?

by division we get rid of trailing or leading zeros (or relatively small numbers) that pollute our judgement of number precision. In the example, the comparison is of order 10^-5, and we have 4 number accuracy, because of that in the beginning code I wrote comparison with 10^(n+1) where n is number accuracy.

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

Using regular expressions to do mass replace in Notepad++ and Vim

In Notepad++ :

<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D


Find what: (.*)(>)(.)
Replace with: \3

Replace All


A
B
C
D

Is there a 'foreach' function in Python 3?

Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

Example:

import random
import numpy as np

ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])

for ptr in np.nditer(ptrs, op_flags=['readwrite']):
    # apply random shift on 1 for each element of the matrix
    ptr += random.choice([-1, 1])

print(ptrs)

d:\>python nditer.py
[[ -1   1]
 [399  -1]
 [  1 399]
 [399 401]]

How to check if a column exists in a SQL Server table?

declare @myColumn   as nvarchar(128)
set @myColumn = 'myColumn'
if not exists (
    select  1
    from    information_schema.columns columns 
    where   columns.table_catalog   = 'myDatabase'
        and columns.table_schema    = 'mySchema' 
        and columns.table_name      = 'myTable' 
        and columns.column_name     = @myColumn
    )
begin
    exec('alter table myDatabase.mySchema.myTable add'
    +'    ['+@myColumn+'] bigint       null')
end

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

How to update data in one table from corresponding data in another table in SQL Server 2005

Try a query like

INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;

Get Insert Statement for existing row in MySQL

you can use Sequel pro to do this, there is an option to 'get as insert statement' for the results obtained

How do I load a file from resource folder?

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
    // Process line
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.

Send JSON data from Javascript to PHP?

You can easily convert object into urlencoded string:

function objToUrlEncode(obj, keys) {
    let str = "";
    keys = keys || [];
    for (let key in obj) {
        keys.push(key);
        if (typeof (obj[key]) === 'object') {
            str += objToUrlEncode(obj[key], keys);
        } else {
            for (let i in keys) {
                if (i == 0) str += keys[0];
                else str += `[${keys[i]}]`
            }
            str += `=${obj[key]}&`;
            keys.pop();
        }
    }
    return str;
}

console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));

// key=value&obj[obj_key]=obj_value&

"Stack overflow in line 0" on Internet Explorer

My was "at line 1" instead but...

I got this problem when using jQuery's .clone method. I replaced these by using making jQuery objects from the html string: $($(selector).html()).

"Press Any Key to Continue" function in C

Use getch():

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

Windows alternative should be _getch().

If you're using Windows, this should be the full example:

#include <conio.h>
#include <ctype.h>

int main( void )
{
    printf("Let the Battle Begin!\n");
    printf("Press Any Key to Continue\n");
    _getch();
}

P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.

good postgresql client for windows?

Actually there is a freeware version of EMS's SQL Manager which is quite powerful

Why is using a wild card with a Java import statement bad?

Performance: No impact on performance as byte code is same. though it will lead to some compile overheads.

Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

The problem is WHEN the event is added and EXECUTED via triggering (the document onload property modification can be verified by examining the properties list).

When does this execute and modify onload relative to the onload event trigger:

document.addEventListener('load', ... );

before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alerting as naively expected:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
                document.addEventListener('load', function(){ alert(42) } );
          </script>
          </head><body>goodbye universe - hello muiltiverse</body>
    </html>

Does loading imply script contents have been executed?

A little out of this world expansion ...
Consider a slight modification:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
              if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
          </script>
        </head><body>goodbye universe - hello muiltiverse</body>
    </html>

and whether the HTML has been loaded or not.

Rendering is certainly pending since goodbye universe - hello muiltiverse is not seen on screen but, does not the confirm( ... ) have to be already loaded to be executed? ... and so document.addEventListener('load', ... ) ... ?

In other words, can you execute code to check for self-loading when the code itself is not yet loaded?

Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.

So which comes first: loading and executing the code or using the code's functionality though not loaded?

onload as a window property works because it is subordinate to the object and not self-referential as in the document case, ie. it's the window's contents, via document, that determine the loaded question err situation.

PS.: When do the following fail to alert(...)? (personally experienced gotcha's):

caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:

window.open(URIstr1,"w") .
   addEventListener('load', 
      function(){ alert(42); 
         window.open(URIstr2,"w") .
            addEventListener('load', 
               function(){ alert(43); 
                  window.open(URIstr3,"w") .
                     addEventListener('load', 
                        function(){ alert(44); 
                 /*  ...  */
                        } )
               } )
      } ) 

alternatively, proceed each successive window.open with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );

data:text/html;charset=utf-8,
    <html content editable><head><!-- tagging fluff --><script>

        window.open(
            "data:text/plain, has no DOM or" ,"Window"
         ) . addEventListener('load', function(){ alert(42) } )

        window.open(
            "data:text/plain, has no DOM but" ,"Window"
         ) . addEventListener('load', function(){ alert(4) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "Window"
         ) . addEventListener('load', function(){ alert(2) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "noWindow"
         ) . addEventListener('load', function(){ alert(1) } )

        /* etc. including where body has onload=... in each appropriate open */

    </script><!-- terminating fluff --></head></html>

which emphasize onload differences as a document or window property.

Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.

ie. From an arbitrary page, this link will do the load but not likely do alert('done'):

    <a href="javascript:window.open('view-source:http://google.ca') . 
                   addEventListener( 'load',  function(){ alert('done') }  )"> src. vu </a>

but if the link is bookmarked and then clicked when viewing a google.ca page, it does both.

test environment:

 window.navigator.userAgent = 
   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

Convert a string to an enum in C#

BEWARE:

enum Example
{
    One = 1,
    Two = 2,
    Three = 3
}

Enum.(Try)Parse() accepts multiple, comma-separated arguments, and combines them with binary 'or' |. You cannot disable this and in my opinion you almost never want it.

var x = Enum.Parse("One,Two"); // x is now Three

Even if Three was not defined, x would still get int value 3. That's even worse: Enum.Parse() can give you a value that is not even defined for the enum!

I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.

Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.

I suggest the following:

    public static bool TryParse<T>(string value, out T result)
        where T : struct
    {
        var cacheKey = "Enum_" + typeof(T).FullName;

        // [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.
        // [Implementation off-topic.]
        var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);

        return enumDictionary.TryGetValue(value.Trim(), out result);
    }

    private static Dictionary<string, T> CreateEnumDictionary<T>()
    {
        return Enum.GetValues(typeof(T))
            .Cast<T>()
            .ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);
    }

Display date in dd/mm/yyyy format in vb.net

I found this catered for dates in 21st Century that could be entered as dd/mm or dd/mm/yy. It is intended to print an attendance register and asks for the meeting date to start with.

Sub Print_Register()

Dim MeetingDate, Answer

    Sheets("Register").Select
    Range("A1").Select
GetDate:
    MeetingDate = DateValue(InputBox("Enter the date of the meeting." & Chr(13) & _
    "Note Format" & Chr(13) & "Format DD/MM/YY or DD/MM", "Meeting Date", , 10000, 10000))
    If MeetingDate = "" Then GoTo TheEnd
    If MeetingDate < 36526 Then MeetingDate = MeetingDate + 36526
    Range("Current_Meeting_Date") = MeetingDate
    Answer = MsgBox("Date OK?", 3)
    If Answer = 2 Then GoTo TheEnd
    If Answer = 7 Then GoTo GetDate
    ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,,,TRUE,,FALSE)"
TheEnd:
End Sub

How to set a default entity property value with Hibernate

what about just setting a default value for the field?

private String _foo = "default";

//property here
public String Foo

if they pass a value, then it will be overwritten, otherwise, you have a default.

Close Bootstrap modal on form submit

Add the same attribute as you have on the Close button:

data-dismiss="modal"

e.g.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

You can also use jQuery if you wish:

$('#frmStudent').submit(function() {

    // submission stuff

    $('#StudentModal').modal('hide');
    return false;
});

What are static factory methods?

A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.

For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.

If you want to implement database pooling, then that would also be done without affecting the rest of the application.

It protects the rest of the application from changes that you may make to the factory, which is the purpose.

The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.

How do you create a hidden div that doesn't create a line break or horizontal space?

In addition to CMS´ answer you may want to consider putting the style in an external stylesheet and assign the style to the id, like this:

#divCheckbox {
display: none;
}

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

not:first-child selector

You can use your selector with :not like bellow you can use any selector inside the :not()

any_CSS_selector:not(any_other_CSS_selector){
    /*YOUR STYLE*/
}

you can use :not without parent selector as well.

   :not(:nth-child(2)){
        /*YOUR STYLE*/
   }

More examples

any_CSS_selector:not(:first-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:checked){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-of-type(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-child(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-child(2)){
    /*YOUR STYLE*/
}