Programs & Examples On #Zend route

Routing in Zend Framework's MVC implementation. Zend Framework is an open source, object-oriented web application framework implemented in PHP 5 and licensed under the New BSD License.

How to access route, post, get etc. parameters in Zend Framework 2

All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:

$params = json_decode(file_get_contents('php://input'), true); print_r($params);

Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make

CURRENT_TIMESTAMP in milliseconds

Postgres: SELECT (extract(epoch from now())*1000)::bigint;

Pretty-Printing JSON with PHP

You could do it like below.

$array = array(
   "a" => "apple",
   "b" => "banana",
   "c" => "catnip"
);

foreach ($array as $a_key => $a_val) {
   $json .= "\"{$a_key}\" : \"{$a_val}\",\n";
}

header('Content-Type: application/json');
echo "{\n"  .rtrim($json, ",\n") . "\n}";

Above would output kind of like Facebook.

{
"a" : "apple",
"b" : "banana",
"c" : "catnip"
}

IntelliJ IDEA generating serialVersionUID

After spending some time on Serialization, I find that, we should not generate serialVersionUID with some random value, we should give it a meaningful value.

Here is a details comment on this. I am coping the comment here.

Actually, you should not be "generating" serial version UIDs. It is a dumb "feature" that stems from the general misunderstanding of how that ID is used by Java. You should be giving these IDs meaningful, readable values, e.g. starting with 1L, and incrementing them each time you think the new version of the class should render all previous versions (that might be previously serialized) obsolete. All utilities that generate such IDs basically do what the JVM does when the ID is not defined: they generate the value based on the content of the class file, hence coming up with unreadable meaningless long integers. If you want each and every version of your class to be distinct (in the eyes of the JVM) then you should not even specify the serialVersionUID value isnce the JVM will produce one on the fly, and the value of each version of your class will be unique. The purpose of defining that value explicitly is to tell the serialization mechanism to treat different versions of the class that have the same SVUID as if they are the same, e.g. not to reject the older serialized versions. So, if you define the ID and never change it (and I assume that's what you do since you rely on the auto-generation, and you probably never re-generate your IDs) you are ensuring that all - even absolutely different - versions of your class will be considered the same by the serialization mechanism. Is that what you want? If not, and if you indeed want to have control over how your objects are recognized, you should be using simple values that you yourself can understand and easily update when you decide that the class has changed significantly. Having a 23-digit value does not help at all.

Hope this helps. Good luck.

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

Play audio file from the assets directory

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

Create a day-of-week column in a Pandas dataframe using Python

Pandas 0.23+

Use pandas.Series.dt.day_name(), since pandas.Timestamp.weekday_name has been deprecated:

import pandas as pd


df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])

df['day_of_week'] = df['my_dates'].dt.day_name()

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Pandas 0.18.1+

As user jezrael points out below, dt.weekday_name was added in version 0.18.1 Pandas Docs

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.weekday_name

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Original Answer:

Use this:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html

See this:

Get weekday/day-of-week for Datetime column of DataFrame

If you want a string instead of an integer do something like this:

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek

days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}

df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1       Thurs
1 2015-01-02       2         Fri
2 2015-01-01       3       Thurs

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

Logging in Scala

I find very convenient using some kind of java logger, sl4j for example, with simple scala wrapper, which brings me such syntax

val #! = new Logger(..) // somewhere deep in dsl.logging.

object User with dsl.logging {

  #! ! "info message"
  #! dbg "debug message"
  #! trace "var a=true"

}

In my opinion very usefull mixin of java proven logging frameworks and scala's fancy syntax.

Get event listeners attached to node using addEventListener

I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:

screen shot of FF Inspector

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

Simplest way to merge ES6 Maps/Sets?

merge to Map

 let merge = {...map1,...map2};

Does --disable-web-security Work In Chrome Anymore?

If you want to automate this: Kill chrome from task Manager First. In Windows - Right Click (or Shift+right click, in-case of taskbar) on Chrome Icon. Select Properties. In "Target" text-box, add --disable-web-security flag.

So text in text-box should look like

C:\Users\njadhav\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --disable-web-security

Click Ok and launch chrome.

Clear screen in shell

An easier way to clear a screen while in python is to use Ctrl + L though it works for the shell as well as other programs.

How to find unused/dead code in java projects

The Structure101 slice perspective will give a list (and dependency graph) of any "orphans" or "orphan groups" of classes or packages that have no dependencies to or from the "main" cluster.

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

Else clause on Python while statement

The else clause is only executed when the while-condition becomes false.

Here are some examples:

Example 1: Initially the condition is false, so else-clause is executed.

i = 99999999

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

this

Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.

i = 0

while i < 5:
    print(i)
    if i == 3:
        break
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3

Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.

i = 0

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3
4
this

Is it safe to delete a NULL pointer?

Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either.

If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.

How to find the statistical mode?

R has so many add-on packages that some of them may well provide the [statistical] mode of a numeric list/series/vector.

However the standard library of R itself doesn't seem to have such a built-in method! One way to work around this is to use some construct like the following (and to turn this to a function if you use often...):

mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)
tabSmpl<-tabulate(mySamples)
SmplMode<-which(tabSmpl== max(tabSmpl))
if(sum(tabSmpl == max(tabSmpl))>1) SmplMode<-NA
> SmplMode
[1] 19

For bigger sample list, one should consider using a temporary variable for the max(tabSmpl) value (I don't know that R would automatically optimize this)

Reference: see "How about median and mode?" in this KickStarting R lesson
This seems to confirm that (at least as of the writing of this lesson) there isn't a mode function in R (well... mode() as you found out is used for asserting the type of variables).

The application has stopped unexpectedly: How to Debug?

Filter your log to just Error and look for FATAL EXCEPTION

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

Thread Safe C# Singleton Pattern

You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance()
    {
        return instance;
    }
}

Twitter bootstrap collapse: change display of toggle button

try this. http://jsfiddle.net/fVpkm/

Html:-

<div class="row-fluid summary">
    <div class="span11">
        <h2>MyHeading</h2>  
    </div>
    <div class="span1">
        <button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
    </div>
</div>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...
    </div>
</div>

JS:-

$('button').click(function(){ //you can give id or class name here for $('button')
    $(this).text(function(i,old){
        return old=='+' ?  '-' : '+';
    });
});

Update With pure Css, pseudo elements

http://jsfiddle.net/r4Bdz/

Supported Browsers

button.btn.collapsed:before
{
    content:'+' ;
    display:block;
    width:15px;
}
button.btn:before
{
    content:'-' ;
    display:block;
    width:15px;
}

Update 2 With pure Javascript

http://jsfiddle.net/WteTy/

function handleClick()
{
    this.value = (this.value == '+' ? '-' : '+');
}
document.getElementById('collapsible').onclick=handleClick;

How to check if array element exists or not in javascript?

This way is easiest one in my opinion.

var nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

And Maybe Another way to do it is.

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }

Getting the first character of a string with $str[0]

It'll vary depending on resources, but you could run the script bellow and see for yourself ;)

<?php
$tests = 100000;

for ($i = 0; $i < $tests; $i++)
{
    $string = md5(rand());
    $position = rand(0, 31);

    $start1 = microtime(true);
    $char1 = $string[$position];
    $end1 = microtime(true);
    $time1[$i] = $end1 - $start1;

    $start2 = microtime(true);
    $char2 = substr($string, $position, 1);
    $end2 = microtime(true);
    $time2[$i] = $end2 - $start2;

    $start3 = microtime(true);
    $char3 = $string{$position};
    $end3 = microtime(true);
    $time3[$i] = $end3 - $start3;
}

$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;

$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;

$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>

Some reference numbers (on an old CoreDuo machine)

$ php 1.php 
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6

It seems that using the [] or {} operators is more or less the same.

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

How to save a spark DataFrame as csv on disk?

Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.

df.coalesce(1)
      .write
      .option("header","true")
      .option("sep",",")
      .mode("overwrite")
      .csv("output/path")

If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

postgresql: INSERT INTO ... (SELECT * ...)

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

View HTTP headers in Google Chrome?

You can find the headers option in the Network tab in Developer's console in Chrome:

  1. In Chrome press F12 to open Developer's console.
  2. Select the Network tab. This tab gives you the information about the requests fired from the browser.
  3. Select a request by clicking on the request name. There you can find the Header information for that request along with some other information like Preview, Response and Timing.

Also, in my version of Chrome (50.0.2661.102), it gives an extension named LIVE HTTP Headers which gives information about the request headers for all the HTTP requests.

update: added image

enter image description here

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

T-SQL: Opposite to string concatenation - how to split string into multiple records

There are a wide varieties of solutions to this problem documented here, including this little gem:

CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
  )

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

form confirm before submit

var r = confirm('Want to delete ?'); 

if (r == true) { 
    $('#admin-category-destroy').submit(); 
}

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Percentage Height HTML 5/CSS

I am trying to set a div to a certain percentage height in CSS

Percentage of what?

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html> and <body>, have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)

Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh) and viewport width (vw):

div {
    height:100vh; 
}

See here for more info.

What is wrong with my SQL here? #1089 - Incorrect prefix key

according to the latest version of MySQL (phpMyAdmin), add a correct INDEX while choosing primary key. for example: id[int] INDEX 0 ,if id is your primary key and at the first index. Or,


For your problem try this one

CREATE TABLE `table`.`users` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(50) NOT NULL,
    `password` VARCHAR(50) NOT NULL,
    `dir` VARCHAR(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

Cannot read property 'addEventListener' of null

Thanks from all, Load the Scripts in specific pages that you use, not for all pages, sometimes using swiper.js or other library it may cause this error message, the only way to solve this issue it to load the JS library on specific pages that ID is exist and prevent loading of the same library in all pages.

Hope this help you.

Are parameters in strings.xml possible?

There is many ways to use it and i recomend you to see this documentation about String Format.

http://developer.android.com/intl/pt-br/reference/java/util/Formatter.html

But, if you need only one variable, you'll need to use %[type] where [type] could be any Flag (see Flag types inside site above). (i.e. "My name is %s" or to set my name UPPERCASE, use this "My name is %S")

<string name="welcome_messages">Hello, %1$S! You have %2$d new message(s) and your quote is %3$.2f%%.</string>

Hello, ANDROID! You have 1 new message(s) and your quote is 80,50%.

Indenting code in Sublime text 2?

Netbeans like Shortcut Key

Go to Preferences > Key Bindings > User and add the code below:

[
    { "keys": ["ctrl+shift+f"], "command": "reindent", "args": {"single_line": false} }
]

Usage

Ctrl + Shift + F

How does true/false work in PHP?

PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Explicitly specifying the max_iter resolves the warning as the default max_iter is 100. [For Logistic Regression].

 logreg = LogisticRegression(max_iter=1000)

how to make window.open pop up Modal?

Modal Window using ExtJS approach.

In Main Window

<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>    
<script type="text/javascript" src="ext-all.js"></script>

function openModalDialog() {
    Ext.onReady(function() {
        Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: Ext.getBody().getViewSize().height*0.8,
        width: Ext.getBody().getViewSize().width*0.8,
        minWidth:'730',
        minHeight:'450',
        layout: 'fit',
        itemId : 'popUpWin',        
        modal:true,
        shadow:false,
        resizable:true,
        constrainHeader:true,
        items: [{
            xtype: 'box',
            autoEl: {
                     tag: 'iframe',
                     src: '2.html',
                     frameBorder:'0'
            }
        }]
        }).show();
  });
}
function closeExtWin(isSubmit) {
     Ext.ComponentQuery.query('#popUpWin')[0].close();
     if (isSubmit) {
          document.forms[0].userAction.value = "refresh";
          document.forms[0].submit();
    }
}
</head>
<body>
   <form action="abc.jsp">
   <a href="javascript:openModalDialog()"> Click to open dialog </a>
   </form>
</body>
</html>

In popupWindow 2.html

<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
     if (action == 'save') {
         window.parent.closeExtWin(true);
     } else {
         window.parent.closeExtWin(false);
     }   
}
</script>
</head>
<body>
    <a href="javascript:doSubmit('save');" title="Save">Save</a>
    <a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>
</body>
</html>

Select by partial string from a pandas DataFrame

There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:

df.filter(regex=".*STRING_YOU_LOOK_FOR.*")

This way let's you get the column you look for whatever the way is wrote.

( Obviusly, you have to write the proper regex expression for each case )

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

It works for me thank you. I had this issue when I installed .Net Framework 4.7.1, somehow DbProviderFactories settings under System.Data in machine config got wiped-out. It started working after adding the necessary configuration settings as shown below DataProviderFactories

<system.data>
    <DbProviderFactories>
      <add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
    </DbProviderFactories>
</system.data>

Git on Windows: How do you set up a mergetool?

As already answered here (and here and here), mergetool is the command to configure this. For a nice graphical frontend I recommend kdiff3 (GPL).

How to maintain page scroll position after a jquery event is carried out?

You can save the current scroll amount and then set it later:

var tempScrollTop = $(window).scrollTop();

..//Your code

$(window).scrollTop(tempScrollTop);

How do I check if a list is empty?

I prefer it explicitly:

if len(li) == 0:
    print('the list is empty')

This way it's 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: ... is that it gives the false impression that li is a boolean variable.

Using async/await for multiple tasks

int[] ids = new[] { 1, 2, 3, 4, 5 };
Parallel.ForEach(ids, i => DoSomething(1, i, blogClient).Wait());

Although you run the operations in parallel with the above code, this code blocks each thread that each operation runs on. For example, if the network call takes 2 seconds, each thread hangs for 2 seconds w/o doing anything but waiting.

int[] ids = new[] { 1, 2, 3, 4, 5 };
Task.WaitAll(ids.Select(i => DoSomething(1, i, blogClient)).ToArray());

On the other hand, the above code with WaitAll also blocks the threads and your threads won't be free to process any other work till the operation ends.

Recommended Approach

I would prefer WhenAll which will perform your operations asynchronously in Parallel.

public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

In fact, in the above case, you don't even need to await, you can just directly return from the method as you don't have any continuations:

public Task DoWork() 
{
    int[] ids = new[] { 1, 2, 3, 4, 5 };
    return Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

To back this up, here is a detailed blog post going through all the alternatives and their advantages/disadvantages: How and Where Concurrent Asynchronous I/O with ASP.NET Web API

How to get maximum value from the Collection (for example ArrayList)?

depending on the size of your array a multithreaded solution might also speed up things

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

Where value in column containing comma delimited values

Although the tricky solution @tbaxter120 advised is good but I use this function and work like a charm, pString is a delimited string and pDelimiter is a delimiter character:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
        (@pString NVARCHAR(MAX), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover VARCHAR(8000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL -- does away with 0 base CTE, and the OR condition in one go!
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ---ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,50000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l

;

Then for example you can call it in where clause as below:

WHERE [fieldname] IN (SELECT LTRIM(RTRIM(Item)) FROM [dbo].[DelimitedSplit]('2,5,11', ','))

Hope this help.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

Different between parseInt() and valueOf() in java?

If you check the Integer class you will find that valueof call parseInt method. The big difference is caching when you call valueof API . It cache if the value is between -128 to 127 Please find below the link for more information

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

What does "Content-type: application/json; charset=utf-8" really mean?

I was using HttpClient and getting back response header with content-type of application/json, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.

There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.

Spring Boot Configure and Use Two DataSources

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

Most answers do not provide how to use them (as datasource itself and as transaction), only how to config them.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

IF statement: how to leave cell blank if condition is false ("" does not work)

You could try this.

=IF(A1=1,B1,TRIM(" "))

If you put this formula in cell C1, then you could test if this cell is blank in another cells

=ISBLANK(C1)

You should see TRUE. I've tried on Microsoft Excel 2013. Hope this helps.

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

How to change progress bar's progress color in Android

Horizontal progress bar custom material style :

To change color of background and progress of horizontal progress bar.

<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">#69f0ae</item>
    <item name="android:progressTint">#b71c1c</item>
    <item name="android:minWidth">200dp</item>
</style>

Apply it to progress bar by setting style attribute, for custom material styles and custom progress bar check http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples

IF...THEN...ELSE using XML

Perhaps another way to code conditional constructs in XML:

<rule>
    <if>
        <conditions>
            <condition var="something" operator="&gt;">400</condition>
            <!-- more conditions possible -->
        </conditions>
        <statements>
            <!-- do something -->
        </statements>
    </if>
    <elseif>
        <conditions></conditions>
        <statements></statements>
    </elseif>
    <else>
        <statements></statements>
    </else>
</rule>

How do I get the name of a Ruby class?

If you want to get a class name from inside a class method, class.name or self.class.name won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

module Foo
  class Bar
    def self.say_name
      puts "I'm a #{name}!"
    end
  end
end

Foo::Bar.say_name

output:

I'm a Foo::Bar!

How do I get the height of a div's full content with jQuery?

If you can possibly help it, DO NOT USE .scrollHeight.

.scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).

For example:

<div id='outer' style='width:100px; height:350px; overflow-y:hidden;'>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
</div>

If you do

console.log($('#outer').scrollHeight);

you'll get 900px in Chrome, FireFox and Opera. That's great.

But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).

A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):

$('#outer').css("height", "auto");
var outerContentsHeight = $('#outer').height();
$('#outer').css("height", "350px");

console.log(outerContentsHeight); //Should get 900px in these 3 browsers

The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.

Where is the Keytool application?

For me it turned out to be in c/Program Files/Java/jdk1.7.0_25/bin (Windows 8). A more general answer to this question is that it will most likely be in the bin sub directory of wherever your jdk is installed.

Efficiency of Java "Double Brace Initialization"?

To create sets you can use a varargs factory method instead of double-brace initialisation:

public static Set<T> setOf(T ... elements) {
    return new HashSet<T>(Arrays.asList(elements));
}

The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.

As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I had this problem and used this technique.

Its the best solution i found which is very flexible.

Also please vote here to add support for cumulative section declaration

req.body empty on posts

A similar problem happened to me, I simply mixed the order of the callback params. Make sure your are setting up the callback functions in the correct order. At least for anyone having the same problem.

router.post('/', function(req, res){});

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

Sequel Pro Alternative for Windows

Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).

From the website:

Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.

Execute ssh with password authentication via windows command prompt

PowerShell solution

Using Posh-SSH:

New-SSHSession -ComputerName 0.0.0.0 -Credential $cred | Out-Null
Invoke-SSHCommand -SessionId 1 -Command "nohup sleep 5 >> abs.log &" | Out-Null

Converting string format to datetime in mm/dd/yyyy

You need an uppercase M for the month part.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Lowercase m is for outputting (and parsing) a minute (such as h:mm).

e.g. a full date time string might look like this:

string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");

Notice the uppercase/lowercase mM difference.


Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.

public static class DateTimeMyFormatExtensions
{
  public static string ToMyFormatString(this DateTime dt)
  {
    return dt.ToString("MM/dd/yyyy");
  }
}

public static class StringMyDateTimeFormatExtension
{
  public static DateTime ParseMyFormatDateTime(this string s)
  {
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
  }
}

EXAMPLE: Translating between DateTime/string

DateTime now = DateTime.Now;

string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();

Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.

System.Globalization.CultureInfo.CurrentCulture.

The only easy way you can do is to roll a custom extension method.

Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.

How to use a dot "." to access members of dictionary?

I recently came across the 'Box' library which does the same thing.

Installation command : pip install python-box

Example:

from box import Box

mydict = {"key1":{"v1":0.375,
                    "v2":0.625},
          "key2":0.125,
          }
mydict = Box(mydict)

print(mydict.key1.v1)

I found it to be more effective than other existing libraries like dotmap, which generate python recursion error when you have large nested dicts.

link to library and details: https://pypi.org/project/python-box/

git push rejected: error: failed to push some refs

I did the following steps to resolve the issue. On the branch which was giving me the error:

  1. git pull origin [branch-name]<current branch>
  2. After pulling, got some merge issues, solved them, pushed the changes to the same branch.
  3. Created the Pull request with the pushed branch... tada, My changes were reflecting, all of them.

Pass arguments to Constructor in VBA

I use one Factory module that contains one (or more) constructor per class which calls the Init member of each class.

For example a Point class:

Class Point
Private X, Y
Sub Init(X, Y)
  Me.X = X
  Me.Y = Y
End Sub

A Line class

Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  If P1 Is Nothing Then
    Set Me.P1 = NewPoint(X1, Y1)
    Set Me.P2 = NewPoint(X2, Y2)
  Else
    Set Me.P1 = P1
    Set Me.P2 = P2
  End If
End Sub

And a Factory module:

Module Factory
Function NewPoint(X, Y)
  Set NewPoint = New Point
  NewPoint.Init X, Y
End Function

Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  Set NewLine = New Line
  NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function

Function NewLinePt(P1, P2)
  Set NewLinePt = New Line
  NewLinePt.Init P1:=P1, P2:=P2
End Function

Function NewLineXY(X1, Y1, X2, Y2)
  Set NewLineXY = New Line
  NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function

One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:

D = Distance(NewPoint(10, 10), NewPoint(20, 20)

or:

D = NewPoint(10, 10).Distance(NewPoint(20, 20))

It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init call on each creator.

And it's fairly object oriented: the Init functions are defined inside the objects.

EDIT

I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):

NewLine.DeleteAllLinesShorterThan 10

Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.

This certificate has an invalid issuer Apple Push Services

In Apple's Developer's portal, add a new certificate, and when asked "What type of certificate do you need?" choose "WorldWide developer relations certificate". Generate the new certificate, download and install. The moment you do that, you will no longer see the message you have described.

Edit:
The certificate can be downloaded from the following page: https://www.apple.com/certificateauthority/ You can choose one of the following two certificates: "WWDR Certificate (Expiring 02/07/23)" or "WWDR Certificate (Expiring 02/14/16)"

Where is the itoa function in Linux?

If you are calling it a lot, the advice of "just use snprintf" can be annoying. So here's what you probably want:

const char *my_itoa_buf(char *buf, size_t len, int num)
{
  static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */

  if (!buf)
  {
    buf = loc_buf;
    len = sizeof(loc_buf);
  }

  if (snprintf(buf, len, "%d", num) == -1)
    return ""; /* or whatever */

  return buf;
}

const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }

java.lang.IllegalArgumentException: View not attached to window manager

i agree a opinion of 'Damjan'.
if you use many dialogs, should close all dialog in onDestroy() or onStop().
then you may be able to reduce the frequency 'java.lang.IllegalArgumentException: View not attached to window manager' exception occurs.

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mDialog.dismiss();
    super.onDestroy();
}



but little exceed...
to make it more clear, you prevent to show any dialog after onDestroy called.
i don't use as below. but it's clear.

private boolean mIsDestroyed = false;

private void showDialog() {
    closeDialog();

    if (mIsDestroyed) {
        Log.d(TAG, "called onDestroy() already.");
        return;
    }

    mDialog = new AlertDialog(this)
        .setTitle("title")
        .setMessage("This is DialogTest")
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
        .create();
    mDialog.show();
}

private void closeDialog() {
    if (mDialog != null) {
        mDialog.dismiss();
    }
}

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mIsDestroyed = true;
    closeDialog();
    super.onDestroy();
}


good luck!

Save modifications in place with awk

@sudo_O has the right answer.

This can't work:

someprocess < file > file

The shell performs the redirections before handing control over to someprocess (redirections). The > redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.

Do something if screen width is less than 960 px

use

$(window).width()

or

$(document).width()

or

$('body').width()

Javascript/jQuery: Set Values (Selection) in a multiple Select

this is error in some answers for replace |

var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);

this correction is correct but the | In the end it should look like this \|

var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

Fastest way to check if string contains only digits

You can do this in a one line LINQ statement. OK, I realise this is not necessarily the fastest, so doesn't technically answer the question, but it's probably the easiest to write:

str.All(c => c >= '0' && c <= '9')

Disable Tensorflow debugging information

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.

Use of exit() function

Bad programming practice. Using a goto function is a complete no no in C programming.
Also include header file stdlib.h by writing #include <iostream.h>for using exit() function. Also remember that exit() function takes an integer argument . Use exit(0) if the program completed successfully and exit(-1) or exit function with any non zero value as the argument if the program has error.

Detect when input has a 'readonly' attribute

Try a simple way:

if($('input[readonly="readonly"]')){
   alert("foo");
}

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

How can I divide two integers stored in variables in Python?

if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b

Try float(a)/b

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

Generate a random letter in Python

import random
def Random_Alpha():
    l = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    return l[random.randint(0,25)]

print(Random_Alpha())

How do I correctly clean up a Python object?

Just wrap your destructor with a try/except statement and it will not throw an exception if your globals are already disposed of.

Edit

Try this:

from weakref import proxy

class MyList(list): pass

class Package:
    def __init__(self):
        self.__del__.im_func.files = MyList([1,2,3,4])
        self.files = proxy(self.__del__.im_func.files)

    def __del__(self):
        print self.__del__.im_func.files

It will stuff the file list in the del function that is guaranteed to exist at the time of call. The weakref proxy is to prevent Python, or yourself from deleting the self.files variable somehow (if it is deleted, then it will not affect the original file list). If it is not the case that this is being deleted even though there are more references to the variable, then you can remove the proxy encapsulation.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc. This is an ObjectId but "foo" is not a valid ObjectId so the cast fails.

This doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId.

One way to resolve this is to add a check prior to your findById call to see if id is a valid ObjectId or not like so:

if (id.match(/^[0-9a-fA-F]{24}$/)) {
  // Yes, it's a valid ObjectId, proceed with `findById` call.
}

How do I add more members to my ENUM-type column in MySQL?

It's possible if you believe. Hehe. try this code.

public function add_new_enum($new_value)
  {
    $table="product";
    $column="category";
         $row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();

    $old_category = array();
    $new_category="";
    foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
    {
        //getting the old category first

        $old_category[$val] = $val;
        $new_category.="'".$old_category[$val]."'".",";
    }

     //after the end of foreach, add the $new_value to $new_category

      $new_category.="'".$new_value."'";

    //Then alter the table column with the new enum

    $this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
  }

Before adding new value

After adding new value

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

Iterating through a variable length array

here is an example, where the length of the array is changed during execution of the loop

import java.util.ArrayList;
public class VariableArrayLengthLoop {

public static void main(String[] args) {

    //create new ArrayList
    ArrayList<String> aListFruits = new ArrayList<String>();

    //add objects to ArrayList
    aListFruits.add("Apple");
    aListFruits.add("Banana");
    aListFruits.add("Orange");
    aListFruits.add("Strawberry");

    //iterate ArrayList using for loop
    for(int i = 0; i < aListFruits.size(); i++){

        System.out.println( aListFruits.get(i) + " i = "+i );
         if ( i == 2 ) {
                aListFruits.add("Pineapple");  
                System.out.println( "added now a Fruit to the List "); 
                }
        }
    }
}

Change color of bootstrap navbar on hover link?

This is cleaner:

ul.nav a:hover { color: #fff !important; }

There's no need to get more specific than this. Unfortunately, the !important is necessary in this instance.

I also added :focus and :active to the same declaration for accessibility reasons and for smartphone/tablet/touchscreen users.

What is use of c_str function In c++

Most OLD c++ and c functions, when deal with strings, use const char*.
With STL and std::string, string.c_str() is introduced to be able to convert from std::string to const char*.

That means that if you promise not to change the buffer, you'll be able to use read only string contents. PROMISE = const char*

SQL: how to select a single id ("row") that meets multiple criteria from a single column

one of the approach if you want to get all user_id that satisfies all conditions is:

SELECT DISTINCT user_id FROM table WHERE ancestry IN ('England', '...', '...') GROUP BY user_id HAVING count(*) = <number of conditions that has to be satisfied> 

etc. If you need to take all user_ids that satisfies at least one condition, then you can do

SELECT DISTINCT user_id from table where ancestry IN ('England', 'France', ... , '...')

I am not aware if there is something similar to IN but that joins conditions with AND instead of OR

What does the star operator mean, in a function call?

It is called the extended call syntax. From the documentation:

If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

and:

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Overview of JSP Syntax Elements

First, to make things more clear, here is a short overview of JSP syntax elements:

  • Directives: These convey information regarding the JSP page as a whole.
  • Scripting elements: These are Java coding elements such as declarations, expressions, scriptlets, and comments.
  • Objects and scopes: JSP objects can be created either explicitly or implicitly and are accessible within a given scope, such as from anywhere in the JSP page or the session.
  • Actions: These create objects or affect the output stream in the JSP response (or both).

How content is included in JSP

There are several mechanisms for reusing content in a JSP file.

The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")

1) The include directive:

<%@ include file="header.html" %>

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

2) The <jsp:include> standard action:

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

3) The <c:import> JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like <jsp:include>, but it’s more powerful and flexible: unlike the other two includes, the <c:import> url can be from outside the web Container!

4) Preludes and codas:

Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding <include-prelude> and <include-coda> elements respectively within a <jsp-property-group> element in the Web application web.xml deployment descriptor. Read more here:
Configuring Implicit Includes at the Beginning and End of JSPs
Defining implicit includes


Tag File is an indirect method of content reuse, the way of encapsulating reusable content. A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.

The PURPOSE of includes and Tag Files is different.

Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags. Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.

Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.


Regarding your Edit

Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can

  • Be customized by means of attributes passed from the calling page.

  • Pass variables back to the calling page.

  • Access all the objects available to JSP pages.

  • Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.

  • Be nested within one another and communicate by means of private variables.

Also read this from "Pro JSP 2": Understanding JSP Custom Tags.


Useful reading.


Conclusion

Use the right tools for each task.

Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.

As for the including content in JSP (quote from here):

  • Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
  • Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.

How do you create a dropdownlist from an enum in ASP.NET MVC?

I found an answer here. However, some of my enums have [Description(...)] attribute, so I've modified the code to provide support for that:

    enum Abc
    {
        [Description("Cba")]
        Abc,

        Def
    }


    public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, string name, TEnum selectedValue)
    {
        IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum))
            .Cast<TEnum>();

        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var value in values)
        {
            string text = value.ToString();

            var member = typeof(TEnum).GetMember(value.ToString());
            if (member.Count() > 0)
            {
                var customAttributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (customAttributes.Count() > 0)
                {
                    text = ((DescriptionAttribute)customAttributes[0]).Description;
                }
            }

            items.Add(new SelectListItem
            {
                Text = text,
                Value = value.ToString(),
                Selected = (value.Equals(selectedValue))
            });
        }

        return htmlHelper.DropDownList(
            name,
            items
            );
    }

Hope that helps.

How to make div same height as parent (displayed as table-cell)

You can use this CSS:

.content {
    height: 100%;
    display: inline-table;
    background-color: blue;
}

JSFiddle

In Java, how do you determine if a thread is running?

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.

Java constructor/method with optional parameters?

Why do you want to do that?

However, You can do this:

public void foo(int param1)
{
    int param2 = 2;
    // rest of code
}

or:

public void foo(int param1, int param2)
{
    // rest of code
}

public void foo(int param1)
{
    foo(param1, 2);
}

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

How to get all options of a select using jQuery?

    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

scp (secure copy) to ec2 instance without password

write this code

scp -r -o "ForwardAgent=yes" /Users/pengge/11.vim [email protected]:/root/

If you have a SSH key with access to the destination server and the source server does not, adding -o "ForwardAgent=yes" will allow you to forward your SSH agent to the source server so that it can use your SSH key to connect to the destination server.

How to manually send HTTP POST requests from Firefox or Chrome browser?

Here's the Advanced REST Client extension for Chrome.

It works great for me -- do remember that you can still use the debugger with it. The Network pane is particularly useful; it'll give you rendered JSON objects and error pages.

PHP salt and hash SHA256 for login password

You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.

Change EditText hint color when using TextInputLayout

Use TextInputLayout.setDefaultHintTextColor

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

fatal: Not a valid object name: 'master'

copying Superfly Jon's comment into an answer:

To create a new branch without committing on master, you can use:

git checkout -b <branchname>

Could not load file or assembly 'Microsoft.Web.Infrastructure,

I had to set "Copy Local" in the Reference Properties to False, then back to True. Doing this added the Private True setting to the .csproj file.

<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">      <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
      <Private>True</Private>
    </Reference>

I had assumed this was already set, since the "Copy Local" showed as True.

Try/catch does not seem to have an effect

If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.

try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";  
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default
}

Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.

function log([System.String] $text){write-host $text;}

function logException{
    log "Logging current exception.";
    log $Error[0].Exception;
}


function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
                    [System.Management.Automation.ScriptBlock] $catch,
                    [System.Management.Automation.ScriptBlock]  $finally = $({})){



# Make all errors terminating exceptions.
    $ErrorActionPreference = "Stop";

    # Set the trap
    trap [System.Exception]{
        # Log the exception.
        logException;

        # Execute the catch statement
        & $catch;

        # Execute the finally statement
        & $finally

        # There was an exception, return false
        return $false;
    }

    # Execute the scriptblock
    & $try;

    # Execute the finally statement
    & $finally

    # The following statement was hit.. so there were no errors with the scriptblock
    return $true;
}


#execute your own try catch
mytrycatch {
        gi filethatdoesnotexist; #normally non-terminating
        write-host "You won't hit me."
    } {
        Write-Host "Caught the exception";
    }

Cross-reference (named anchor) in markdown

Using the latest Markdown, you should be able to use the following syntax:

[](){:name='anchorName'}

This should create the following HTML:

<a name="anchorName"></a>

If you wanted the anchor to have text, simply add the anchor text within the square brackets:

[Some Text](){:name='anchorName'}

Resize image in PHP

You need to use either PHP's ImageMagick or GD functions to work with images.

With GD, for example, it's as simple as...

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

And you could call this function, like so...

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

Disable scrolling when touch moving certain element

Note: As pointed out in the comments by @nevf, this solution may no longer work (at least in Chrome) due to performance changes. The recommendation is to use touch-action which is also suggested by @JohnWeisz's answer.

Similar to the answer given by @Llepwryd, I used a combination of ontouchstart and ontouchmove to prevent scrolling when it is on a certain element.

Taken as-is from a project of mine:

window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e)
{
    if ($(e.target).closest('#mobileMenuHeader').length == 1)
    {
        blockMenuHeaderScroll = true;
    }
});
$(window).on('touchend', function()
{
    blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e)
{
    if (blockMenuHeaderScroll)
    {
        e.preventDefault();
    }
});

Essentially, what I am doing is listening on the touch start to see whether it begins on an element that is a child of another using jQuery .closest and allowing that to turn on/off the touch movement doing scrolling. The e.target refers to the element that the touch start begins with.

You want to prevent the default on the touch move event however you also need to clear your flag for this at the end of the touch event otherwise no touch scroll events will work.

This can be accomplished without jQuery however for my usage, I already had jQuery and didn't need to code something up to find whether the element has a particular parent.

Tested in Chrome on Android and an iPod Touch as of 2013-06-18

How to set a parameter in a HttpServletRequest?

From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using

void setAttribute(String name, Object o);

and then

Object getAttribute(String name);

Apache and Node.js on the Same Server

This question belongs more on Server Fault but FWIW I'd say running Apache in front of Node.js is not a good approach in most cases.

Apache's ProxyPass is awesome for lots of things (like exposing Tomcat based services as part of a site) and if your Node.js app is just doing a specific, small role or is an internal tool that's only likely to have a limited number of users then it might be easier just to use it so you can get it working and move on, but that doesn't sound like the case here.

If you want to take advantage of the performance and scale you'll get from using Node.js - and especially if you want to use something that involves maintaining a persistent connection like web sockets - you are better off running both Apache and your Node.js on other ports (e.g. Apache on localhost:8080, Node.js on localhost:3000) and then running something like nginx, Varnish or HA proxy in front - and routing traffic that way.

With something like varnish or nginx you can route traffic based on path and/or host. They both use much less system resources and is much more scalable that using Apache to do the same thing.

POSTing JsonObject With HttpClient From Web API

The easiest way is to use a StringContent, with the JSON representation of your JSON object.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));

How to check if an object implements an interface?

If you want a method like public void doSomething([Object implements Serializable]) you can just type it like this public void doSomething(Serializable serializableObject). You can now pass it any object that implements Serializable but using the serializableObject you only have access to the methods implemented in the object from the Serializable interface.

how to get right offset of an element? - jQuery

Maybe I'm misunderstanding your question, but the offset is supposed to give you two variables: a horizontal and a vertical. This defines the position of the element. So what you're looking for is:

$("#whatever").offset().left

and

$("#whatever").offset().top

If you need to know where the right boundary of your element is, then you should use:

$("#whatever").offset().left + $("#whatever").outerWidth()

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

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

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

e.g.

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

Video auto play is not working in Safari and Chrome desktop browser

This is because of now chrome is preventing auto play in html5 video, so by default they will not allow auto play. so we can change this settings using chrome flag settings. this is not possible for normal case so i have find another solution. this is working perfect... (add preload="auto")

<video autoplay preload="auto" loop="loop" muted="muted" id="videoBanner" class="videoBanner">
<source src="banner-video.webm" type="video/webm">
<source src="banner-video.mp4" type="video/mp4">
<source src="banner-video.ogg" type="video/ogg">

var herovide = document.getElementById('videoBanner');
       herovide.autoplay=true;
       herovide.load();  

How to send 500 Internal Server Error error from a PHP script

You may use the following function to send a status change:

function header_status($statusCode) {
    static $status_codes = null;

    if ($status_codes === null) {
        $status_codes = array (
            100 => 'Continue',
            101 => 'Switching Protocols',
            102 => 'Processing',
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            207 => 'Multi-Status',
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            307 => 'Temporary Redirect',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            422 => 'Unprocessable Entity',
            423 => 'Locked',
            424 => 'Failed Dependency',
            426 => 'Upgrade Required',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            506 => 'Variant Also Negotiates',
            507 => 'Insufficient Storage',
            509 => 'Bandwidth Limit Exceeded',
            510 => 'Not Extended'
        );
    }

    if ($status_codes[$statusCode] !== null) {
        $status_string = $statusCode . ' ' . $status_codes[$statusCode];
        header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
    }
}

You may use it as such:

<?php
header_status(500);

if (that_happened) {
    die("that happened")
}

if (something_else_happened) {
    die("something else happened")
}

update_database();

header_status(200);

How do I print a double value with full precision using cout?

By full precision, I assume mean enough precision to show the best approximation to the intended value, but it should be pointed out that double is stored using base 2 representation and base 2 can't represent something as trivial as 1.1 exactly. The only way to get the full-full precision of the actual double (with NO ROUND OFF ERROR) is to print out the binary bits (or hex nybbles).

One way of doing that is using a union to type-pun the double to a integer and then printing the integer, since integers do not suffer from truncation or round-off issues. (Type punning like this is not supported by the C++ standard, but it is supported in C. However, most C++ compilers will probably print out the correct value anyways. I think g++ supports this.)

union {
    double d;
    uint64_t u64;
} x;
x.d = 1.1;
std::cout << std::hex << x.u64;

This will give you the 100% accurate precision of the double... and be utterly unreadable because humans can't read IEEE double format ! Wikipedia has a good write up on how to interpret the binary bits.

In newer C++, you can do

std::cout << std::hexfloat << 1.1;

Strip all non-numeric characters from string in JavaScript

try

myString.match(/\d/g).join``

_x000D_
_x000D_
var myString = 'abc123.8<blah>'_x000D_
console.log( myString.match(/\d/g).join`` );
_x000D_
_x000D_
_x000D_

downcast and upcast

Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.

Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.

But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.

So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.

Use a LIKE statement on SQL Server XML Datatype

This is what I am going to use based on marc_s answer:

SELECT 
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)

FROM WEBPAGECONTENT 
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0

Return a substring on the search where the search criteria exists

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I was receiving this error CastError: Cast to ObjectId failed for value “[object Object]” at path “_id” after creating a schema, then modifying it and couldn't track it down. I deleted all the documents in the collection and I could add 1 object but not a second. I ended up deleting the collection in Mongo and that worked as Mongoose recreated the collection.

How can I delete all Git branches which have been merged?

Based on some of these answers I made my own Bash script to do it too!

It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.

merged_branches(){
  local current_branch=$(git rev-parse --abbrev-ref HEAD)
  for branch in $(git branch --merged | cut -c3-)
    do
      echo "Branch $branch is already merged into $current_branch."
      echo "Would you like to delete it? [Y]es/[N]o "
      read REPLY
      if [[ $REPLY =~ ^[Yy] ]]; then
        git branch -d $branch
      fi
  done
}

How do you use bcrypt for hashing passwords in PHP?

Here's an updated answer to this old question!

The right way to hash passwords in PHP since 5.5 is with password_hash(), and the right way to verify them is with password_verify(), and this is still true in PHP 8.0. These functions use bcrypt hashes by default, but other stronger algorithms have been added. You can alter the work factor (effectively how "strong" the encryption is) via the password_hash parameters.

However, while it's still plenty strong enough, bcrypt is no longer considered state-of-the-art; a better set of password hash algorithms has arrived called Argon2, with Argon2i, Argon2d, and Argon2id variants. The difference between them (as described here):

Argon2 has one primary variant: Argon2id, and two supplementary variants: Argon2d and Argon2i. Argon2d uses data-depending memory access, which makes it suitable for cryptocurrencies and proof-of-work applications with no threats from side-channel timing attacks. Argon2i uses data-independent memory access, which is preferred for password hashing and password-based key derivation. Argon2id works as Argon2i for the first half of the first iteration over the memory, and as Argon2d for the rest, thus providing both side-channel attack protection and brute-force cost savings due to time-memory tradeoffs.

Argon2i support was added in PHP 7.2, and you request it like this:

$hash = password_hash('mypassword', PASSWORD_ARGON2I);

and Argon2id support was added in PHP 7.3:

$hash = password_hash('mypassword', PASSWORD_ARGON2ID);

No changes are required for verifying passwords since the resulting hash string contains information about what algorithm, salt, and work factors were used when it was created.

Quite separately (and somewhat redundantly), libsodium (added in PHP 7.2) also provides Argon2 hashing via the sodium_crypto_pwhash_str () and sodium_crypto_pwhash_str_verify() functions, which work much the same way as the PHP built-ins. One possible reason for using these is that PHP may sometimes be compiled without libargon2, which makes the Argon2 algorithms unavailable to the password_hash function; PHP 7.2 and higher should always have libsodium enabled, but it may not - but at least there are two ways you can get at that algorithm. Here's how you can create an Argon2id hash with libsodium (even in PHP 7.2, which otherwise lacks Argon2id support)):

$hash = sodium_crypto_pwhash_str(
    'mypassword',
    SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
    SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);

Note that it doesn't allow you to specify a salt manually; this is part of libsodium's ethos – don't allow users to set params to values that might compromise security – for example there is nothing preventing you from passing an empty salt string to PHP's password_hash function; libsodium doesn't let you do anything so silly!

How to remove numbers from a string?

You're remarkably close.

Here's the code you wrote in the question:

questionText.replace(/[0-9]/g, '');

The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.

However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:

questionText = questionText.replace(/[0-9]/g, '');

Trigger event when user scroll to specific element - with jQuery

Fire scroll only once after a successful scroll

The accepted answer worked for me (90%) but I had to tweak it a little to actually fire only once.

$(window).on('scroll',function() {
            var hT = $('#comment-box-section').offset().top,
                hH = $('#comment-box-section').outerHeight(),
                wH = $(window).height(),
                wS = $(this).scrollTop();

            if (wS > ((hT+hH-wH)-500)){
                console.log('comment box section arrived! eh');
                // After Stuff
                $(window).off('scroll');
                doStuff();
            }

        });

Note: By successful scroll I mean when user has scrolled to my element or in other words when my element is in view.

Oracle - Insert New Row with Auto Incremental ID

To get an auto increment number you need to use a sequence in Oracle. (See here and here).

CREATE SEQUENCE my_seq;

SELECT my_seq.NEXTVAL FROM DUAL; -- to get the next value

-- use in a trigger for your table demo
CREATE OR REPLACE TRIGGER demo_increment 
BEFORE INSERT ON demo
FOR EACH ROW

BEGIN
  SELECT my_seq.NEXTVAL
  INTO   :new.id
  FROM   dual;
END;
/

syntax error: unexpected token <

This usually happens when you're including or posting to a file which doesn't exist. The server will return a regular html-formatted "404 Not Found" enclosed with

'<html></html>' 

tags. That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.

What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?

EDIT (several years later)

The root cause might not always come from 404 errors. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned

{
   error: "you must be authenticated to make this request"
}

With header 401. And instead I got

<html>You must be authenticated to make this request</html>

With header 200.

Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

SQL Server - Adding a string to a text column (concat equivalent)

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table 
create table test (
    a text
) 
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works: 
update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added

hope that helps

How to define an enumerated type (enum) in C?

I tried with gcc and come up with for my need I was forced to use the last alternative, to compile with out error.

typedef enum state {a = 0, b = 1, c = 2} state;

typedef enum state {a = 0, b = 1, c = 2} state;

typedef enum state old; // New type, alias of the state type.
typedef enum state new; // New type, alias of the state type.

new now     = a;
old before  = b;

printf("State   now = %d \n", now);
printf("Sate before = %d \n\n", before);

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

Storing and Retrieving ArrayList values from hashmap

Our variable:

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

To store:

map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

To add numbers one and one, you can do something like this:

String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);

In Java 8 you can use putIfAbsent to add the list if it did not exist already:

map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);

Use the map.entrySet() method to iterate on:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}

How to write to files using utl_file in oracle

Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:

declare 
  fHandle  UTL_FILE.FILE_TYPE;
begin
  fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');

  UTL_FILE.PUT(fHandle, 'This is the first line');
  UTL_FILE.PUT(fHandle, 'This is the second line');
  UTL_FILE.PUT_LINE(fHandle, 'This is the third line');

  UTL_FILE.FCLOSE(fHandle);
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || '  SQLERRM=' || SQLERRM);
    RAISE;
end;

The output from this looks like:

This is the first lineThis is the second lineThis is the third line

Share and enjoy.

How do I escape only single quotes?

I am not sure what exactly you are doing with your data, but you could always try:

$string = str_replace("'", "%27", $string);

I use this whenever strings are sent to a database for storage.

%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.

To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.

Happy injection avoiding!

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.

All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).

In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.

More food for thought...

There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.

For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:

  • Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.

  • Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.

  • Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.

  • Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):

    myDirectory/
        A.m
        B.m
        C.m
        private/
            D.m
            E.m
            F.m
    

All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

python: How do I know what type of exception occurred?

These answers are fine for debugging, but for programmatically testing the exception, isinstance(e, SomeException) can be handy, as it tests for subclasses of SomeException too, so you can create functionality that applies to hierarchies of exceptions.

Which method performs better: .Any() vs .Count() > 0?

EDIT: it was fixed in EF version 6.1.1. and this answer is no more actual

For SQL Server and EF4-6, Count() performs about two times faster than Any().

When you run Table.Any(), it will generate something like(alert: don't hurt the brain trying to understand it)

SELECT 
CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [Table] AS [Extent1]
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [Table] AS [Extent2]
)) THEN cast(0 as bit) END AS [C1]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]

that requires 2 scans of rows with your condition.

I don't like to write Count() > 0 because it hides my intention. I prefer to use custom predicate for this:

public static class QueryExtensions
{
    public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
    {
        return source.Count(predicate) > 0;
    }
}

Change <select>'s option and trigger events with JavaScript

It is as simple as this:

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    sel.onchange();
});

But this way has a problem. You can't call events just like you would, with normal functions, because there may be more than one function listening for an event, and they can get set in several different ways.

Unfortunately, the 'right way' to fire an event is not so easy because you have to do it differently in Internet Explorer (using document.createEventObject) and Firefox (using document.createEvent("HTMLEvents"))

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    fireEvent(sel,'change');

});


function fireEvent(element,event){
    if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    }
    else{
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
    }
}

How to Convert JSON object to Custom C# object?

JavaScript Serializer: requires using System.Web.Script.Serialization;

public class JavaScriptSerializerDeSerializer<T>
{
    private readonly JavaScriptSerializer serializer;

    public JavaScriptSerializerDeSerializer()
    {
        this.serializer = new JavaScriptSerializer();
    }

    public string Serialize(T t)
    {
        return this.serializer.Serialize(t);
    }

    public T Deseralize(string stringObject)
    {
        return this.serializer.Deserialize<T>(stringObject);
    }
}

Data Contract Serializer: requires using System.Runtime.Serialization.Json; - The generic type T should be serializable more on Data Contract

public class JsonSerializerDeserializer<T> where T : class
{
    private readonly DataContractJsonSerializer jsonSerializer;

    public JsonSerializerDeserializer()
    {
        this.jsonSerializer = new DataContractJsonSerializer(typeof(T));
    }

    public string Serialize(T t)
    {
        using (var memoryStream = new MemoryStream())
        {
            this.jsonSerializer.WriteObject(memoryStream, t);
            memoryStream.Position = 0;
            using (var sr = new StreamReader(memoryStream))
            {
                return sr.ReadToEnd();
            }
        }
    }

    public T Deserialize(string objectString)
    {
        using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString))))
        {
            return (T)this.jsonSerializer.ReadObject(ms);
        }
    }
}

Getting the class name of an instance?

Alternatively you can use the classmethod decorator:

class A:
    @classmethod
    def get_classname(cls):
        return cls.__name__

    def use_classname(self):
        return self.get_classname()

Usage:

>>> A.get_classname()
'A'
>>> a = A()
>>> a.get_classname()
'A'
>>> a.use_classname()
'A'

Date only from TextBoxFor()

// datimetime displays in the datePicker is 11/24/2011 12:00:00 AM

// you could split this by space and set the value to date only

Script:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

Markup:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

Hopes this helps..

Disabled href tag

Anything in the href tag will display at the bottom-left of the browser window when you mouse over it.

I personally think having something like javascript:void(0) displayed to the user is hideous.

Instead, leave href off, do your magic with with jQuery/whatever else and add a style rule (if you still need it to look like a link):

a {
    cursor:pointer;
}

How to import and use image in a Vue single file component?

I encounter a problem in quasar which is a mobile framework based vue, the tidle syntax ~assets/cover.jpg works in normal component, but not in my dynamic defined component, that is defined by

let c=Vue.component('compName',{...})

finally this work:

    computed: {
      coverUri() {
        return require('../assets/cover.jpg');
      }
    }
<q-img class="coverImg" :src="coverUri" :height="uiBook.coverHeight" spinner-color="white"/>

according to the explain at https://quasar.dev/quasar-cli/handling-assets

In *.vue components, all your templates and CSS are parsed by vue-html-loader and css-loader to look for asset URLs. For example, in <img src="./logo.png"> and background: url(./logo.png), "./logo.png" is a relative asset path and will be resolved by Webpack as a module dependency.

How to tell if a <script> tag failed to load

The script from Erwinus works great, but isn't very clearly coded. I took the liberty to clean it up and decipher what it was doing. I've made these changes:

  • Meaningful variable names
  • Use of prototype.
  • require() uses an argument variable
  • No alert() messages are returned by default
  • Fixed some syntax errors and scope issues I was getting

Thanks again to Erwinus, the functionality itself is spot on.

function ScriptLoader() {
}

ScriptLoader.prototype = {

    timer: function (times, // number of times to try
                     delay, // delay per try
                     delayMore, // extra delay per try (additional to delay)
                     test, // called each try, timer stops if this returns true
                     failure, // called on failure
                     result // used internally, shouldn't be passed
            ) {
        var me = this;
        if (times == -1 || times > 0) {
            setTimeout(function () {
                result = (test()) ? 1 : 0;
                me.timer((result) ? 0 : (times > 0) ? --times : times, delay + ((delayMore) ? delayMore : 0), delayMore, test, failure, result);
            }, (result || delay < 0) ? 0.1 : delay);
        } else if (typeof failure == 'function') {
            setTimeout(failure, 1);
        }
    },

    addEvent: function (el, eventName, eventFunc) {
        if (typeof el != 'object') {
            return false;
        }

        if (el.addEventListener) {
            el.addEventListener(eventName, eventFunc, false);
            return true;
        }

        if (el.attachEvent) {
            el.attachEvent("on" + eventName, eventFunc);
            return true;
        }

        return false;
    },

    // add script to dom
    require: function (url, args) {
        var me = this;
        args = args || {};

        var scriptTag = document.createElement('script');
        var headTag = document.getElementsByTagName('head')[0];
        if (!headTag) {
            return false;
        }

        setTimeout(function () {
            var f = (typeof args.success == 'function') ? args.success : function () {
            };
            args.failure = (typeof args.failure == 'function') ? args.failure : function () {
            };
            var fail = function () {
                if (!scriptTag.__es) {
                    scriptTag.__es = true;
                    scriptTag.id = 'failed';
                    args.failure(scriptTag);
                }
            };
            scriptTag.onload = function () {
                scriptTag.id = 'loaded';
                f(scriptTag);
            };
            scriptTag.type = 'text/javascript';
            scriptTag.async = (typeof args.async == 'boolean') ? args.async : false;
            scriptTag.charset = 'utf-8';
            me.__es = false;
            me.addEvent(scriptTag, 'error', fail); // when supported
            // when error event is not supported fall back to timer
            me.timer(15, 1000, 0, function () {
                return (scriptTag.id == 'loaded');
            }, function () {
                if (scriptTag.id != 'loaded') {
                    fail();
                }
            });
            scriptTag.src = url;
            setTimeout(function () {
                try {
                    headTag.appendChild(scriptTag);
                } catch (e) {
                    fail();
                }
            }, 1);
        }, (typeof args.delay == 'number') ? args.delay : 1);
        return true;
    }
};

$(document).ready(function () {
    var loader = new ScriptLoader();
    loader.require('resources/templates.js', {
        async: true, success: function () {
            alert('loaded');
        }, failure: function () {
            alert('NOT loaded');
        }
    });
});

asp.net: Invalid postback or callback argument

You can add ViewStateMode="Disabled"

asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Disabled"

How to show uncommitted changes in Git and some Git diffs in detail

How to show uncommitted changes in Git

The command you are looking for is git diff.

git diff - Show changes between commits, commit and working tree, etc


Here are some of the options it expose which you can use

git diff (no parameters)
Print out differences between your working directory and the index.

git diff --cached:
Print out differences between the index and HEAD (current commit).

git diff HEAD:
Print out differences between your working directory and the HEAD.

git diff --name-only
Show only names of changed files.

git diff --name-status
Show only names and status of changed files.

git diff --color-words
Word by word diff instead of line by line.

Here is a sample of the output for git diff --color-words:

enter image description here


enter image description here

How do you reverse a string in place in C or C++?

void reverseString(vector<char>& s) {
        int l = s.size();
        char ch ;
        int i = 0 ;
        int j = l-1;
        while(i < j){
                s[i] = s[i]^s[j];
                s[j] = s[i]^s[j];
                s[i] = s[i]^s[j];
                i++;
                j--;
        }
        for(char c : s)
                cout <<c ;
        cout<< endl;
}

REST HTTP status codes for failed validation or invalid duplicate

A duplicate in the database should be a 409 CONFLICT.

I recommend using 422 UNPROCESSABLE ENTITY for validation errors.

I give a longer explanation of 4xx codes here.

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

What's the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):

  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not pending anymore):

  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) When x is a Promise that is pending:

  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Read more on this topic on the Promise.prototype.then() docs.

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

proper way to sudo over ssh

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

Replacing blank values (white space) with NaN in pandas

I will did this:

df = df.apply(lambda x: x.str.strip()).replace('', np.nan)

or

df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)

You can strip all str, then replace empty str with np.nan.

New to unit testing, how to write great tests?

My tests just seems so tightly bound to the method (testing all codepath, expecting some inner methods to be called a number of times, with certain arguments), that it seems that if I ever refactor the method, the tests will fail even if the final behavior of the method did not change.

I think you are doing it wrong.

A unit test should:

  • test one method
  • provide some specific arguments to that method
  • test that the result is as expected

It should not look inside the method to see what it is doing, so changing the internals should not cause the test to fail. You should not directly test that private methods are being called. If you are interested in finding out whether your private code is being tested then use a code coverage tool. But don't get obsessed by this: 100% coverage is not a requirement.

If your method calls public methods in other classes, and these calls are guaranteed by your interface, then you can test that these calls are being made by using a mocking framework.

You should not use the method itself (or any of the internal code it uses) to generate the expected result dynamically. The expected result should be hard-coded into your test case so that it does not change when the implementation changes. Here's a simplified example of what a unit test should do:

testAdd()
{
    int x = 5;
    int y = -2;
    int expectedResult = 3;
    Calculator calculator = new Calculator();
    int actualResult = calculator.Add(x, y);
    Assert.AreEqual(expectedResult, actualResult);
}

Note that how the result is calculated is not checked - only that the result is correct. Keep adding more and more simple test cases like the above until you have have covered as many scenarios as possible. Use your code coverage tool to see if you have missed any interesting paths.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had that problem. And I found this solve. In Android Studio, Open File menu, and go to Project Structure, In Module app, go to dependencies tab and you can add 'com.google.android.gms:play-services:x.x.x' by clicking on + button.

Create patch or diff file from git repository and apply it to another different git repository

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

Running a cron job on Linux every six hours

You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.

It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.

No module named MySQLdb

for window :

pip install mysqlclient pymysql

then:

import pymysql pymysql.install_as_MySQLdb()

for python 3 Ubuntu

sudo apt-get install -y python3-mysqldb

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

jquery multiple checkboxes array

A global function that can be reused:

function getCheckedGroupBoxes(groupName) {

    var checkedAry= [];
    $.each($("input[name='" + groupName + "']:checked"), function () {
        checkedAry.push($(this).attr("id"));
    });

     return checkedAry;

}

where the groupName is the name of the group of the checkboxes, in you example :'options[]'

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

In cases where I don't care whether the variable is undef or equal to '', I usually summarize it as:

$name = "" unless defined $name;
if($name ne '') {
  # do something with $name
}

Combine or merge JSON on node.js without jQuery

You can do it inline, without changing any variables like this:

let obj1 = { name: 'John' };
let obj2 = { surname: 'Smith' };
let obj = Object.assign({}, obj1, obj2); // { name: 'John', surname: 'Smith' }

How do browser cookie domains work?

I was surprised to read section 3.3.2 about rejecting cookies:

http://tools.ietf.org/html/rfc2965

That says that a browser should reject a cookie from x.y.z.com with domain .z.com, because 'x.y' contains a dot. So, unless I am misinterpreting the RFC and/or the questions above, there could be questions added:

Will a cookie for .example.com be available for www.yyy.example.com? No.

Will a cookie set by origin server www.yyy.example.com, with domain .example.com, have it's value sent by the user agent to xxx.example.com? No.

jQuery autoComplete view all on click?

 $j(".auto_complete").focus(function() { $j(this).keydown(); })

How do I evenly add space between a label and the input field regardless of length of text?

2019 answer:

Some time has passed and I changed my approach now when building forms. I've done thousands of them till today and got really tired of typing id for every label/input pair, so this was flushed down the toilet. When you dive input right into the label, things work the same way, no ids necessary. I also took advantage of flexbox being, well, very flexible.

HTML:

<label>
  Short label <input type="text" name="dummy1" />
</label>

<label>
  Somehow longer label <input type="text" name="dummy2" />
</label>

<label>
  Very long label for testing purposes <input type="text" name="dummy3" />
</label>

CSS:

label {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  text-align: right;
  width: 400px;
  line-height: 26px;
  margin-bottom: 10px;
}

input {
  height: 20px;
  flex: 0 0 200px;
  margin-left: 10px;
}

Fiddle DEMO


Original answer:

Use label instead of span. It's meant to be paired with inputs and preserves some additional functionality (clicking label focuses the input).

This might be exactly what you want:

HTML:

<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">

<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">

<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">

CSS:

label {
    width:180px;
    clear:left;
    text-align:right;
    padding-right:10px;
}

input, label {
    float:left;
}

jsfiddle DEMO here.

How to set UITextField height?

  1. Choose the border style as not rounded

enter image description here

  1. Set your height

enter image description here

in your viewWillAppear set the corners as round

yourUITextField.borderStyle = UITextBorderStyleRoundedRect;

enter image description here

  1. Enjoy your round and tall UITextField

iPad/iPhone hover problem causes the user to double click a link

This works for me when you have jquery ui dropdown

if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
      $('.ui-autocomplete').off('menufocus hover mouseover');
}

Why do you have to link the math library in C?

All libraries like stdio.h and stdlib.h have their implementation in libc.so or libc.a and get linked by the linker by default. The libraries for libc.so are automatically linked while compiling and is included in the executable file.
But math.h has its implementations in libm.so or libm.a which is seperate from libc.so and it does not get linked by default and you have to manually link it while compiling your program in gcc by using -lm flag.

The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.

Here read the item no 14.3, you could read it all if you wish: Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage: using the library

Why em instead of px?

Pixel is an absolute unit whereas rem/em are relative units. For more: https://drafts.csswg.org/css-values-3/

You should use the relative unit when you want the font-size to be adaptive according to the system's font size because the system provides the font-size value to the root element which is the HTML element.

In this case, where the webpage is open in google chrome, the font-size to the HTML element is set by chrome, try changing it to see the effect on webpages with fonts of rem/ em units.

enter image description here

If you use px as the unit for fonts, the fonts will not resize whereas the fonts with rem/ em unit will resize when you change the system's font size.

So use px when you want the size to be fixed and use rem/ em when you want the size to be adaptive/ dynamic to the size of the system.

How do ACID and database transactions work?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.

  • Atomicity :
  • Consistency
  • Isolation
  • Durability

NPM clean modules

For windows environment:

"scripts": {
    "clean": "rmdir /s /q node_modules",
    ...
}

Multiple ping script in Python

Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(200, 240):
                ip="10.2.7.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

Just change the ip= for your scheme and the xrange for the hosts.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I had this problem when I wanted to make a vnc connection via a tunnel. But the vncserver was not running. I solved it by opening the channel on the remote machine with vncserver :3.

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You need to give the user table an alias the second time you join to it

e.g.

SELECT article . * , section.title, category.title, user.name, u2.name 
FROM article 
INNER JOIN section ON article.section_id = section.id 
INNER JOIN category ON article.category_id = category.id 
INNER JOIN user ON article.author_id = user.id 
LEFT JOIN user u2 ON article.modified_by = u2.id 
WHERE article.id = '1'