Programs & Examples On #Web technologies

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

CSS to hide INPUT BUTTON value text

I had this noted from somewhere:

adding text-transform to input to remove it

input.button {
    text-indent:-9999px;
    text-transform:capitalize;
}

What is the Java equivalent of PHP var_dump?

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

What is and how to fix System.TypeInitializationException error?

i. Please check the InnerException property of the TypeInitializationException

ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly

How do you implement a good profanity filter?

Regarding your "trick the system" subquestion, you can handle that by normalizing both the "bad word" list and the user-entered text before doing your search. e.g., Use a series of regexes (or tr if PHP has it) to convert [z$5] to "s", [4@] to "a", etc., then compare the normalized "bad word" list against the normalized text. Note that the normalization could potentially lead to additional false positives, although I can't think of any actual cases at the moment.

The larger challenge is to come up with something that will let people quote "The pen is mightier than the sword" while blocking "p e n i s".

Good tutorial for using HTML5 History API (Pushstate?)

I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.html and history demo - http://diveintohtml5.info/examples/history/fer.html

PHP DOMDocument loadHTML not encoding UTF-8 correctly

This took me a while to figure out but here's my answer.

Before using DomDocument I would use file_get_contents to retrieve urls and then process them with string functions. Perhaps not the best way but quick. After being convinced Dom was just as quick I first tried the following:

$dom = new DomDocument('1.0', 'UTF-8');
if ($dom->loadHTMLFile($url) == false) { // read the url
    // error message
}
else {
    // process
}

This failed spectacularly in preserving UTF-8 encoding despite the proper meta tags, php settings and all the rest of the remedies offered here and elsewhere. Here's what works:

$dom = new DomDocument('1.0', 'UTF-8');
$str = file_get_contents($url);
if ($dom->loadHTML(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8')) == false) {
}

etc. Now everything's right with the world. Hope this helps.

Unit Testing: DateTime.Now

I ran into this same issue but found a research project from Microsoft that solves this issue.

http://research.microsoft.com/en-us/projects/moles/

Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates. Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types

// Let's detour DateTime.Now
MDateTime.NowGet = () => new DateTime(2000,1, 1);

if (DateTime.Now == new DateTime(2000, 1, 1);
{
    throw new Exception("Wahoo we did it!");
}

The sample code was modified from the original.

I had done what other suggested and abstracted the DateTime into a provider. It just felt wrong and I felt like it was too much just for testing. I'm going to implement this into my personal project this evening.

How should I log while using multiprocessing in Python?

The only way to deal with this non-intrusively is to:

  1. Spawn each worker process such that its log goes to a different file descriptor (to disk or to pipe.) Ideally, all log entries should be timestamped.
  2. Your controller process can then do one of the following:
    • If using disk files: Coalesce the log files at the end of the run, sorted by timestamp
    • If using pipes (recommended): Coalesce log entries on-the-fly from all pipes, into a central log file. (E.g., Periodically select from the pipes' file descriptors, perform merge-sort on the available log entries, and flush to centralized log. Repeat.)

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Here's what I did (the object returns the unit of time along with its value):

_x000D_
_x000D_
function timeSince(post_date, reference)_x000D_
{_x000D_
 var reference = reference ? new Date(reference) : new Date(),_x000D_
  diff = reference - new Date(post_date + ' GMT-0000'),_x000D_
  date = new Date(diff),_x000D_
  object = { unit: null, value: null };_x000D_
 _x000D_
 if (diff < 86400000)_x000D_
 {_x000D_
  var secs  = date.getSeconds(),_x000D_
   mins  = date.getMinutes(),_x000D_
   hours = date.getHours(),_x000D_
   array = [ ['second', secs], ['minute', mins], ['hour', hours] ];_x000D_
 }_x000D_
 else_x000D_
 {_x000D_
  var days   = date.getDate(),_x000D_
   weeks  = Math.floor(days / 7),_x000D_
   months = date.getMonth(),_x000D_
   years  = date.getFullYear() - 1970,_x000D_
   array  = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ];_x000D_
 }_x000D_
_x000D_
 for (var i = 0; i < array.length; i++)_x000D_
 {_x000D_
  array[i][0] += array[i][1] != 1 ? 's' : '';_x000D_
_x000D_
  object.unit  = array[i][1] >= 1 ? array[i][0] : object.unit;_x000D_
  object.value = array[i][1] >= 1 ? array[i][1] : object.value;_x000D_
 }_x000D_
_x000D_
 return object;_x000D_
}
_x000D_
_x000D_
_x000D_

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

You are getting the error because you might not have run the command npm install first.

i.e. First, run npm install and then npm run dev

Trim string in JavaScript?

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Added natively in: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:

Firefox: 3.5+

Safari: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/

Maven – Always download sources and javadocs

Not sure, but you should be able to do something by setting a default active profile in your settings.xml

See

See http://maven.apache.org/guides/introduction/introduction-to-profiles.html

ValueError : I/O operation on closed file

Same error can raise by mixing: tabs + spaces.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

tmux set -g mouse-mode on doesn't work

You can still using the devil logic of setting options depending on your current Tmux version: see my previous answer.

But since Tmux v1.7, set-option adds "-q" to silence errors and not print out anything (see changelog). I recommend to use this feature, it's more readable and easily expandable.

Add this to your ~/.tmux.conf:

# from v2.1
set -gq mouse on
# before v2.1
set -gq mode-mouse on
set -gq mouse-resize-pane on
set -gq mouse-select-pane on
set -gq mouse-select-window on

Restar tmux or source-file your new .tmux.conf


Side note: I'm open to remove my old answer if people prefer this one

How to update large table with millions of rows in SQL Server?

WHILE EXISTS (SELECT * FROM TableName WHERE Value <> 'abc1' AND Parameter1 = 'abc' AND Parameter2 = 123)
BEGIN
UPDATE TOP (1000) TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 AND Value <> 'abc1'
END

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

Find object in list that has attribute equal to some value (that meets any condition)

Since it has not been mentioned just for completion. The good ol' filter to filter your to be filtered elements.

Functional programming ftw.

####### Set Up #######
class X:

    def __init__(self, val):
        self.val = val

elem = 5

my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]

####### Set Up #######

### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on

print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)

### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
#   File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
#     print(next(my_filter_iter).value)
# StopIteration


# You can do that None stuff or whatever at this point, if you don't like exceptions.

I know that generally in python list comprehensions are preferred or at least that is what I read, but I don't see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.

So there you go. Know thy functional programming.

filter condition list

It won't get any easier than this:

next(filter(lambda x: x.val == value,  my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions

How to target the href to div

From what I know this will not be possible only with css. Heres a solution how you could make it work with jQuery which is a javascript Library. More about jquery here: http://jquery.com/

Here is a working example : http://jsfiddle.net/uyDbL/

$(document).ready(function(){
    $('a').on('click',function(){
        var aID = $(this).attr('href');
        var elem = $(''+aID).html();

        $('.target').html(elem);
    });
});

Update 2018 (as this still gets upvoted) here is a plain javascript solution without jQuery

_x000D_
_x000D_
var target = document.querySelector('.target');_x000D_
[...document.querySelectorAll('table a')].forEach(function(element){_x000D_
    element.addEventListener('click', function(){_x000D_
        target.innerHTML = document.querySelector(element.getAttribute('href')).innerHTML;_x000D_
    });_x000D_
});
_x000D_
a{_x000D_
    text-decoration:none;_x000D_
    color:black;_x000D_
}_x000D_
_x000D_
.target{_x000D_
    width:50%;_x000D_
    height:200px;_x000D_
    border:solid black 1px; _x000D_
}_x000D_
_x000D_
#m1, #m2, #m3, #m4, #m5, #m6, #m7, #m8, #m9{_x000D_
    display:none;_x000D_
}
_x000D_
<table border="0">_x000D_
<tr>_x000D_
<td>_x000D_
<hr>_x000D_
<a href="#m1">fea1</a><br><hr>_x000D_
<a href="#m2">fea2</a><br><hr>_x000D_
<a href="#m3">fea3</a><br><hr>_x000D_
<a href="#m4">fea4</a><br><hr>_x000D_
<a href="#m5">fea5</a><br><hr>_x000D_
<a href="#m6">fea6</a><br><hr>_x000D_
<a href="#m7">fea7</a><br><hr>_x000D_
<a href="#m8">fea8</a><br><hr>_x000D_
<a href="#m9">fea9</a>_x000D_
<hr>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
_x000D_
<div class="target">_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
<div id="m1">dasdasdasd</div>_x000D_
<div id="m2">dadasdasdasd</div>_x000D_
<div id="m3">sdasdasds</div>_x000D_
<div id="m4">dasdasdsad</div>_x000D_
<div id="m5">dasdasd</div>_x000D_
<div id="m6">asdasdad</div>_x000D_
<div id="m7">asdasda</div>_x000D_
<div id="m8">dasdasd</div>_x000D_
<div id="m9">dasdasdsgaswa</div>
_x000D_
_x000D_
_x000D_

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

How to get the caller class in Java

I know this is an old question but I believed the asker wanted the class, not the class name. I wrote a little method that will get the actual class. It is sort of cheaty and may not always work, but sometimes when you need the actual class, you will have to use this method...

/**
     * Get the caller class.
     * @param level The level of the caller class.
     *              For example: If you are calling this class inside a method and you want to get the caller class of that method,
     *                           you would use level 2. If you want the caller of that class, you would use level 3.
     *
     *              Usually level 2 is the one you want.
     * @return The caller class.
     * @throws ClassNotFoundException We failed to find the caller class.
     */
    public static Class getCallerClass(int level) throws ClassNotFoundException {
        StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
        String rawFQN = stElements[level+1].toString().split("\\(")[0];
        return Class.forName(rawFQN.substring(0, rawFQN.lastIndexOf('.')));
    }

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

Should I use != or <> for not equal in T-SQL?

They are both accepted in T-SQL. However, it seems that using <> works a lot faster than !=. I just ran a complex query that was using !=, and it took about 16 seconds on average to run. I changed those to <> and the query now takes about 4 seconds on average to run. That's a huge improvement!

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS

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

I think the following helper method could also solve the problem.

private TResult InvokeAsyncFuncSynchronously<TResult>(Func< Task<TResult>> func)
    {
        TResult result = default(TResult);
        var autoResetEvent = new AutoResetEvent(false);

        Task.Run(async () =>
        {
            try
            {
                result = await func();
            }
            catch (Exception exc)
            {
                mErrorLogger.LogError(exc.ToString());
            }
            finally
            {
                autoResetEvent.Set();
            }
        });
        autoResetEvent.WaitOne();

        return result;
    }

Can be used the following way:

InvokeAsyncFuncSynchronously(Service.GetCustomersAsync);

Add JVM options in Tomcat

As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc.

#   JAVA_OPTS       (Optional) Java runtime options used when any command
#                   is executed.
#                   Include here and not in CATALINA_OPTS all options, that
#                   should be used by Tomcat and also by the stop process,
#                   the version command etc.
#                   Most options should go into CATALINA_OPTS.

The name 'model' does not exist in current context in MVC3

I ran into this problem when I inadvertently had a copy of the view file (About.cshtml) for the route /about in the root directory. (Not the views folder) Once I moved the file out of the root, the problem went away.

Cause of No suitable driver found for

Not sure if it's worth anything, but I had a similar problem where I was getting a "java.sql.SQLException: No suitable driver found" error. I found this thread while researching a solution.

The way I ended up solving my problem was to forgo using java.sql.DriverManager to get a connection and instead built up an instance of org.hsqldb.jdbc.jdbcDataSource and used that.

The root cause of my problem (I believe) had to do with the classloader hierarchy and the fact that the JRE was running Java 5. Even though I could successfully load the jdbcDriver class, the classloader behind java.sql.DriverManager was higher up, to the point that it couldn't see the hsqldb.jar I needed.

Anyway, just putting this note here in case someone else stumbles by with a similar problem.

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

Style input type file?

After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.

The important parts for me was:

  • The Browse button had to be a Button (not an image).
  • The button had to have a hover effect (to make it look nice).
  • The Width of both the Text and the button had to be easy to adjust.
  • The solution had to work in IE8, FF, Chrome and Safari.

This is the solution i came up with. And hope it can be of use to others as well.

Change the width of .file_input_textbox to change the width of the textbox.

Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...

To test this solution, make a new html file and paste the content into it.

<html>
<head>

<style type="text/css">

.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div     {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button  {width: 80px;position:absolute;top:0px;
                     border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
                     border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden  {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
                     opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
    <input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
 <div class="file_input_div">
  <input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
  <input type="file" class="file_input_hidden" 
      onchange="javascript: document.getElementById('fileName').value = this.value" 
      onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
      onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>

How to index an element of a list object in R

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

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

Dataframes

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

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

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

Table objects

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

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

Now with the list

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

1  2  3  4  5 
9 11 12  9  9 

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

1  2 
9 11 

How do I output lists as a table in Jupyter notebook?

I want to output a table where each column has the smallest possible width, where columns are padded with white space (but this can be changed) and rows are separated by newlines (but this can be changed) and where each item is formatted using str (but...).


def ftable(tbl, pad='  ', sep='\n', normalize=str):

    # normalize the content to the most useful data type
    strtbl = [[normalize(it) for it in row] for row in tbl] 

    # next, for each column we compute the maximum width needed
    w = [0 for _ in tbl[0]]
    for row in strtbl:
        for ncol, it in enumerate(row):
            w[ncol] = max(w[ncol], len(it))

    # a string is built iterating on the rows and the items of `strtbl`:
    #   items are  prepended white space to an uniform column width
    #   formatted items are `join`ed using `pad` (by default "  ")
    #   eventually we join the rows using newlines and return
    return sep.join(pad.join(' '*(wid-len(it))+it for wid, it in zip(w, row))
                                                      for row in strtbl)

The function signature, ftable(tbl, pad=' ', sep='\n', normalize=str), with its default arguments is intended to provide for maximum flexibility.

You can customize

  • the column padding,
  • the row separator, (e.g., pad='&', sep='\\\\\n' to have the bulk of a LaTeX table)
  • the function to be used to normalize the input to a common string format --- by default, for the maximum generality it is str but if you know that all your data is floating point lambda item: "%.4f"%item could be a reasonable choice, etc.

Superficial testing:

I need some test data, possibly involving columns of different width so that the algorithm needs to be a little more sophisticated (but just a little bit;)

In [1]: from random import randrange

In [2]: table = [[randrange(10**randrange(10)) for i in range(5)] for j in range(3)]

In [3]: table
Out[3]: 
[[974413992, 510, 0, 3114, 1],
 [863242961, 0, 94924, 782, 34],
 [1060993, 62, 26076, 75832, 833174]]

In [4]: print(ftable(table))
974413992  510      0   3114       1
863242961    0  94924    782      34
  1060993   62  26076  75832  833174

In [5]: print(ftable(table, pad='|'))
974413992|510|    0| 3114|     1
863242961|  0|94924|  782|    34
  1060993| 62|26076|75832|833174

Convert string to List<string> in one line?

Split a string delimited by characters and return all non-empty elements.

var names = ",Brian,Joe,Chris,,,";
var charSeparator = ",";
var result = names.Split(charSeparator, StringSplitOptions.RemoveEmptyEntries);

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

updating table rows in postgres using subquery

There are many ways to update the rows.

When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

  1. Approach-1 [Using direct table reference]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2>
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

  1. Approach-2 [Using SubQueries]
UPDATE
  <table1>
SET
  customer=subquery.customer,
  address=subquery.address,
  partn=subquery.partn
FROM
  (
    SELECT
      address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
  ) AS subquery
WHERE
  dummy.address_id=subquery.address_id;

Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

  1. Approach-3 [Using multiple Joined tables]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2> as t2
  JOIN <table3> as t3
  ON
    t2.id = t3.id
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

  1. Approach-4 [Using WITH statement]

    • 4.1 [Using simple query]
WITH subquery AS (
    SELECT
      address_id,
      customer,
      address,
      partn
    FROM
      <table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
  • 4.2 [Using query with complex JOIN]
WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM
      <table1> as t1
    JOIN
      <table2> as t2
    ON
      t1.id = t2.id;
    -- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;

Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

I hope, this would be helpful.

How do I register a DLL file on Windows 7 64-bit?

I just tested this extremely simple method and it works perfectly--but I use the built-in Administrator account, so I don't have to jump through hoops for elevated privileges.

The following batch file relieves the user of the need to move files in/out of system folders. It also leaves it up to Windows to apply the proper version of Regsvr32.

INSTRUCTIONS:

  • In the folder that contains the library (-.dll or -.ax) file you wish to register, open a new text file and paste in ONE of the routines below :

    echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 64-BIT SYSTEMS
    copy %1 C:\Windows\System32
    regsvr32 "%nx1"
    echo END BATCH FILE
    pause
    

    echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 32-BIT SYSTEMS
    copy %1 C:\Windows\SysWOW64
    regsvr32 "%nx1"
    echo END BATCH FILE
    pause
    
  • Save your new text file as a batch (-.bat) file; then simply drag-and-drop your -.dll or -.ax file on top of the batch file.

  • If UAC doesn't give you the opportunity to run the batch file as an Administrator, you may need to manually elevate privileges (instructions are for Windows 7):

    1. Right-click on the batch file;
    2. Select Create shortcut;
    3. Right-click on the shortcut;
    4. Select Properties;
    5. Click the Compatibility tab;
    6. Check the box labeled Run this program as administrator;
    7. Drag-and-drop your -.dll or -.ax file on top of the new shortcut instead of the batch file.

That's it. I chose COPY instead of MOVE to prevent the failure of any UAC-related follow-up attempt(s). Successful registration should be followed by deletion of the original library (-.dll or -.ax) file.

Don't worry about copies made to the system folder (C:\Windows\System32 or C:\Windows\SysWOW64) by previous passes--they will be overwritten every time you run the batch file.

Unless you ran the wrong batch file, in which case you will probably want to delete the copy made to the wrong system folder (C:\Windows\System32 or C:\Windows\SysWOW64) before running the proper batch file, ...or...

  • Help Windows choose the right library file to register by fully-qualifying its directory location.

    1. From the right batch file copy the system folder path
      • If 64-bit: C:\Windows\System32
      • If 32-bit: C:\Windows\SysWOW64
    2. Paste it on the next line so that it precedes %nx1
      • If 64-bit: regsvr32 "C:\Windows\System32\%nx1"
      • If 32-bit: regsvr32 "C:\Windows\SysWOW64\%nx1"
        • Paste path inside quotation marks
        • Insert backslash to separate %nx1 from system folder path
      • or ...

  • Run this shotgun batch file, which will (in order):

    1. Perform cleanup of aborted registration processes
      • Reverse any registration process completed by your library file;
      • Delete any copies of your library file that have been saved to either system folder;
      • Pause to allow you to terminate the batch file at this point (and run another if you would like).
    2. Attempt 64-Bit Installation on your library file
      • Copy your library file to C:\Windows\System32;
      • Register your library file as a 64-bit process;
      • Pause to allow you to terminate the batch file at this point.
    3. Undo 64-Bit Installation
      • Reverse any registration of your library file as a 64-bit process;
      • Delete your library file from C:\Windows\System32;
      • Pause to allow you to terminate the batch file at this point (and run another if you would like).
    4. Attempt 32-Bit Installation on your library file
      • Copy your library file to C:\Windows\SystemWOW64
      • Register your library file as a 32-bit process;
      • Pause to allow you to terminate the batch file at this point.
    5. Delete original, unregistered copy of library file

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

CREATE OR REPLACE FUNCTION cols(
    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  RETURN VARCHAR2
IS
  v_string VARCHAR2(4000);
BEGIN
  SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
  ORDER BY ROWNUM )
  INTO v_string
  FROM ALL_TAB_COLUMNS
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;
END;
/

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

MSBUILD : error MSB1008: Only one project can be specified

This worked for me in TFS MSBuild Argument. Note the number of slashes.

/p:DefaultPackageOutputDir="\\Rdevnet\Visual Studio Projects\Insurance\"

How do I implement basic "Long Polling"?

For a ASP.NET MVC implementation, look at SignalR which is available on NuGet.. note that the NuGet is often out of date from the Git source which gets very frequent commits.

Read more about SignalR on a blog on by Scott Hanselman

Cannot change version of project facet Dynamic Web Module to 3.0?

Delete

.settings 
.classpatch 
.projejct 
target

and import again the maven project.

Use a normal link to submit a form

use:

<input type="image" src=".."/>

or:

<button type="send"><img src=".."/> + any html code</button>

plus some CSS

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

What's the difference between a word and byte?

In fact, in common usage, word has become synonymous with 16 bits, much like byte has with 8 bits. Can get a little confusing since the "word size" on a 32-bit CPU is 32-bits, but when talking about a word of data, one would mean 16-bits. Microcontrollers with a 32-bit word size have taken to calling their instructions "longs" (supposedly to try and avoid the word/doubleword confusion).

Converting String To Float in C#

First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).

Note: Use always CultureInfo information when dealing with floating point numbers versus strings.

float.Parse("41.00027357629127",
      System.Globalization.CultureInfo.InvariantCulture);

This is just an example; choose an appropriate culture for your case.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Powershell: count members of a AD group

Try:

$group = Get-ADGroup -Identity your-group-name -Properties *

$group.members | count

This worked for me for a group with over 17000 members.

Moq, SetupGet, Mocking a property

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

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

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

which is causing the exception.

Change it to return whole list:

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

How to use git merge --squash?

git checkout YOUR_RELEASE_BRANCH
git pull
git checkout -b A_NEW_BRANCH
git merge --squash YOUR_BRANCH_WITH_MULTIPLE_COMMITS
git commit -am "squashing all commits into one"
git push --set-upstream origin A_NEW_BRANCH

VBA: Conditional - Is Nothing

Based on your comment to Issun:

Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>

You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.

I did test several common objects and found that an instantiated Collection with no items added shows <No Variables> in the watch window. If your object is indeed a collection, you can check for the <No Variables> condition using the .Count property:

Sub TestObj()
Dim Obj As Object
    Set Obj = New Collection
    If Obj Is Nothing Then
        Debug.Print "Object not instantiated"
    Else
        If Obj.Count = 0 Then
            Debug.Print "<No Variables> (ie, no items added to the collection)"
        Else
            Debug.Print "Object instantiated and at least one item added"
        End If
    End If
End Sub

It is also worth noting that if you declare any object As New then the Is Nothing check becomes useless. The reason is that when you declare an object As New then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!

Dim MyObject As New Collection
If MyObject Is Nothing Then  ' <--- This check always returns False

This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.

C# DataRow Empty-check

Maybe a better solution would be to add an extra column that is automatically set to 1 on each row. As soon as there is an element that is not null change it to a 0.

then

If(drEntitity.rows[i].coulmn[8] = 1)
{
   dtEntity.Rows.Add(drEntity);
}
 else
 {
   //don't add, will create a new one (drEntity = dtEntity.NewRow();)
 }

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Difference between partition key, composite key and clustering key in Cassandra?

Worth to note, you will probably use those lots more than in similar concepts in relational world (composite keys).

Example - suppose you have to find last N users who recently joined user group X. How would you do this efficiently given reads are predominant in this case? Like that (from offical Cassandra guide):

CREATE TABLE group_join_dates (
    groupname text,
    joined timeuuid,
    join_date text,
    username text,
    email text,
    age int,
    PRIMARY KEY ((groupname, join_date), joined)
) WITH CLUSTERING ORDER BY (joined DESC)

Here, partitioning key is compound itself and the clustering key is a joined date. The reason why a clustering key is a join date is that results are already sorted (and stored, which makes lookups fast). But why do we use a compound key for partitioning key? Because we always want to read as few partitions as possible. How putting join_date in there helps? Now users from the same group and the same join date will reside in a single partition! This means we will always read as few partitions as possible (first start with the newest, then move to older and so on, rather than jumping between them).

In fact, in extreme cases you would also need to use the hash of a join_date rather than a join_date alone - so that if you query for last 3 days often those share the same hash and therefore are available from same partition!

Disabling contextual LOB creation as createClob() method threw error

For anyone who is facing this problem with Spring Boot 2

by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml

<hibernate.version>5.4.2.Final</hibernate.version>

and error was gone. Reason for error is already explained in posts above

ElasticSearch - Return Unique Values

I am looking for this kind of solution for my self as well. I found reference in terms aggregation.

So, according to that following is the proper solution.

{
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  
                    "size" : 500 }
    }
}}

But if you ran into following error:

"error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
            }
        ]}

In that case, you have to add "KEYWORD" in the request, like following:

   {
    "aggs" : {
        "langs" : {
            "terms" : { "field" : "language.keyword",  
                        "size" : 500 }
        }
    }}

How to convert Seconds to HH:MM:SS using T-SQL

Using SQL Server 2008

declare @Seconds as int = 3600;
SELECT CONVERT(time(0), DATEADD(SECOND, @Seconds, 0)) as 'hh:mm:ss'

Reset Entity-Framework Migrations

In EF6

  1. Delete all your files in 'migrations' folder... But not the 'initial create' or 'config'.
  2. Delete the database.
  3. Now run Add-Migration Initial.
  4. Now you can 'update-database' and all will be well.

C++ JSON Serialization

This is my attempt using Qt: https://github.com/carlonluca/lqobjectserializer. A JSON like this:

{"menu": {
    "header": "SVG Viewer",
    "items": [
        {"id": "Open"},
        {"id": "OpenNew", "label": "Open New"},
        null,
        {"id": "ZoomIn", "label": "Zoom In"},
        {"id": "ZoomOut", "label": "Zoom Out"},
        {"id": "OriginalView", "label": "Original View"},
        null,
        {"id": "Quality"},
        {"id": "Pause"},
        {"id": "Mute"},
        null,
        {"id": "Find", "label": "Find..."},
        {"id": "FindAgain", "label": "Find Again"},
        {"id": "Copy"},
        {"id": "CopyAgain", "label": "Copy Again"},
        {"id": "CopySVG", "label": "Copy SVG"},
        {"id": "ViewSVG", "label": "View SVG"},
        {"id": "ViewSource", "label": "View Source"},
        {"id": "SaveAs", "label": "Save As"},
        null,
        {"id": "Help"},
        {"id": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}

can be deserialized by declaring classes like these:

L_BEGIN_CLASS(Item)
L_RW_PROP(QString, id, setId, QString())
L_RW_PROP(QString, label, setLabel, QString())
L_END_CLASS

L_BEGIN_CLASS(Menu)
L_RW_PROP(QString, header, setHeader)
L_RW_PROP_ARRAY_WITH_ADDER(Item*, items, setItems)
L_END_CLASS

L_BEGIN_CLASS(MenuRoot)
L_RW_PROP(Menu*, menu, setMenu, nullptr)
L_END_CLASS

and writing writing:

LDeserializer<MenuRoot> deserializer;
QScopedPointer<MenuRoot> g(deserializer.deserialize(jsonString));

You also need to inject mappings for meta objects once:

QHash<QString, QMetaObject> factory {
    { QSL("Item*"), Item::staticMetaObject },
    { QSL("Menu*"), Menu::staticMetaObject }
};

I'm looking for a way to avoid this.

What is the correct way to do a CSS Wrapper?

The best way to do it depends on your specific use-case.

However, if we speak for the general best practices for implementing a CSS Wrapper, here is my proposal: introduce an additional <div> element with the following class:

/**
 * 1. Center the content. Yes, that's a bit opinionated.
 * 2. Use `max-width` instead `width`
 * 3. Add padding on the sides.
 */
.wrapper {
    margin-right: auto; /* 1 */
    margin-left:  auto; /* 1 */

    max-width: 960px; /* 2 */

    padding-right: 10px; /* 3 */
    padding-left:  10px; /* 3 */
}

... for those of you, who want to understand why, here are the 4 big reasons I see:

1. Use max-width instead width

In the answer currently accepted Aron says width. I disagree and I propose max-width instead.

Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Therefore, the Wrapper element will take up the specified width. The problem occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices. Here’s a good example showcasing the problem:

_x000D_
_x000D_
/**_x000D_
 * The problem with this one occurs_x000D_
 * when the browser window is smaller than 960px._x000D_
 * The browser then adds a horizontal scrollbar to the page._x000D_
 */_x000D_
.width {_x000D_
    width: 960px;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    border: 3px solid #73AD21;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Using max-width instead, in this situation,_x000D_
 * will improve the browser's handling of small windows._x000D_
 * This is important when making a site usable on small devices._x000D_
 */_x000D_
.max-width {_x000D_
    max-width: 960px;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    border: 3px solid #73AD21;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Credits for the tip: W3Schools_x000D_
 * https://www.w3schools.com/css/css_max-width.asp_x000D_
 */
_x000D_
<div class="width">This div element has width: 960px;</div>_x000D_
<br />_x000D_
_x000D_
<div class="max-width">This div element has max-width: 960px;</div>
_x000D_
_x000D_
_x000D_

So in terms of Responsiveness, is seems like max-width is the better choice!-


2. Add Padding on the Sides

I’ve seen a lot of developers still forget one edge case. Let’s say we have a Wrapper with max-width set to 980px. The edge case appears when the user’s device screen width is exactly 980px. The content then will exactly glue to the edges of the screen with not any breathing space left.

Generally, we’d want to have a bit of padding on the sides. That’s why if I need to implement a Wrapper with a total width of 980px, I’d do it like so:

.wrapper {
   max-width: 960px; /** 20px smaller, to fit the paddings on the sides */

   padding-right: 10px;
   padding-left:  10px;

   /** ... omitted for brevity */
}

Therefore, that’s why adding padding-left and padding-right to your Wrapper might be a good idea, especially on mobile.


3. Use a <div> Instead of a <section>

By definition, the Wrapper has no semantic meaning. It simply holds all visual elements and content on the page. It’s just a generic container. Therefore, in terms of semantics, <div> is the best choice.

One might wonder if maybe a <section> element could fit this purpose. However, here’s what the W3C spec says:

The element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

The <section> element carries it’s own semantics. It represents a thematic grouping of content. The theme of each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

It might not seem very obvious at first sight, but yes! The plain old <div> fits best for a Wrapper!


4. Using the <body> Tag vs. Using an Additional <div>

Here's a related question. Yes, there are some instances where you could simply use the <body> element as a wrapper. However, I wouldn’t recommend you to do so, simply due to flexibility and resilience to changes.

Here's an use-case that illustrates a possible issue: Imagine if on a later stage of the project you need to enforce a footer to "stick" to the end of the document (bottom of the viewport when the document is short). Even if you can use the most modern way to do it - with Flexbox, I guess you need an additional Wrapper <div>.

I would conclude it is still best practice to have an additional <div> for implementing a CSS Wrapper. This way if spec requirements change later on you don't have to add the Wrapper later and deal with moving the styles around a lot. After all, we're only talking about 1 extra DOM element.

Javascript equivalent of php's strtotime()?

Yes, it is. And it is supported in all major browser:

var ts = Date.parse("date string");

The only difference is that this function returns milliseconds instead of seconds, so you need to divide the result by 1000.

Check what valid formats can JavaScript parse.

How to store Query Result in variable using mysql

use this

 SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;

tested and workes fine...

Explicitly set column value to null SQL Developer

If you want to use the GUI... click/double-click the table and select the Data tab. Click in the column value you want to set to (null). Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.

enter image description here

More info here:

How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data

Determine which MySQL configuration file is being used

For people running windows server with mysql as a service, an easy way to find out what config file you are running is to open up the services control panel, find your mysql service (in my case 'MYSQL56'), right click and click properties. Then from here you can check the "Path to Executable" which should have a defaults-file switch which points to where your config file is.

How to execute powershell commands from a batch file?

Type in cmd.exe Powershell -Help and see the examples.

Auto-loading lib files in Rails 4

This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module whose name matched my filename appropriately, rather than just defining a class:

In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))

module DevelopmentMailInterceptor
  class DevelopmentMailInterceptor
    def self.delivering_email(message)
      message.subject = "intercepted for: #{message.to} #{message.subject}"
      message.to = "[email protected]"
    end
  end
end

works, but it doesn't load if I hadn't put the class inside a module.

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Remove duplicates from a list of objects based on property in Java 8

This worked for me:

list.stream().distinct().collect(Collectors.toList());

You need to implement equals, of course

Date in to UTC format Java

java.time

It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.

    ZoneId utc = ZoneId.of("Etc/UTC");
    DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
            "MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);

    String itsAlarmDttm = "2013-10-22T01:37:56";
    ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
            .atZone(ZoneId.systemDefault())
            .withZoneSameInstant(utc);
    String formatterUtcDateTime = utcDateTime.format(targetFormatter);
    System.out.println(formatterUtcDateTime);

When running in my time zone, Europe/Copenhagen, the output is:

10/21/2013 11:37:56 PM UTC

I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").

I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.

I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.

Links

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

GIT: Checkout to a specific folder

Addition to @hasen's answer. You might want to use git ls-files instead of find to list files to checkout like:

git ls-files -z *.txt | git checkout-index --prefix=/path-to/dest/ -f -z --stdin

git ls-files ignores uncommitted files.

How to do a LIKE query with linq?

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2

Java Swing - how to show a panel on top of another panel?

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

Am I understanding this question correctly?

Downloading an entire S3 bucket?

You can use this AWS cli command to download entire S3 bucket content to local folder

aws s3 sync s3://your-bucket-name "Local Folder Path"

If you see error like this

fatal error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)

--no-verify-ssl (boolean)

By default, the AWS CLI uses SSL when communicating with AWS services. For each SSL connection, the AWS CLI will verify SSL certificates. This option overrides the default behavior of verifying SSL certificates. reference

Use this tag with command --no-verify-ssl

aws s3 sync s3://your-bucket-name "Local Folder Path" --no-verify-ssl

How to compare two NSDates: Which is more recent?

Use this simple function for date comparison

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
    isTokonValid = NO;
} else {
    isTokonValid = NO;
    NSLog(@"dates are the same");
}

return isTokonValid;}

How to find my Subversion server version number?

If you use VisualSVN Server, you can find out the version number by several different means.

Use VisualSVN Server Manager

Follow these steps to find out the version via the management console:

  1. Start the VisualSVN Server Manager console.
  2. See the Version at the bottom-right corner of the dashboard.

enter image description here

If you click Version you will also see the versions of the components.

enter image description here

Check the README.txt file

Follow these steps to find out the version from the readme.txt file:

  1. Start notepad.exe.
  2. Open the %VISUALSVN_SERVER%README.txt file. The first line shows the version number.

enter image description here

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Since we're in the PowerShell area, it's extra useful if we can return a proper PowerShell object ...

I personally like this method of parsing, for the terseness:

((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv

Note: this doesn't account for disconnected ("disc") users, but works well if you just want to get a quick list of users and don't care about the rest of the information. I just wanted a list and didn't care if they were currently disconnected.

If you do care about the rest of the data it's just a little more complex:

(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ForEach-Object {
    if ($_.Split(',').Count -eq 5) {
        Write-Output ($_ -replace '(^[^,]+)', '$1,')
    } else {
        Write-Output $_
    }
} | ConvertFrom-Csv

I take it a step farther and give you a very clean object on my blog.

I ended up making this into a module.

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

How to define a preprocessor symbol in Xcode

It's under "GCC 4.2 Preprocessing" (or just put "prepro" in the search box)...

...however, for the life of me I can't get it to work.

I have my standard Debug and Release configurations, and I want to define DEBUG=1 in the debugging configuration. But after adding it as a value:

(in the settings window) > Preprocessor Macros : DEBUG=1

#if DEBUG
    printf("DEBUG is set!");
#endif 

...never prints/gets called. It's driving me crazy...

1052: Column 'id' in field list is ambiguous

SQL supports qualifying a column by prefixing the reference with either the full table name:

SELECT tbl_names.id, tbl_section.id, name, section
  FROM tbl_names
  JOIN tbl_section ON tbl_section.id = tbl_names.id 

...or a table alias:

SELECT n.id, s.id, n.name, s.section
  FROM tbl_names n
  JOIN tbl_section s ON s.id = n.id 

The table alias is the recommended approach -- why type more than you have to?

Why Do These Queries Look Different?

Secondly, my answers use ANSI-92 JOIN syntax (yours is ANSI-89). While they perform the same, ANSI-89 syntax does not support OUTER joins (RIGHT, LEFT, FULL). ANSI-89 syntax should be considered deprecated, there are many on SO who will not vote for ANSI-89 syntax to reinforce that. For more information, see this question.

iPad WebApp Full Screen in Safari

It only opens the first (bookmarked) page full screen. Any next page will be opened WITH the address bar visible again. Whatever meta tag you put into your page header...

How to concatenate a std::string and an int?

If you have C++11, you can use std::to_string.

Example:

std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;

Output:

John21

Java Try and Catch IOException Problem

Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.

private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

Also, your countLines can be made simpler:

  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    while (reader.readLine() != null) {}
    reader.close();
    return reader.getLineNumber();
  }

Based on my test, it looks like you can getLineNumber() after close().

TypeScript enum to object array

If you are using ES8

For this case only it will work perfectly fine. It will give you value array of the given enum.

enum Colors {
  WHITE = 0,
  BLACK = 1,
  BLUE = 3
}

const colorValueArray = Object.values(Colors); //[ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]

You will get colorValueArray like this [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]. All the keys will be in first half of the array and all the values in second half.

Even this kind of enum will work fine

enum Operation {
    READ,
    WRITE,
    EXECUTE
}

But this solution will not work for Heterogeneous enums like this

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

What is the proper way to re-throw an exception in C#?

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow" and C#'s "throw ex;" gets compiled into MSIL's "throw" and C#'s "throw;" - into MSIL "rethrow"! Basically I can see the reason why "throw ex" overrides the stack trace.

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Basically <key>ITSAppUsesNonExemptEncryption</key><false/> stands for a Boolean value equal to NO.

info.plist value

Update by @JosepH: This value means that the app uses no encryption, or only exempt encryption. If your app uses encryption and is not exempt, you must set this value to YES/true.

It seems debatable sometimes when an app is considered to use encryption.

How do I embed PHP code in JavaScript?

This is the bit of code you need at the top of your JavaScript file:

<?php
    header('Content-Type: text/javascript; charset=UTF-8');
?>

(function() {
    alert("hello world");
}) ();

Use :hover to modify the css of another class?

It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).

For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.

[Edit]

With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Getting Python error "from: can't read /var/mail/Bio"

I got same error because I was trying to run on

XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass

from: can't read /var/mail/classDemo

To solve this, type command python and when you get these >>> then run any python commands

>>>from classDemo import MyClass
>>>f = MyClass()

asp.net Button OnClick event not firing

Try to Clean your solution and then try once again.

It will definitely work. Because every thing in code seems to be ok.

Go through this link for cleaning solution>

http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/

Cannot authenticate into mongo, "auth fails"

The proper way to login into mongo shell is

mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname

Class 'ViewController' has no initializers in swift

Replace var appDelegate : AppDelegate? with let appDelegate = UIApplication.sharedApplication().delegate as hinted on the second commented line in viewDidLoad().

The keyword "optional" refers exactly to the use of ?, see this for more details.

Character Limit on Instagram Usernames

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

Why I can't access remote Jupyter Notebook server?

Alternatively you can just create a tunnel to the server:

ssh -i <your_key> <user@server-instance> -L 8888:127.0.0.1:8888

Then just open 127.0.0.1:8888 in your browser.

You also omit the -i <your_key> if you don't have an identity_file.

How to configure PHP to send e-mail?

Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World! in the JavaScript alert.

You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

how to print json data in console.log

To output an object to the console, you have to stringify the object first:

success:function(data){
     console.log(JSON.stringify(data));
}

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

Best way to compare two complex objects

Serialize both objects, then calculate Hash Code, then compare.

How to pass anonymous types as parameters?

Normally, you do this with generics, for example:

MapEntToObj<T>(IQueryable<T> query) {...}

The compiler should then infer the T when you call MapEntToObj(query). Not quite sure what you want to do inside the method, so I can't tell whether this is useful... the problem is that inside MapEntToObj you still can't name the T - you can either:

  • call other generic methods with T
  • use reflection on T to do things

but other than that, it is quite hard to manipulate anonymous types - not least because they are immutable ;-p

Another trick (when extracting data) is to also pass a selector - i.e. something like:

Foo<TSource, TValue>(IEnumerable<TSource> source,
        Func<TSource,string> name) {
    foreach(TSource item in source) Console.WriteLine(name(item));
}
...
Foo(query, x=>x.Title);

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

SOAP PHP fault parsing WSDL: failed to load external entity?

try this. works for me

$options = array(
    'cache_wsdl' => 0,
    'trace' => 1,
    'stream_context' => stream_context_create(array(
          'ssl' => array(
               'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
          )
    ));

$client = new SoapClient(url, $options);

How to set minDate to current date in jQuery UI Datepicker?

can also use:

$("input.DateFrom").datepicker({
    minDate: 'today'
});

How to create streams from string in Node.Js?

From node 10.17, stream.Readable have a from method to easily create streams from any iterable (which includes array literals):

const { Readable } = require("stream")

const readable = Readable.from(["input string"])

readable.on("data", (chunk) => {
  console.log(chunk) // will be called once with `"input string"`
})

Note that at least between 10.17 and 12.3, a string is itself a iterable, so Readable.from("input string") will work, but emit one event per character. Readable.from(["input string"]) will emit one event per item in the array (in this case, one item).

Also note that in later nodes (probably 12.3, since the documentation says the function was changed then), it is no longer necessary to wrap the string in an array.

https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options

How to make borders collapse (on a div)?

Use simple negative margin rather than using display table.

Updated in fiddle JS Fiddle

.container { 
    border-style: solid;
    border-color: red;
    border-width: 1px 0 0 1px;
    display: inline-block;
}
.column { 
    float: left; overflow: hidden; 
}
.cell { 
    border: 1px solid red; width: 120px; height: 20px; 
    margin:-1px 0 0 -1px;
}
.clearfix {
    clear:both;
}

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

If you are using LAMP stack, then add this into your .htaccess file in your web root folder. No need to add it to every PHP file.

<IfModule mod_headers.c>
    Header add X-UA-Compatible "IE=Edge"
</IfModule>

Java ArrayList how to add elements at the beginning

You can use

public List<E> addToListStart(List<E> list, E obj){
list.add(0,obj);
return (List<E>)list;

}

Change E with your datatype

If deleting the oldest element is necessary then you can add:

list.remove(list.size()-1); 

before return statement. Otherwise list will add your object at beginning and also retain oldest element.

This will delete last element in list.

Android setOnClickListener method - How does it work?

It works like this. View.OnClickListenere is defined -

public interface OnClickListener {
    void onClick(View v);
}

As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:

public class MyListener implements View.OnClickListener {
    @Override
    public void onClick (View v) {
         // your code here;
    }
}

But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.

setOnClickListener takes View.OnClickListener as its parameter.

Append value to empty vector in R?

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

How to show alert message in mvc 4 controller?

I know this is not typical alert box, but I hope it may help someone.

There is this expansion that enables you to show notifications inside HTML page using bootstrap.

It is very easy to implement and it works fine. Here is a github page for the project including some demo images.

Convert java.util.date default format to Timestamp in Java

You can use

  long startTime = date.getTime() * 1000000;;
  long estimatedTime = System.nanoTime() - startTime;

To get time in nano.

Java Docs

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Can two Java methods have same name with different return types?

Only, if they accept different parameters. If there are no parameters, then you must have different names.

int doSomething(String s);
String doSomething(int); // this is fine


int doSomething(String s);
String doSomething(String s); // this is not

json_decode to array

This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.
}

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);

... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

Can I append an array to 'formdata' in javascript?

You can only stringify the array and append it. Sends the array as an actual Array even if it has only one item.

const array = [ 1, 2 ];
let formData = new FormData();
formData.append("numbers", JSON.stringify(array));

get launchable activity name of package from adb

$ adb shell pm dump PACKAGE_NAME | grep -A 1 MAIN

Why is quicksort better than mergesort?

Mu! Quicksort is not better, it is well suited for a different kind of application, than mergesort.

Mergesort is worth considering if speed is of the essence, bad worst-case performance cannot be tolerated, and extra space is available.1

You stated that they «They're both O(nlogn) […]». This is wrong. «Quicksort uses about n^2/2 comparisons in the worst case.»1.

However the most important property according to my experience is the easy implementation of sequential access you can use while sorting when using programming languages with the imperative paradigm.

1 Sedgewick, Algorithms

How to make HTML code inactive with comments

Use:

<!-- This is a comment for an HTML page and it will not display in the browser -->

For more information, I think 3 On SGML and HTML may help you.

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

if (window.frames.length != parent.frames.length) { page loaded in iframe }

But only if number of iframes differs in your page and page who are loading you in iframe. Make no iframe in your page to have 100% guarantee of result of this code

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

If you are using <ng-content> with *ngIf you are bound to fall into this loop.

Only way out I found was to change *ngIf to display:none functionality

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.

There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.

Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:

  • std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
  • std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)

How do I format a number with commas in T-SQL?

While I agree with everyone, including the OP, who says that formatting should be done in the presentation layer, this formatting can be accomplished in T-SQL by casting to money and then converting to varchar. This does include trailing decimals, though, that could be looped off with SUBSTRING.

SELECT CONVERT(varchar, CAST(987654321 AS money), 1)

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

Can media queries resize based on a div element instead of the screen?

I was also thinking of media queries, but then I found this:

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

_x000D_
_x000D_
div {_x000D_
  width: 100%;_x000D_
  padding-bottom: 75%;_x000D_
  background:gold; /** <-- For the demo **/_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

This technique can also be coupled with media queries and a bit of ad hoc knowledge about page layout for even more finer-grained control.

It's enough for my needs. Which might be enough for your needs too.

How to open Visual Studio Code from the command line on OSX?

This was the tutorial I was looking for in this thread. It shows the way to open files in Visual Studio Code by writing code .

1.- Open the file

Bash

                open ~/.bash_profile 

Terminal OS

                    open ~/.zshrc

2.- Add in your file the :

         code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}

3.- Reinicialize terminal and try in the folder you want to open

         code .

4.- Then you can use it as shown in this comment: https://stackoverflow.com/a/41821250/10033560

Symfony2 : How to get form validation errors after binding the request to the form

I came up with this solution. It works solid with the latest Symfony 2.4.

I will try to give some explanations.

Using separate validator

I think it's a bad idea to use separate validation to validate entities and return constraint violation messages, like suggested by other writers.

  1. You will need to manually validate all the entities, specify validation groups, etc, etc. With complex hierarchical forms it's not practical at all and will get out of hands quickly.

  2. This way you will be validating form twice: once with form and once with separate validator. This is a bad idea from the performance perspective.

I suggest to recursively iterate form type with it's children to collect error messages.

Using some suggested methods with exclusive IF statement

Some answers suggested by another authors contain mutually exclusive IF statements like this: if ($form->count() > 0) or if ($form->hasChildren()).

As far as I can see, every form can have errors as well as children. I'm not expert with Symfony Forms component, but in practice you will not get some errors of the form itself, like CSRF protection error or extra fields error. I suggest to remove this separation.

Using denormalized result structure

Some authors suggest to put all errors inside of a plain array. So all the error messages of the form itself and of it's children will be added to the same array with different indexing strategies: number-based for type's own errors and name-based for children errors. I suggest to use normalized data structure of the form:

errors:
    - "Self error"
    - "Another self error"

children
    - "some_child":
        errors:
            - "Children error"
            - "Another children error"

        children
            - "deeper_child":
                errors:
                    - "Children error"
                    - "Another children error"

    - "another_child":
        errors:
            - "Children error"
            - "Another children error"

That way result can be easily iterated later.

My solution

So here's my solution to this problem:

use Symfony\Component\Form\Form;

/**
 * @param Form $form
 * @return array
 */
protected function getFormErrors(Form $form)
{
    $result = [];

    // No need for further processing if form is valid.
    if ($form->isValid()) {
        return $result;
    }

    // Looking for own errors.
    $errors = $form->getErrors();
    if (count($errors)) {
        $result['errors'] = [];
        foreach ($errors as $error) {
            $result['errors'][] = $error->getMessage();
        }
    }

    // Looking for invalid children and collecting errors recursively.
    if ($form->count()) {
        $childErrors = [];
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $childErrors[$child->getName()] = $this->getFormErrors($child);
            }
        }
        if (count($childErrors)) {
            $result['children'] = $childErrors;
        }
    }

    return $result;
}

I hope it'll help someone.

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Git - Pushing code to two remotes

In recent versions of Git you can add multiple pushurls for a given remote. Use the following to add two pushurls to your origin:

git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git

So when you push to origin, it will push to both repositories.

UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v should reveal the current URLs for each remote.

UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url> adds a pushurl for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurls for a given remote, which then allows you to push to multiple remotes using a single git push. You can verify this behavior below:

$ git clone git://original/repo.git
$ git remote -v
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

Now, if you want to push to two or more repositories using a single command, you may create a new remote named all (as suggested by @Adam Nelson in comments), or keep using the origin, though the latter name is less descriptive for this purpose. If you still want to use origin, skip the following step, and use origin instead of all in all other steps.

So let's add a new remote called all that we'll reference later when pushing to multiple repositories:

$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)               <-- ADDED
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git            <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED

Then let's add a pushurl to the all remote, pointing to another repository:

$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)                 <-- CHANGED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git         <-- ADDED

Here git remote -v shows the new pushurl for push, so if you do git push all master, it will push the master branch to git://another/repo.git only. This shows how pushurl overrides the default url (remote.all.url).

Now let's add another pushurl pointing to the original repository:

$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git        <-- ADDED

You see both pushurls we added are kept. Now a single git push all master will push the master branch to both git://another/repo.git and git://original/repo.git.

How to call a function in shell Scripting?

You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.

Function Definition : Create a new script file
Function Call       : Invoke the script file

How to add an image in the title bar using html?

Showing image in title bar is easy. please follow the steps :

a) first save you image some where in the folder and name like favicon. b) then use below line inside head tag of the html view

<link rel="icon" type="image/png" href="image_url" />

c) Here you must know the path of your file, where you have saved the image d) save your image url in place of image_url e) save your working.

console.log showing contents of array object

console.log does not produce any message box. I don't think it is available in any version of IE (nor Firefox) without the addition of firebug or some equivalent.

It is however available in Safari and Chrome. Since you mention Chrome I'll use that for my example.

You'll need to open your window and its developer window counterpart. you can do this by right clicking any element on the page and selecting "Inspect element". your window will be divided in two parts, the developer part being the bottom. in the division between the two parts is a bar with buttons and the rightmost button there is labeled "console". You'll need to click that to switch to the console tab. Press F12 for developer tools in most browsers on Windows, command + shift + I on macOS.

Once there, you will be able to interact with whatever page is loaded on top through javascript from that console, and any messages you console.log will be displayed there.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

this error I was able to remove after adding profile:

<profile>
            <id>surefire-windows-fork-disable</id>
            <activation>
                <os>
                    <family>Windows</family>
                </os>
            </activation>
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-surefire-plugin</artifactId>
                            <configuration>
                                <forkCount>0</forkCount>
                                <useSystemClassLoader>false</useSystemClassLoader>
                            </configuration>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>

seems that this is a windows problem regarding maven surefire forks

Set up adb on Mac OS X

if you are using Android Studio in MAC OS X , you could exec the following command in your terminal app:

echo 'alias adb="/Applications/Android\ Studio.app/sdk/platform-tools/adb"' >> .bashrc
exec $SHELL

and next:

adb devices

and you should be showing a list with your android devices connected via USB cable in your MAC, for example something like this:

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
deb7bed5        device

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

Creating pdf files at runtime in c#

I have used Gnostice in the past and found them to be very good.

http://www.gnostice.com/PDFOne_dot_Net.asp

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

Is there a way to use use text as the background with CSS?

SVG text background image

_x000D_
_x000D_
body {_x000D_
    background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>");_x000D_
}
_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>
_x000D_
_x000D_
_x000D_

Here is an indented version of the CSS so you can understand better. Note that this does not work, you need to use the single liner SVG from the snippet above instead:

body {
  background-image:url("data:image/svg+xml;utf8,
  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'
       height='50px' width='120px'>
    <text x='0' y='15' fill='red' font-size='20'>I love SVG!</text>
  </svg>");
}

Not sure how portable this is (works on Firefox 31 and Chrome 36), and it is technically an image... but the source is inline and plain text, and it scales infinitely.

@senectus found that it works better on IE if you base64 encode it: https://stackoverflow.com/a/25593531/895245

ROW_NUMBER() in MySQL

I always end up following this pattern. Given this table:

+------+------+
|    i |    j |
+------+------+
|    1 |   11 |
|    1 |   12 |
|    1 |   13 |
|    2 |   21 |
|    2 |   22 |
|    2 |   23 |
|    3 |   31 |
|    3 |   32 |
|    3 |   33 |
|    4 |   14 |
+------+------+

You can get this result:

+------+------+------------+
|    i |    j | row_number |
+------+------+------------+
|    1 |   11 |          1 |
|    1 |   12 |          2 |
|    1 |   13 |          3 |
|    2 |   21 |          1 |
|    2 |   22 |          2 |
|    2 |   23 |          3 |
|    3 |   31 |          1 |
|    3 |   32 |          2 |
|    3 |   33 |          3 |
|    4 |   14 |          1 |
+------+------+------------+

By running this query, which doesn't need any variable defined:

SELECT a.i, a.j, count(*) as row_number FROM test a
JOIN test b ON a.i = b.i AND a.j >= b.j
GROUP BY a.i, a.j

Hope that helps!

Could not load file or assembly 'System.Data.SQLite'

I have a 64 bit dev machine and 32 bit build server. I used this code prior to NHibernate initialisation. Works a charm on any architecture (well the 2 I have tested)

Hope this helps someone.

Guido

        private static void LoadSQLLiteAssembly()
        {
            Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            FileInfo fi = new FileInfo(dir.AbsolutePath);           
            string binFile = fi.Directory.FullName + "\\System.Data.SQLite.DLL";
            if (!File.Exists(binFile)) File.Copy(GetAppropriateSQLLiteAssembly(), binFile, false);
        }

        private static string GetAppropriateSQLLiteAssembly()
        {
            string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
            return GetLibsDir() + "\\NUnit\\System.Data.SQLite.x" + arch + ".DLL";
        }

@class vs. #import

if we do this

@interface Class_B : Class_A

mean we are inheriting the Class_A into Class_B, in Class_B we can access all the variables of class_A.

if we are doing this

#import ....
@class Class_A
@interface Class_B

here we saying that we are using the Class_A in our program, but if we want to use the Class_A variables in Class_B we have to #import Class_A in .m file(make a object and use it's function and variables).

Most simple code to populate JTable from ResultSet

go here java tips weblog

then,put in your project : listtabelmodel.java and rowtablemodel.java add another class with this code:

    enter code here
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comp;

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class TableFromDatabase extends JPanel {

    private Connection conexao = null;

    public TableFromDatabase() {
        Vector columnNames = new Vector();
        Vector data = new Vector();

        try {
            //  Connect to an Access Database
            conexao = DriverManager.getConnection("jdbc:mysql://" + "localhost"
                    + ":3306/yourdatabase", "root", "password");

            //  Read data from a table
            String sql = "select * from tb_something";
            Statement stmt = conexao.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++) {
                columnNames.addElement(md.getColumnName(i));
            }

            //  Get row data
            while (rs.next()) {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++) {
                    row.addElement(rs.getObject(i));
                }

                data.addElement(row);
            }

            rs.close();
            stmt.close();
            conexao.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        //  Create table with database data
        JTable table = new JTable(data, columnNames) {
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        JPanel buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("any");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                //Create and set up the content pane.
                TableFromDatabase newContentPane = new TableFromDatabase();
                newContentPane.setOpaque(true); //content panes must be opaque
                frame.setContentPane(newContentPane);

                //Display the window.
                frame.pack();
                frame.setVisible(true);
            }
        });

    }
}

then drag this class to you jframe,and it's done

it's deprecated,but it works.........

How to insert close button in popover for Bootstrap

This is a working solution based on @Chris answer above, but fixed so that upon subsequence clicks of the trigger element, you don't have to click the element twice.

Using .popover('hide) manually messes up bootstraps internal state, as noted in the comments.

var closePopover = function(eventShown) {
   // Set the reference to the calling element
   var $caller = $('#' + this.id);

   // Set the reference to the popover
   var $popover = $('#' + $(eventShown.target).attr('aria-describedby'));

       // Unbind any pre-existing event handlers to prevent duplicate clicks
       $popover.find('.popover-close').off('click');

       // Bind event handler to close button
       $popover.find('.popover-close').on('click', function(e) {

          // Trigger a click on the calling element, to maintain bootstrap's internal state
          $caller.trigger('click');
        });
 }

$('.popoverTriggerElement').popover({
   trigger: 'click'
})
.on('shown.bs.popover', closePopover)

Now, you can use the close button without duplicating the click events, and keeping bootstraps internal state in check so it works as expected.

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

Spring Boot @autowired does not work, classes in different package

Try annotating your Configuration Class(es) with the @ComponentScan("com.esri.birthdays") annotation. Generally spoken: If you have sub-packages in your project, then you have to scan for your relevant classes on project-root. I guess for your case it'll be "com.esri.birthdays". You won't need the ComponentScan, if you have no sub-packaging in your project.

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

Setting an int to Infinity in C++

int min and max values

Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807

i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64

if you always want a to be grater that b why do you need to check it? just set it to be true always

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

How can I delete a newline if it is the last character in a file?

This is a good solution if you need it to work with pipes/redirection instead of reading/output from or to a file. This works with single or multiple lines. It works whether there is a trailing newline or not.

# with trailing newline
echo -en 'foo\nbar\n' | sed '$s/$//' | head -c -1

# still works without trailing newline
echo -en 'foo\nbar' | sed '$s/$//' | head -c -1

# read from a file
sed '$s/$//' myfile.txt | head -c -1

Details:

  • head -c -1 truncates the last character of the string, regardless of what the character is. So if the string does not end with a newline, then you would be losing a character.
  • So to address that problem, we add another command that will add a trailing newline if there isn't one: sed '$s/$//' . The first $ means only apply the command to the last line. s/$// means substitute the "end of the line" with "nothing", which is basically doing nothing. But it has a side effect of adding a trailing newline is there isn't one.

Note: Mac's default head does not support the -c option. You can do brew install coreutils and use ghead instead.

Git push rejected "non-fast-forward"

Write lock on shared local repository

I had this problem and none of above advises helped me. I was able to fetch everything correctly. But push always failed. It was a local repository located on windows directory with several clients working with it through VMWare shared folder driver. It appeared that one of the systems locked Git repository for writing. After stopping relevant VMWare system, which caused the lock everything repaired immediately. It was almost impossible to figure out, which system causes the error, so I had to stop them one by one until succeeded.

Numpy: Creating a complex array from 2 real ones?

That worked for me:

input:

[complex(a,b) for a,b in zip([1,2,3],[1,2,3])]

output:

[(1+4j), (2+5j), (3+6j)]

How can I remove a character from a string using JavaScript?

There's always the string functions, if you know you're always going to remove the fourth character:

str.slice(0, 4) + str.slice(5, str.length))

How do I view 'git diff' output with my preferred diff tool/ viewer?

Introduction

For reference I'd like to include my variation on VonC's answer. Keep in mind that I am using the MSys version of Git (1.6.0.2 at this time) with modified PATH, and running Git itself from Powershell (or cmd.exe), not the Bash shell.

I introduced a new command, gitdiff. Running this command temporarily redirects git diff to use a visual diff program of your choice (as opposed to VonC's solution that does it permanently). This allows me to have both the default Git diff functionality (git diff) as well as visual diff functionality (gitdiff). Both commands take the same parameters, so for example to visually diff changes in a particular file you can type

gitdiff path/file.txt

Setup

Note that $GitInstall is used as a placeholder for the directory where Git is installed.

  1. Create a new file, $GitInstall\cmd\gitdiff.cmd

    @echo off
    setlocal
    for /F "delims=" %%I in ("%~dp0..") do @set path=%%~fI\bin;%%~fI\mingw\bin;%PATH%
    if "%HOME%"=="" @set HOME=%USERPROFILE%
    set GIT_EXTERNAL_DIFF=git-diff-visual.cmd
    set GIT_PAGER=cat
    git diff %*
    endlocal
    
  2. Create a new file, $GitInstall\bin\git-diff-visual.cmd (replacing [visual_diff_exe] placeholder with full path to the diff program of your choice)

    @echo off
    rem diff is called by git with 7 parameters:
    rem path old-file old-hex old-mode new-file new-hex new-mode
    echo Diffing "%5"
    "[visual_diff_exe]" "%2" "%5"
    exit 0
    
  3. You're now done. Running gitdiff from within a Git repository should now invoke your visual diff program for every file that was changed.

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Minimal runnable POSIX read + write example

Usage:

  1. get two computers on a LAN.

    For example, this will work if both computers are connected to your home router in most cases, which is how I tested it.

  2. On the server computer:

    1. Find the server local IP with ifconfig, e.g. 192.168.0.10

    2. Run:

      ./server output.tmp 12345
      
  3. On the client computer:

    printf 'ab\ncd\n' > input.tmp
    ./client input.tmp 192.168.0.10 12345
    
  4. Outcome: a file output.tmp is created on the sever computer containing 'ab\ncd\n'!

server.c

/*
Receive a file over a socket.

Saves it to output.tmp by default.

Interface:

    ./executable [<output_file> [<port>]]

Defaults:

- output_file: output.tmp
- port: 12345
*/

#define _XOPEN_SOURCE 700

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

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *file_path = "output.tmp";
    char buffer[BUFSIZ];
    char protoname[] = "tcp";
    int client_sockfd;
    int enable = 1;
    int filefd;
    int i;
    int server_sockfd;
    socklen_t client_len;
    ssize_t read_return;
    struct protoent *protoent;
    struct sockaddr_in client_address, server_address;
    unsigned short server_port = 12345u;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_port = strtol(argv[2], NULL, 10);
        }
    }

    /* Create a socket and listen to it.. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    server_sockfd = socket(
        AF_INET,
        SOCK_STREAM,
        protoent->p_proto
    );
    if (server_sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(server_port);
    if (bind(
            server_sockfd,
            (struct sockaddr*)&server_address,
            sizeof(server_address)
        ) == -1
    ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    if (listen(server_sockfd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "listening on port %d\n", server_port);

    while (1) {
        client_len = sizeof(client_address);
        puts("waiting for client");
        client_sockfd = accept(
            server_sockfd,
            (struct sockaddr*)&client_address,
            &client_len
        );
        filefd = open(file_path,
                O_WRONLY | O_CREAT | O_TRUNC,
                S_IRUSR | S_IWUSR);
        if (filefd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
        do {
            read_return = read(client_sockfd, buffer, BUFSIZ);
            if (read_return == -1) {
                perror("read");
                exit(EXIT_FAILURE);
            }
            if (write(filefd, buffer, read_return) == -1) {
                perror("write");
                exit(EXIT_FAILURE);
            }
        } while (read_return > 0);
        close(filefd);
        close(client_sockfd);
    }
    return EXIT_SUCCESS;
}

client.c

/*
Send a file over a socket.

Interface:

    ./executable [<input_path> [<sever_hostname> [<port>]]]

Defaults:

- input_path: input.tmp
- server_hostname: 127.0.0.1
- port: 12345
*/

#define _XOPEN_SOURCE 700

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

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char protoname[] = "tcp";
    struct protoent *protoent;
    char *file_path = "input.tmp";
    char *server_hostname = "127.0.0.1";
    char *server_reply = NULL;
    char *user_input = NULL;
    char buffer[BUFSIZ];
    in_addr_t in_addr;
    in_addr_t server_addr;
    int filefd;
    int sockfd;
    ssize_t i;
    ssize_t read_return;
    struct hostent *hostent;
    struct sockaddr_in sockaddr_in;
    unsigned short server_port = 12345;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_hostname = argv[2];
            if (argc > 3) {
                server_port = strtol(argv[3], NULL, 10);
            }
        }
    }

    filefd = open(file_path, O_RDONLY);
    if (filefd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    /* Get socket. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, protoent->p_proto);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    /* Prepare sockaddr_in. */
    hostent = gethostbyname(server_hostname);
    if (hostent == NULL) {
        fprintf(stderr, "error: gethostbyname(\"%s\")\n", server_hostname);
        exit(EXIT_FAILURE);
    }
    in_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
    if (in_addr == (in_addr_t)-1) {
        fprintf(stderr, "error: inet_addr(\"%s\")\n", *(hostent->h_addr_list));
        exit(EXIT_FAILURE);
    }
    sockaddr_in.sin_addr.s_addr = in_addr;
    sockaddr_in.sin_family = AF_INET;
    sockaddr_in.sin_port = htons(server_port);
    /* Do the actual connection. */
    if (connect(sockfd, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in)) == -1) {
        perror("connect");
        return EXIT_FAILURE;
    }

    while (1) {
        read_return = read(filefd, buffer, BUFSIZ);
        if (read_return == 0)
            break;
        if (read_return == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        /* TODO use write loop: https://stackoverflow.com/questions/24259640/writing-a-full-buffer-using-write-system-call */
        if (write(sockfd, buffer, read_return) == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
    }
    free(user_input);
    free(server_reply);
    close(filefd);
    exit(EXIT_SUCCESS);
}

GitHub upstream.

Further comments

Possible improvements:

  • Currently output.tmp gets overwritten each time a send is done.

    This begs for the creation of a simple protocol that allows to pass a filename so that multiple files can be uploaded, e.g.: filename up to the first newline character, max filename 256 chars, and the rest until socket closure are the contents. Of course, that would require sanitation to avoid a path transversal vulnerability.

    Alternatively, we could make a server that hashes the files to find filenames, and keeps a map from original paths to hashes on disk (on a database).

  • Only one client can connect at a time.

    This is specially harmful if there are slow clients whose connections last for a long time: the slow connection halts everyone down.

    One way to work around that is to fork a process / thread for each accept, start listening again immediately, and use file lock synchronization on the files.

  • Add timeouts, and close clients if they take too long. Or else it would be easy to do a DoS.

    poll or select are some options: How to implement a timeout in read function call?

A simple HTTP wget implementation is shown at: How to make an HTTP get request in C without libcurl?

Tested on Ubuntu 15.10.

std::string to char*

For completeness' sake, don't forget std::string::copy().

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

str.copy(chrs, MAX);

std::string::copy() doesn't NUL terminate. If you need to ensure a NUL terminator for use in C string functions:

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

memset(chrs, '\0', MAX);
str.copy(chrs, MAX-1);

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Make sure you have backups of important databases and then try uninstall MySQL related stuff:

apt-get remove --purge mysql\*

Then install it again:

apt-get install mysql-server mysql-client

This worked for me and data was kept.

If PHP MySQL shows errors you might have to reinstall PHP MySQL:

apt-get install php5-fpm php5-mysql

How to increase the distance between table columns in HTML?

You can just use padding. Like so:

http://jsfiddle.net/davidja/KG8Kv/

HTML

   <table>
        <tr>
            <td>item1</td>
            <td>item2</td>
            <td>item2</td>
        </tr>
    </table>

CSS

 td {padding:10px 25px 10px 25px;}

OR

 tr td:first-child {padding-left:0px;}
 td {padding:10px 0px 10px 50px;}

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Try this. The scope of local variables defined by "template" directive.

<table>
  <template ngFor let-group="$implicit" [ngForOf]="groups">
    <tr>
      <td>
        <h2>{{group.name}}</h2>
      </td>
    </tr>
    <tr *ngFor="let item of group.items">
                <td>{{item}}</td>
            </tr>
  </template>
</table>

How to use JavaScript source maps (.map files)?

The map file maps the unminified file to the minified file. If you make changes in the unminified file, the changes will be automatically reflected to the minified version of the file.

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

SFTP Libraries for .NET

I've been using Chilkat's native SFTP library ( http://www.chilkatsoft.com/ssh-sftp-component.asp ) for a couple of months now and it's working great. Been using it in a nightly job to download large files and do private key authentication. Only problem that I had was getting the 64bit version to work on windows server 2008, I needed to install vcredist_x64.exe ( http://www.microsoft.com/download/en/details.aspx?id=14632 ) on my server.

Convert INT to VARCHAR SQL

Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job. Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length and usually default 10 is good enough for integer to string conversion.

SELECT LTRIM(ColumnName) FROM TableName

Convert string to binary then back again using PHP

Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.

var bintext, textresult="", binlength;
    this.aaa = this.text_value;
    bintext = this.aaa.replace(/[^01]/g, "");
        binlength = bintext.length-(bintext.length%8);
        for(var z=0; z<binlength; z=z+8) {
            textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
                            this.ans = textresult;

This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.

How should the ViewModel close the form?

Here's what I initially did, which does work, however it seems rather long-winded and ugly (global static anything is never good)

1: App.xaml.cs

public partial class App : Application
{
    // create a new global custom WPF Command
    public static readonly RoutedUICommand LoggedIn = new RoutedUICommand();
}

2: LoginForm.xaml

// bind the global command to a local eventhandler
<CommandBinding Command="client:App.LoggedIn" Executed="OnLoggedIn" />

3: LoginForm.xaml.cs

// implement the local eventhandler in codebehind
private void OnLoggedIn( object sender, ExecutedRoutedEventArgs e )
{
    DialogResult = true;
    Close();
}

4: LoginFormViewModel.cs

// fire the global command from the viewmodel
private void OnRemoteServerReturnedSuccess()
{
    App.LoggedIn.Execute(this, null);
}

I later on then removed all this code, and just had the LoginFormViewModel call the Close method on it's view. It ended up being much nicer and easier to follow. IMHO the point of patterns is to give people an easier way to understand what your app is doing, and in this case, MVVM was making it far harder to understand than if I hadn't used it, and was now an anti-pattern.

Predefined type 'System.ValueTuple´2´ is not defined or imported

We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.

I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.

How to select records without duplicate on just one field in SQL?

select Country_id,country_title from(
   select Country_id,country_title,row_number() over (partition by country_title 
   order by Country_id  ) rn from country)a
   where rn=1;

In Maven how to exclude resources from the generated jar?

Put those properties files in src/test/resources. Files in src/test/resources are available within Eclipse automatically via eclipse:eclipse but will not be included in the packaged JAR by Maven.

VB.NET - If string contains "value1" or "value2"

Interestingly, this solution can break, but a workaround: Looking for my database called KeyWorks.accdb which must exist:

Run this:

Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry

If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.

If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.

If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

Get the string representation of a DOM node

What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.

var getString = (function() {
  var DIV = document.createElement("div");

  if ('outerHTML' in DIV)
    return function(node) {
      return node.outerHTML;
    };

  return function(node) {
    var div = DIV.cloneNode();
    div.appendChild(node.cloneNode(true));
    return div.innerHTML;
  };

})();

// getString(el) == "<p>Test</p>"

You'll find my jQuery plugin here: Get selected element's outer HTML

Java: Getting a substring from a string starting after a particular character

You can use Apache commons:

For substring after last occurrence use this method.

And for substring after first occurrence equivalent method is here.

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

Implement division with bit-wise operator

Division of two numbers using bitwise operators.

#include <stdio.h>

int remainder, divisor;

int division(int tempdividend, int tempdivisor) {
    int quotient = 1;

    if (tempdivisor == tempdividend) {
        remainder = 0;
        return 1;
    } else if (tempdividend < tempdivisor) {
        remainder = tempdividend;
        return 0;
    }   

    do{

        tempdivisor = tempdivisor << 1;
        quotient = quotient << 1;

     } while (tempdivisor <= tempdividend);


     /* Call division recursively */
    quotient = quotient + division(tempdividend - tempdivisor, divisor);

    return quotient;
} 


int main() {
    int dividend;

    printf ("\nEnter the Dividend: ");
    scanf("%d", &dividend);
    printf("\nEnter the Divisor: ");
    scanf("%d", &divisor);   

    printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
    printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);
    getch();
}

Bulk create model objects in django

for a single line implementation, you can use a lambda expression in a map

map(lambda x:MyModel.objects.get_or_create(name=x), items)

Here, lambda matches each item in items list to x and create a Database record if necessary.

Lambda Documentation

How to delete a line from a text file in C#?

To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:

List<string> quotelist=File.ReadAllLines(filename).ToList();
string firstItem= quotelist[0];
quotelist.RemoveAt(0);
File.WriteAllLines(filename, quotelist.ToArray());
return firstItem;

Can't concatenate 2 arrays in PHP

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

How to read an entire file to a string using C#?

well the quickest way meaning with the least possible C# code is probably this one:

string readText = System.IO.File.ReadAllText(path);

How do I allow HTTPS for Apache on localhost?

I use ngrok (https://ngrok.com/) for this. ngrok is a command line tool and create a tunnel for localhost. It creates both http and https connection. After downloading it, following command needs to be run :

ngrok http 80

( In version 2, the syntax is : ngrok http 80 . In version 2, any port can be tunneled. )

After few seconds, it will give two urls :

http://a_hexadecimal_number.ngrok.com
https://a_hexadecimal_number.ngrok.com

Now, both the urls point to the localhost.

Spring JUnit: How to Mock autowired component in autowired component

I created blog post on the topic. It contains also link to Github repository with working example.

The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary and @Profile annotations for this trick.

Check if any type of files exist in a directory using BATCH script

A roll your own function.

Supports recursion or not with the 2nd switch.

Also, allow names of files with ; which the accepted answer fails to address although a great answer, this will get over that issue.

The idea was taken from https://ss64.com/nt/empty.html

Notes within code.

@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written:               2020.01.26
:: Posted on the thread here:   https://stackoverflow.com/q/10813943/8262102
:: Based on:                    https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>"   = Your path wrapped in quotes.
:: <BOOLEAN>  = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE      = if directory doesn't exist.
:: 0-inf      = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
  echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
  ) else if not "%~1"=="" (
  set count=0 & set msg= & set dirExists=
  if not exist "!%~1!" (set msg=FALSE)
  if exist "!%~1!" (
   if {%~2}=={TRUE} (
    >nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
    set msg=!count!
    )
   if {%~2}=={FALSE} (
    for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
    set msg=!count!
    )
   )
  )
  set "%~1=!msg!" & goto :eof
  )

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

Have a reloadData for a UITableView animate when changing

I believe you can just update your data structure, then:

[tableView beginUpdates];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView endUpdates];

Also, the "withRowAnimation" is not exactly a boolean, but an animation style:

UITableViewRowAnimationFade,
UITableViewRowAnimationRight,
UITableViewRowAnimationLeft,
UITableViewRowAnimationTop,
UITableViewRowAnimationBottom,
UITableViewRowAnimationNone,
UITableViewRowAnimationMiddle

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

Try this solution and it worked. this problem is caused because ADB is unable to connect to the android servers to fetch updates. (If at home try turning off firewall)

  • Goto Android SDK Manager c://android-sdk-windows/ open SDK-Manager
  • Click Settings - Will be asked for a proxy.
  • If have one enter the IP address and the port number. If not turn off your firewall.
  • Check "Force https://... " (to force SDK Manager to use http, not https)

This should work immediately.