Programs & Examples On #Late bound evaluation

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

jQuery when element becomes visible

I just Improved ProllyGeek`s answer

Someone may find it useful. you can access displayChanged(event, state) event when .show(), .hide() or .toggle() is called on element

(function() {
  var eventDisplay = new $.Event('displayChanged'),
    origShow = $.fn.show,
    origHide = $.fn.hide;
  //
  $.fn.show = function() {
    origShow.apply(this, arguments);
    $(this).trigger(eventDisplay,['show']);
  };
  //
  $.fn.hide = function() {
    origHide.apply(this, arguments);
    $(this).trigger(eventDisplay,['hide']);
  };
  //
})();

$('#header').on('displayChanged', function(e,state) {
      console.log(state);
});

$('#header').toggle(); // .show() .hide() supported

Practical uses for the "internal" keyword in C#

Noise reduction, the less types you expose the more simple your library is. Tamper proofing / Security is another (although Reflection can win against it).

Array initializing in Scala

Another way of declaring multi-dimentional arrays:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

HTML combo box with option to type an entry

    <html>
<head>
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
       <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
   </body>
</html>

Click to see OutPut Screen

Thanks...:)

How to vertically align text inside a flexbox?

Instead of using align-self: center use align-items: center.

There's no need to change flex-direction or use text-align.

Here's your code, with one adjustment, to make it all work:

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  /* align-self: center;    <---- REMOVE */
  align-items: center;   /* <---- NEW    */
  background: silver;
  width: 100%;
  height: 20%; 
}

The align-self property applies to flex items. Except your li is not a flex item because its parent – the ul – does not have display: flex or display: inline-flex applied.

Therefore, the ul is not a flex container, the li is not a flex item, and align-self has no effect.

The align-items property is similar to align-self, except it applies to flex containers.

Since the li is a flex container, align-items can be used to vertically center the child elements.

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
ul {_x000D_
  height: 100%;_x000D_
}_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  /* align-self: center; */_x000D_
  align-items: center;_x000D_
  background: silver;_x000D_
  width: 100%;_x000D_
  height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
  <li>This is the text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

codepen demo


Technically, here's how align-items and align-self work...

The align-items property (on the container) sets the default value of align-self (on the items). Therefore, align-items: center means all flex items will be set to align-self: center.

But you can override this default by adjusting the align-self on individual items.

For example, you may want equal height columns, so the container is set to align-items: stretch. However, one item must be pinned to the top, so it is set to align-self: flex-start.

example


How is the text a flex item?

Some people may be wondering how a run of text...

<li>This is the text</li>

is a child element of the li.

The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.

From the CSS spec:

9.2.2.1 Anonymous inline boxes

Any text that is directly contained inside a block container element must be treated as an anonymous inline element.

The flexbox specification provides for similar behavior.

4. Flex Items

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

Hence, the text in the li is a flex item.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

width:auto for <input> fields

"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."

No one actually answered the above part of the original poster's question.

Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/

As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.

To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

How to connect to MongoDB in Windows?

Did you create the default db path?
It defaults to "/data/db directory (or c:\data\db on Windows)"
Source: http://www.mongodb.org/display/DOCS/Starting+and+Stopping+Mongo

indexOf Case Sensitive?

 static string Search(string factMessage, string b)
        {

            int index = factMessage.IndexOf(b, StringComparison.CurrentCultureIgnoreCase);
            string line = null;
            int i = index;
            if (i == -1)
            { return "not matched"; }
            else
            {
                while (factMessage[i] != ' ')
                {
                    line = line + factMessage[i];
                    i++;
                }

                return line;
            }

        }

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Commenting out code blocks in Atom

Atom does not have block comment by default, so I would recommend searching for atom packages by "block comment" and install the one suits to you.

I prefer https://atom.io/packages/block-comment because is has the closest keyboard shortcut to line comment and it works as i need it to, meaning it would not comment the whole line but only the selected text.

line comment: CTRL+/ block comment: CTRL+SHIFT+/ (with the plugin installed)

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

Open Sublime Text from Terminal in macOS

Please note not to write into /usr/bin but instead into /usr/local/bin. The first one is for app that write themselves the binary into the system and the latest is for that specific usage of making our own system-wide binaries (which is our case here when symlinking).

Also /usr/local/bin is read after /usr/bin and therefore also a good place to override any default app.

Considering this, the right symlinking would be:

ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Combining two expressions (Expression<Func<T, bool>>)

Nothing new here but married this answer with this answer and slightly refactored it so that even I understand what's going on:

public static class ExpressionExtensions
{
    public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
    {
        ParameterExpression parameter1 = expr1.Parameters[0];
        var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
        var body2WithParam1 = visitor.Visit(expr2.Body);
        return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);
    }

    private class ReplaceParameterVisitor : ExpressionVisitor
    {
        private ParameterExpression _oldParameter;
        private ParameterExpression _newParameter;

        public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
        {
            _oldParameter = oldParameter;
            _newParameter = newParameter;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (ReferenceEquals(node, _oldParameter))
                return _newParameter;

            return base.VisitParameter(node);
        }
    }
}

jquery data selector

Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector

Use it like that:

data selector           jQuery selector
  $$('name')              $('[data-name]')
  $$('name', 10)          $('[data-name=10]')
  $$('name', false)       $('[data-name=false]')
  $$('name', null)        $('[data-name]')
  $$('name', {})          Syntax error

inserting characters at the start and end of a string

Let's say we have a string called yourstring:

for x in range(0, [howmanytimes you want it at the beginning]):
    yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
    yourstring += "L"

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

How to declare and use 1D and 2D byte arrays in Verilog?

It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.

reg a[0:3]; 

This will create a 1D of array of single bit. Similarly 2D array can be created like this:

reg [0:3][0:2];

Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:

reg [0:4] a [0:3][0:2];

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

How do I use Assert to verify that an exception has been thrown?

This is going to depend on what test framework are you using?

In MbUnit, for example, you can specify the expected exception with an attribute to ensure that you are getting the exception you really expect.

[ExpectedException(typeof(ArgumentException))]

What is a race condition?

What is a Race Condition?

You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That's a race condition - specifically a "check-then-act" scenario of race conditions.

How do you detect them?

Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.

How do you handle and prevent them?

The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.

The best resource for concurrency is JCIP. You can also get some more details on above explanation here.

How can I compare two time strings in the format HH:MM:SS?

I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.

function compareDateTimes() {
    //date format ex "04/20/2017 01:30PM"
    //the problem is that this format results in Invalid Date
    //var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date

    var start_date = $(".letter #depo_arrival_time").val();
    var end_date = $(".letter #depo_dateandtime").val();

    if (start_date=="" || end_date=="") {
        return;
    }
    //break it up for processing
    var d1 = stringToDate(start_date);
    var d2 = stringToDate(end_date);

    var diff = d2.getTime() - d1.getTime();
    if (diff < 0) {
        end_date = moment(d2).format("MM/DD/YYYY hh:mA");
        $(".letter #depo_arrival_time").val(end_date);
    }
}

function stringToDate(the_date) {
    var arrDate = the_date.split(" ");
    var the_date = arrDate[0];
    var the_time = arrDate[1];
    var arrTime = the_time.split(":");
    var blnPM = (arrTime[1].indexOf("PM") > -1);
    //first fix the hour
    if (blnPM) {
        if (arrTime[0].indexOf("0")==0) {
            var clean_hour = arrTime[0].substr(1,1);
            arrTime[0] = Number(clean_hour) + 12;
        }
        arrTime[1] = arrTime[1].replace("PM", ":00");
    } else {
        arrTime[1] = arrTime[1].replace("AM", ":00");
    }
    var date_object =  new Date(the_date);
    //now replace the time
    date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
    date_object =  new Date(date_object);

    return date_object;
}

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

How to check if user input is not an int value

Simply throw Exception if input is invalid

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

How to tell which row number is clicked in a table?

In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:

<table id="elitable" border="1" cellspacing="0" width="100%">
  <tr>
 <td>100</td><td>AAA</td><td>aaa</td>
  </tr>
  <tr>
<td>200</td><td>BBB</td><td>bbb</td>
   </tr>
   <tr>
<td>300</td><td>CCC</td><td>ccc</td>
  </tr>
</table>


    <script>
    $(function(){
        $("#elitable tr").click(function(){
        alert (this.rowIndex);
        });
    });
    </script>

DEMO

Fundamental difference between Hashing and Encryption algorithms

Use hashes when you don't want to be able to get back the original input, use encryption when you do.

Hashes take some input and turn it into some bits (usually thought of as a number, like a 32 bit integer, 64 bit integer, etc). The same input will always produce the same hash, but you PRINCIPALLY lose information in the process so you can't reliably reproduce the original input (there are a few caveats to that however).

Encryption principally preserves all of the information you put into the encryption function, just makes it hard (ideally impossible) for anyone to reverse back to the original input without possessing a specific key.

Simple Example of Hashing

Here's a trivial example to help you understand why hashing can't (in the general case) get back the original input. Say I'm creating a 1-bit hash. My hash function takes a bit string as input and sets the hash to 1 if there are an even number of bits set in the input string, else 0 if there were an odd number.

Example:

Input    Hash
0010     0
0011     1
0110     1
1000     0

Note that there are many input values that result in a hash of 0, and many that result in a hash of 1. If you know the hash is 0, you can't know for sure what the original input was.

By the way, this 1-bit hash isn't exactly contrived... have a look at parity bit.

Simple Example of Encryption

You might encrypt text by using a simple letter substitution, say if the input is A, you write B. If the input is B, you write C. All the way to the end of the alphabet, where if the input is Z, you write A again.

Input   Encrypted
CAT     DBU
ZOO     APP

Just like the simple hash example, this type of encryption has been used historically.

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

How to change JDK version for an Eclipse project

Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.

Changing JRE

Enter image description here

How can I lookup a Java enum from its String value?

And you can't use valueOf()?

Edit: Btw, there is nothing stopping you from using static { } in an enum.

How to do logging in React Native?

Every developer facing this issue of debugging with the react native, even I faced too and I refer this and solution is sufficient for me at initial level, it cover few ways that help us to try and use what ever comfortable with us

  1. Debugging with console.log
  2. Debugging code (logic) with Nuclide
  3. Debugging code(logic) with Chrome
  4. Use Xcode to debug GUI

https://codeburst.io/react-native-debugging-tools-3a24e4e40e4

Search all the occurrences of a string in the entire project in Android Studio

Android Studio 3.3 seems to have changed the shortcut to search for all references (find in path) on macOS.

In order to do that you should use Ctrl + Shift + F now (instead of Command + Shift + F as wrote on the previous answers):

UPDATE

To replace in path just use Ctrl + Shift + R.

enter image description here

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How to copy text from a div to clipboard

Both examples work like a charm :)

  1. JAVASCRIPT:

    _x000D_
    _x000D_
    function CopyToClipboard(containerid) {_x000D_
      if (document.selection) {_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select().createTextRange();_x000D_
        document.execCommand("copy");_x000D_
      } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().addRange(range);_x000D_
        document.execCommand("copy");_x000D_
        alert("Text has been copied, now paste in the text-area")_x000D_
      }_x000D_
    }
    _x000D_
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
    <br /><br />_x000D_
    <div id="div1">Text To Copy </div>_x000D_
    <br />_x000D_
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
    _x000D_
    _x000D_
    _x000D_

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard

What does cmd /C mean?

CMD.exe

Start a new CMD shell

Syntax
      CMD [charset] [options] [My_Command] 

Options       

**/C     Carries out My_Command and then
terminates**

From the help.

How to pass a PHP variable using the URL

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

How to dynamically create CSS class in JavaScript and apply?

There is a light jQuery plugin which allows to generate CSS declarations: jQuery-injectCSS

In fact, it uses JSS (CSS described by JSON), but it's quite easy to handle in order to generate dynamic css stylesheets.

$.injectCSS({
    "#test": {
        height: 123
    }
});

Run a JAR file from the command line and specify classpath

Run a jar file and specify a class path like this:

java -cp <jar_name.jar:libs/*> com.test.App

jar_name.jar is the full name of the JAR you want to execute

libs/* is a path to your dependency JARs

com.test.App is the fully qualified name of the class from the JAR that has the main(String[]) method

The jar and dependent jar should have execute permissions.

psql: could not connect to server: No such file or directory (Mac OS X)

This happened to me after my Mac (High Sierra) froze and I had to manually restart it (press and hold the power button). All I had to do to fix it was do a clean restart.

Sorting Python list based on the length of the string

def lensort(list_1):
    list_2=[];list_3=[]
for i in list_1:
    list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
    list_3.append(i[0])
return list_3

This works for me!

How to create a GUID in Excel?

Italian version:

=CONCATENA(
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
    DECIMALE.HEX(CASUALE.TRA(0;42949);4))

Multiple distinct pages in one HTML file

Solution 1

One solution for this, not requiring any JavaScript, is simply to create a single page in which the multiple pages are simply regular content that is separated by a lot of white space. They can be wrapped into div containers, and an inline style sheet can endow them with the margin:

<style>
.subpage { margin-bottom: 2048px; }
</style>
... main page ...

<div class="subpage">
<!-- first one is empty on purpose: just a place holder for margin;
     alternative is to use this for the main part of the page also! -->
</div>

<div class="subpage">
</div>

<div class="subpage">
</div>

You get the picture. Each "page" is just a section followed by a whopping amount of vertical space so that the next one doesn't show.

I'm using this trick to add "disambiguation navigation links" into a large document (more than 430 pages long in its letter-sized PDF form), which I would greatly prefer to keep as a single .html file. I emphasize that this is not a web site, but a document.

When the user clicks on a key word hyperlink in the document for which there are multiple possible topics associated with word, the user is taken a small navigation menu presenting several topic choices. This menu appears at top of what looks like a blank browser window, and so effectively looks like a page.

The only clue that the menu isn't a separate page is the state of the browser's vertical scroll bar, which is largely irrelevant in this navigation use case. If the user notices that, and starts scrolling around, the whole ruse is revealed, at which point the user will smile and appreciate not having been required to unpack a .zip file full of little pages and go hunting for the index.html.

Solution 2

It's actually possible to embed a HTML page within HTML. It can be done using the somewhat obscure data: URL in the href attribute. As a simple test, try sticking this somewhere in a HTML page:

<a href="data:text/html;charset=utf-8,<h3>FOO</h3>">blah</a>

In Firefox, I get a "blah" hyperlink, which navigates to a page showing the FOO heading. (Note that I don't have a fully formed HTML page here, just a HTML snippet; it's just a hello-world example).

The downside of this technique is that the entire target page is in the URL, which is stuffed into the browser's address input box.

If it is large, it could run into some issues, perhaps browser-specific; I don't have much experience with it.

Another disadvantage is that the entire HTML has to be properly escaped so that it can appear as the argument of the href attribute. Obviously, it cannot contain a plain double quote character anywhere.

A third disadvantage is that each such link has to replicates the data: material, since it isn't semantically a link at all, but a copy and paste embedding. It's not an attractive solution if the page-to-be-embeddded is large, and there are to be numerous links to it.

How to change text color and console color in code::blocks?

I Know, I am very late but, May be my answer can help someone. Basically it's very Simple. Here is my Code.

#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
    HANDLE colors=GetStdHandle(STD_OUTPUT_HANDLE);

    string text;
    int k;
    cout<<" Enter your Text : ";
    getline(cin,text);
    for(int i=0;i<text.length();i++)
    {
        k>9 ? k=0 : k++;

        if(k==0)
        {
            SetConsoleTextAttribute(colors,1);
        }else
        {
            SetConsoleTextAttribute(colors,k);
        }
        cout<<text.at(i);
    }
}

OUTPUT

This Image will show you how it works

If you want the full tutorial please see my video here: How to change Text color in C++

How to check permissions of a specific directory?

$ ls -ld directory

ls is the list command.

- indicates the beginning of the command options.

l asks for a long list which includes the permissions.

d indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.

Run Android studio emulator on AMD processor

Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.

In my opinion, the performance is significantly better than all previous workarounds.

ffprobe or avprobe not found. Please install one

You can install them by

sudo apt-get install -y libav-tools

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

PostgreSQL unnest() with element number

Use Subscript Generating Functions.
http://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS

For example:

SELECT 
  id
  , elements[i] AS elem
  , i AS nr
FROM
  ( SELECT 
      id
      , elements
      , generate_subscripts(elements, 1) AS i
    FROM
      ( SELECT
          id
          , string_to_array(elements, ',') AS elements
        FROM
          myTable
      ) AS foo
  ) bar
;

More simply:

SELECT
  id
  , unnest(elements) AS elem
  , generate_subscripts(elements, 1) AS nr
FROM
  ( SELECT
      id
      , string_to_array(elements, ',') AS elements
    FROM
      myTable
  ) AS foo
;

C# function to return array

 static void Main()
     {
             for (int i=0; i<GetNames().Length; i++)
               {
                    Console.WriteLine (GetNames()[i]);
                }
     }

  static string[] GetNames()
   {
         string[] ret = {"Answer", "by", "Anonymous", "Pakistani"};
         return ret;
   }

Pass multiple parameters to rest API - Spring

(1) Is it possible to pass a JSON object to the url like in Ex.2?

No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"} is not a valid URL.

If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif, and defined your method like this:

@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
    // code here
}

(2) How can we pass and parse the parameters in Ex.1?

Just add two request parameters, and give the correct path.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
    // code here
}

UPDATE (from comment)

What if we have a complicated parameter structure ?

"A": [ {
    "B": 37181,
    "timestamp": 1160100436,
    "categories": [ {
        "categoryID": 2653,
        "timestamp": 1158555774
    }, {
        "categoryID": 4453,
        "timestamp": 1158555774
    } ]
} ]

Send that as a POST with the JSON data in the request body, not in the URL, and specify a content type of application/json.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
    // code here
}

How to join two JavaScript Objects, without using JQUERY

1)

var merged = {};
for(key in obj1)
    merged[key] = obj1[key];
for(key in obj2)
    merged[key] = obj2[key];

2)

var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);

OR

Object.keys(obj1)
    .concat(Object.keys(obj2))
    .forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);

3) Simplest way:

var merged = {};
Object.assign(merged, obj1, obj2);

Selecting empty text input using jQuery

I'd recommend:

$('input:text:not([value])')

Checking version of angular-cli that's installed?

ng --version

ng--version output

Please take a look at the above image.

Making button go full-width?

The width of the button is defined by the button text. So if you want to define the width of the button you can use a defined width by using pixel in the css or if you want to by responsive use a percentage value.

How to have Android Service communicate with Activity

You may also use LiveData that works like an EventBus.

class MyService : LifecycleService() {
    companion object {
        val BUS = MutableLiveData<Any>()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        val testItem : Object

        // expose your data
        if (BUS.hasActiveObservers()) {
            BUS.postValue(testItem)
        }

        return START_NOT_STICKY
    }
}

Then add an observer from your Activity.

MyService.BUS.observe(this, Observer {
    it?.let {
        // Do what you need to do here
    }
})

You can read more from this blog.

ImportError: No module named dateutil.parser

For Python 3 above, use:

sudo apt-get install python3-dateutil

How to use SQL LIKE condition with multiple values in PostgreSQL?

Using array or set comparisons:

create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');

select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');

select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));

It is also possible to do an AND which would not be easy with a regex if it were to match any order:

select str from t
where str like all ('{"%999%", "DDD%"}');

select str from t
where str like all (values('%999%'), ('DDD%'));

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

You need to add the command 'go' after you set the identity insert. Example:

SET IDENTITY_INSERT sometableWithIdentity ON
go

INSERT sometableWithIdentity (IdentityColumn, col2, col3, ...)
VALUES (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF
go

How do you show animated GIFs on a Windows Form (c#)

It doesn't when you start a long operation behind, because everything STOPS since you'Re in the same thread.

Replace only some groups with Regex

Here is another nice clean option that does not require changing your pattern.

        var text = "example-123-example";
        var pattern = @"-(\d+)-";

        var replaced = Regex.Replace(text, pattern, (_match) =>
        {
            Group group = _match.Groups[1];
            string replace = "AA";
            return String.Format("{0}{1}{2}", _match.Value.Substring(0, group.Index - _match.Index), replace, _match.Value.Substring(group.Index - _match.Index + group.Length));
        });

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

How to capitalize the first character of each word in a string

You can also do it very simply like this and preserve any doubled and leading, trailing whitespaces

public static String capitalizeWords(String text) {

    StringBuilder sb = new StringBuilder();
    if(text.length()>0){
        sb.append(Character.toUpperCase(text.charAt(0)));
    }
    for (int i=1; i<text.length(); i++){
        String chPrev = String.valueOf(text.charAt(i-1));
        String ch = String.valueOf(text.charAt(i));

        if(Objects.equals(chPrev, " ")){
            sb.append(ch.toUpperCase());
        }else {
            sb.append(ch);
        }

    }

    return sb.toString();

}

How do I tell Python to convert integers into words

The inflect package can do this.

https://pypi.python.org/pypi/inflect

$ pip install inflect

and then:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Can I hide the HTML5 number input’s spin box?

To make this work in Safari I found adding !important to the webkit adjustment forces the spin button to be hidden.

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    /* display: none; <- Crashes Chrome on hover */
    -webkit-appearance: none !important;
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}

I am still having trouble working out a solution for Opera as well.

Convert string to int array using LINQ

This post asked a similar question and used LINQ to solve it, maybe it will help you out too.

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How to move files from one git repo to another (not a clone), preserving history

The one I always use is here http://blog.neutrino.es/2012/git-copy-a-file-or-directory-from-another-repository-preserving-history/ . Simple and fast.

For compliance with stackoverflow standards, here is the procedure:

mkdir /tmp/mergepatchs
cd ~/repo/org
export reposrc=myfile.c #or mydir
git format-patch -o /tmp/mergepatchs $(git log $reposrc|grep ^commit|tail -1|awk '{print $2}')^..HEAD $reposrc
cd ~/repo/dest
git am /tmp/mergepatchs/*.patch

How to implement zoom effect for image view in android?

Very simple way (Tested) :-

PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();

Add bellow line in build.gradle :-

compile 'com.commit451:PhotoView:1.2.4'

How do I fix a NoSuchMethodError?

Note that in the case of reflection, you get an NoSuchMethodException, while with non-reflective code, you get NoSuchMethodError. I tend to go looking in very different places when confronted with one versus the other.

Use virtualenv with Python with Visual Studio Code in Ubuntu

It seems to be (as of 2018.03) in code-insider. A directive has been introduced called python.venvFolders:

  "python.venvFolders": [
    "envs",
    ".pyenv",
    ".direnv"
  ],

All you need is to add your virtualenv folder name.

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

How do I write a bash script to restart a process if it dies?

I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.

From man page:

run-one-constantly COMMAND [ARGS]

Note: obviously this could be called from within your script, but also it removes the need for having a script at all.

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

How to display an IFRAME inside a jQuery UI dialog

There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:

$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});

Another would be to load the content of your external link into the dialog container using ajax.

$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});

Both works fine but depends on the external content.

How to determine the version of the C++ standard used by the compiler?

Normally you should use __cplusplus define to detect c++17, but by default microsoft compiler does not define that macro properly, see https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ - you need to either modify project settings to include /Zc:__cplusplus switch, or you could use syntax like this:

#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
     //C++17 specific stuff here
#endif

Which Python memory profiler is recommended?

Try also the pytracemalloc project which provides the memory usage per Python line number.

EDIT (2014/04): It now has a Qt GUI to analyze snapshots.

How to read an external local JSON file in JavaScript?

So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,

1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -

enter image description here



2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.

enter image description here


3> Paste your json file over there. enter image description here



4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"enter image description here

Implementing autocomplete

I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete

Restoring database from .mdf and .ldf files of SQL Server 2008

From a script (one that works):

CREATE DATABASE Northwind
ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
GO

obviously update the path:

C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA

To where your .mdf and .ldf reside.

How to send objects through bundle

One More way to send objects through bundle is by using bundle.putByteArray
Sample code

public class DataBean implements Serializable {
private Date currentTime;

public setDate() {
    currentTime = Calendar.getInstance().getTime();
 }

public Date getCurrentTime() {
    return currentTime;
 }
}

put Object of DataBean in to Bundle:

class FirstClass{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//When you want to start new Activity...
Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
            Bundle dataBundle=new Bundle();
            DataBean dataObj=new DataBean();
            dataObj.setDate();
            try {
                dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

            dataIntent.putExtras(dataBundle);

            startActivity(dataIntent);
}

Converting objects to byte arrays

/**
 * Converting objects to byte arrays
 */
static public byte[] object2Bytes( Object o ) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream( baos );
      oos.writeObject( o );
      return baos.toByteArray();
    }

Get Object back from Bundle:

class SecondClass{
DataBean dataBean;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//Get Info from Bundle...
    Bundle infoBundle=getIntent().getExtras();
    try {
        dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Method to get objects from byte arrays:

/**
 * Converting byte arrays to objects
 */
static public Object bytes2Object( byte raw[] )
        throws IOException, ClassNotFoundException {
      ByteArrayInputStream bais = new ByteArrayInputStream( raw );
      ObjectInputStream ois = new ObjectInputStream( bais );
      Object o = ois.readObject();
      return o;
    }

Hope this will help to other buddies.

Add characters to a string in Javascript

Simple use text = text + string2

Xcode 6 Storyboard the wrong size?

You shall probably use the "Resolve Auto Layout Issues" (bottom right - triangle icon in the storyboard view) to add/reset to suggested constraints (Xcode 6.0.1).

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

post ajax data to PHP and return data

So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

What is JavaScript's highest integer value that a number can go to without losing precision?

>= ES6:

Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;

<= ES5

From the reference:

Number.MAX_VALUE;
Number.MIN_VALUE;

_x000D_
_x000D_
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);

console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
_x000D_
_x000D_
_x000D_

Javascript event handler with parameters

this inside of doThings is the window object. Try this instead:

var doThings = function (element) {
    var eventHandler = function(ev, func){
        if (element[ev] == undefined) {
            return;
        }

        element[ev] = function(e){
            func(e, element);
        }
    };

    return {
        eventHandler: eventHandler
    };
};

What does .class mean in Java?

It means your Class reference can hold a reference to any Class object.

It's basically the same as "Class" but you're showing other people who read your code that you didn't forget about generics, you just want a reference that can hold any Class object.

Bruce Eckel, Thinking in Java:

In Java SE5, Class<?> is preferred over plain Class, even though they are equivalent and the plain Class, as you saw, doesn’t produce a compiler warning. The benefit of Class<?> is that it indicates that you aren’t just using a non-specific class reference by accident, or out of ignorance. You chose the non-specific version.

How to find most common elements of a list?

nltk is convenient for a lot of language processing stuff. It has methods for frequency distribution built in. Something like:

import nltk
fdist = nltk.FreqDist(your_list) # creates a frequency distribution from a list
most_common = fdist.max()    # returns a single element
top_three = fdist.keys()[:3] # returns a list

Rearrange columns using cut

You can use Perl for that:

perl -ane 'print "$F[1] $F[0]\n"' < file.txt
  • -e option means execute the command after it
  • -n means read line by line (open the file, in this case STDOUT, and loop over lines)
  • -a means split such lines to a vector called @F ("F" - like Field). Perl indexes vectors starting from 0 unlike cut which indexes fields starting form 1.
  • You can add -F pattern (with no space between -F and pattern) to use pattern as a field separator when reading the file instead of the default whitespace

The advantage of running perl is that (if you know Perl) you can do much more computation on F than rearranging columns.

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

Skip first entry in for loop in python?

I do it like this, even though it looks like a hack it works every time:

ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
    if first == 0
        first = first + 1
        pass
    elif first == last - 1:
        break
    else:
        do_stuff
        first = first + 1
        pass

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

On newer versions of PHP on Windows, the majority of answers here won't work, since the corresponding configuration lines have changed.

For PHP 7.x, you need to uncomment (remove the ; at the beginning of the line) the following lines:

extension_dir = "ext"
extension=openssl

Binding multiple events to a listener (without JQuery)?

AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.

This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types.

    // Add elem as a property of the handle function
    // This is to prevent a memory leak with non-native events in IE.
    eventHandle.elem = elem;

    // Handle multiple events separated by a space
    // jQuery(...).bind("mouseover mouseout", fn);
    types = types.split(" ");  

    var type, i = 0, namespaces;

    while ( (type = types[ i++ ]) ) {  <-- iterates thru 1 by 1

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How to use bootstrap-theme.css with bootstrap 3?

Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

A simple case that generates this error message:

In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

Some variations that work:

In [9]: [1,2,3,4,5][np.array(1)]     # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]    
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])

Basic python list indexing is more restrictive than numpy's:

In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list

edit

Looking again at

indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)

indices is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

Bring a window to the front in WPF

To make this a quick copy-paste one -
Use this class' DoOnProcess method to move process' main window to foreground (but not to steal focus from other windows)

public class MoveToForeground
{
    [DllImportAttribute("User32.dll")]
    private static extern int FindWindow(String ClassName, String WindowName);

    const int SWP_NOMOVE        = 0x0002;
    const int SWP_NOSIZE        = 0x0001;            
    const int SWP_SHOWWINDOW    = 0x0040;
    const int SWP_NOACTIVATE    = 0x0010;
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

    public static void DoOnProcess(string processName)
    {
        var allProcs = Process.GetProcessesByName(processName);
        if (allProcs.Length > 0)
        {
            Process proc = allProcs[0];
            int hWnd = FindWindow(null, proc.MainWindowTitle.ToString());
            // Change behavior by settings the wFlags params. See http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx
            SetWindowPos(new IntPtr(hWnd), 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);
        }
    }
}

HTH

SQL: Select columns with NULL values only

Here I have created a script for any kind of SQL table. please copy this stored procedure and create this on your Environment and run this stored procedure with your Table.

exec [dbo].[SP_RemoveNullValues] 'Your_Table_Name'

stored procedure

GO
/****** Object:  StoredProcedure [dbo].[SP_RemoveNullValues]    Script Date: 09/09/2019 11:26:53 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- akila liyanaarachchi
Create procedure [dbo].[SP_RemoveNullValues](@PTableName Varchar(50) ) as 
begin


DECLARE Cussor CURSOR FOR 
SELECT COLUMN_NAME,TABLE_NAME,DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @PTableName  

OPEN Cussor;

Declare @ColumnName Varchar(50)
Declare @TableName  Varchar(50)
Declare @DataType Varchar(50)
Declare @Flage  int 

FETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType
WHILE @@FETCH_STATUS = 0
BEGIN

set @Flage=0


If(@DataType in('bigint','numeric','bit','smallint','decimal','smallmoney','int','tinyint','money','float','real'))
begin
set @Flage=1
end 
If(@DataType in('date','atetimeoffset','datetime2','smalldatetime','datetime','time'))
begin
set @Flage=2
end 
If(@DataType in('char','varchar','text','nchar','nvarchar','ntext'))
begin
set @Flage=3
end 

If(@DataType in('binary','varbinary'))
begin
set @Flage=4
end 



DECLARE @SQL VARCHAR(MAX) 

if  (@Flage in(1,4))
begin 

SET @SQL ='  update ['+@TableName+'] set ['+@ColumnName+']=0 where ['+@ColumnName+'] is null'
end 

if  (@Flage =3)
begin 

SET @SQL ='  update ['+@TableName+'] set ['+@ColumnName+'] = '''' where ['+@ColumnName+'] is null '
end 

if  (@Flage =2)
begin 

SET @SQL ='  update ['+@TableName+'] set ['+@ColumnName+'] ='+'''1901-01-01 00:00:00.000'''+' where ['+@ColumnName+'] is null '
end 


EXEC(@SQL)



FETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType
END

CLOSE Cussor
DEALLOCATE Cussor

END

Questions every good .NET developer should be able to answer?

I think if I were interviewing someone who had LINQ experience, I'd possibly just ask them to explain LINQ. If they can explain deferred execution, streaming, the IEnumerable/IEnumerator interfaces, foreach, iterator blocks, expression trees (for bonus points, anyway) then they can probably cope with the rest. (Admittedly they could be "ok" developers and not "get" LINQ yet - I'm really thinking of the case where they've claimed to know enough LINQ to make it a fair question.)

In the past I've asked several of the questions already listed, and a few others:

  • Difference between reference and value types
  • Pass by reference vs pass by value
  • IDisposable and finalizers
  • Strings, immutability, character encodings
  • Floating point
  • Delegates
  • Generics
  • Nullable types

How is __eq__ handled in Python and in what order?

The a == b expression invokes A.__eq__, since it exists. Its code includes self.value == other. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__ to see if it knows how to compare itself to an int.

If you amend your code to show what values are being compared:

class A(object):
    def __eq__(self, other):
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self.value == other
class B(object):
    def __eq__(self, other):
        print("B __eq__ called: %r == %r ?" % (self, other))
        return self.value == other

a = A()
a.value = 3
b = B()
b.value = 4
a == b

it will print:

A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?

Object spread vs. Object.assign

The object spread operator (...) doesn't work in browsers, because it isn't part of any ES specification yet, just a proposal. The only option is to compile it with Babel (or something similar).

As you can see, it's just syntactic sugar over Object.assign({}).

As far as I can see, these are the important differences.

  • Object.assign works in most browsers (without compiling)
  • ... for objects isn't standardized
  • ... protects you from accidentally mutating the object
  • ... will polyfill Object.assign in browsers without it
  • ... needs less code to express the same idea

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

offsetTop vs. jQuery.offset().top

You can use parseInt(jQuery.offset().top) to always use the Integer (primitive - int) value across all browsers.

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

How do I get rid of an element's offset using CSS?

In my case the offset was added to a custom element with grid layout within an li while the ul was a vertical flexbox.

enter image description here

The pretty simple solution was to set the define the li as block element with

li {
 display: block;
}

And the offset was gone

sql delete statement where date is greater than 30 days

GETDATE() didn't work for me using mySQL 8

ERROR 1305 (42000): FUNCTION mydatabase.GETDATE does not exist

but this does:

DELETE FROM table_name WHERE date_column < CURRENT_DATE - 30;

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

git pull error :error: remote ref is at but expected

Same case here, but nothing about comments posted it's right in my case, I have only one branch (master) and only use Unix file system, this error occur randomly when I run git fetch --progress --prune origin and branch is ahead or 'origin/master'. Nobody can commit, only 1 user can do push.

NOTE: I have a submodule in acme repository, and acme have new submodule changes (new commits), I need first do a submodule update with git submodule update.

[2014-07-29 13:58:37] Payload POST received from Bitbucket
[2014-07-29 13:58:37] Exec: cd /var/www/html/acme
---------------------
[2014-07-29 13:58:37] Updating Git code for all branches
[2014-07-29 13:58:37] Exec: /usr/bin/git checkout --force master
[2014-07-29 13:58:37] Your branch is ahead of 'origin/master' by 1 commit.
[2014-07-29 13:58:37]   (use "git push" to publish your local commits)
[2014-07-29 13:58:37] Command returned some errors:
[2014-07-29 13:58:37] Already on 'master'
---------------------
[2014-07-29 13:58:37] Exec: /usr/bin/git fetch --progress --prune origin
[2014-07-29 13:58:39] Command returned some errors:
[2014-07-29 13:58:39] error: Ref refs/remotes/origin/master is at 8213a9906828322a3428f921381bd87f42ec7e2f but expected c8f9c00551dcd0b9386cd9123607843179981c91
[2014-07-29 13:58:39] From bitbucket.org:acme/acme
[2014-07-29 13:58:39]  ! c8f9c00..8213a99  master     -> origin/master  (unable to update local ref)
---------------------
[2014-07-29 13:58:39] Unable to fetch Git data

To solve this problem (in my case) simply run first git push if your branch is ahead of origin.

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

Reset the diagnostics and the static analysis under the, for example, Properties -> FORTRAN -> diagnostics. Particular be careful the 'Level of Static Security Analysis' and set it none. Good luck!

Get value of a specific object property in C# without knowing the class behind

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

How to sort mongodb with pymongo

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

Python uses key,direction. You can use the above way.

So in your case you can do this

for post in db.posts.find().sort('entities.user_mentions.screen_name',pymongo.ASCENDING):
        print post

What is the simplest method of inter-process communication between 2 C# processes?

There's also COM.

There are technicalities, but I'd say the advantage is that you'll be able to call methods that you can define.

MSDN offers C# COM interop tutorials. Please search because these links do change.

To get started rightaway go here...

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

Increase days to php current Date()

Add 15 day to a select element (using "Alive to Die" suggestion)

<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
    $NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
    echo "<option>" . $NewDate . "</option>";
    $countDates += 1;
}
?>

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

How to move up a directory with Terminal in OS X

For Mac Terminal

cd ..   # one up
cd ../  # two up
cd      # home directory 
cd /    # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces

Is it possible to declare a public variable in vba and assign a default value?

It's been quite a while, but this may satisfy you :

Public MyVariable as Integer: MyVariable = 123

It's a bit ugly since you have to retype the variable name, but it's on one line.

Catch an exception thrown by an async void method

Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.

public async Task DoFoo()
    {
        try
        {
            return await Foo();
        }
        catch (ProtocolException ex)
        {
            /* Exception with chronological stack trace */     
        }
    }

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

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

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

How do I set GIT_SSL_NO_VERIFY for specific repos only?

If you are on a Windows machine and have the Git installed, you can try the below steps:

  1. Go to the folder of Git installation, ex: C:\Program Files (x86)\Git\etc
  2. Edit the file: gitconfig
  3. Under the [http] section, add the line: sslVerify = false

    [http]
      sslVerify = false
    

ASP.NET MVC3 Razor - Html.ActionLink style

Here's the signature.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

You might want to do this.

@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
     new { @style="text-transform:capitalize;" });

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

Share link on Google+

New Google share link: http://plus.google.com/share?url=YOUR_URL

For secure connection:

https://plus.google.com/share?url=YOUR_URL

For Wordpress:

https://plus.google.com/share?url=<?php the_permalink(); ?>

How to install a specific version of a ruby gem?

Linux

To install different version of ruby, check the latest version of package using apt as below:

$ apt-cache madison ruby
      ruby |    1:1.9.3 | http://ftp.uk.debian.org/debian/ wheezy/main amd64 Packages
      ruby |        4.5 | http://ftp.uk.debian.org/debian/ squeeze/main amd64 Packages

Then install it:

$ sudo apt-get install ruby=1:1.9.3

To check what's the current version, run:

$ gem --version # Check for the current user.
$ sudo gem --version # Check globally.

If the version is still old, you may try to switch the version to new by using ruby version manager (rvm) by:

rvm 1.9.3

Note: You may prefix it by sudo if rvm was installed globally. Or run /usr/local/rvm/scripts/rvm if your command rvm is not in your global PATH. If rvm installation process failed, see the troubleshooting section.


Troubleshooting:

  • If you still have the old version, you may try to install rvm (ruby version manager) via:

    sudo apt-get install curl # Install curl first
    curl -sSL https://get.rvm.io | bash -s stable --ruby # Install only for the user.
    #or:# curl -sSL https://get.rvm.io | sudo bash -s stable --ruby # Install globally. 
    

    then if installed locally (only for current user), load rvm via:

    source /usr/local/rvm/scripts/rvm; rvm 1.9.3
    

    if globally (for all users), then:

    sudo bash -c "source /usr/local/rvm/scripts/rvm; rvm 1.9.3"
    
  • if you still having problem with the new ruby version, try to install it by rvm via:

    source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3 # Locally.
    sudo bash -c "source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3" # Globally.
    
  • if you'd like to install some gems globally and you have rvm already installed, you may try:

    rvmsudo gem install [gemname]
    

    instead of:

      gem install [gemname] # or:
      sudo gem install [gemname]
    

Note: It's prefered to NOT use sudo to work with RVM gems. When you do sudo you are running commands as root, another user in another shell and hence all of the setup that RVM has done for you is ignored while the command runs under sudo (such things as GEM_HOME, etc...). So to reiterate, as soon as you 'sudo' you are running as the root system user which will clear out your environment as well as any files it creates are not able to be modified by your user and will result in strange things happening.

Cannot delete directory with Directory.Delete(path, true)

I think that there is a file open by some stream you are not aware of I had the same problem and solved it by closing all the streams that where pointing to the directory I wanted to delete.

Where does the iPhone Simulator store its data?

iOS 8 ~/Library/Developer/CoreSimulator/Devices/[Device ID]/data/Applications/[appGUID]/Documents/

How can I check for an empty/undefined/null string in JavaScript?

All the previous answers are good, but this will be even better. Use dual NOT operators (!!):

if (!!str) {
    // Some code here
}

Or use type casting:

if (Boolean(str)) {
    // Code here
}

Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for string "0" and whitespace " ".

Reactjs - setting inline styles correctly

You could also try setting style inline without using a variable, like so:

style={{"height" : "100%"}} or,

for multiple attributes: style={{"height" : "100%", "width" : "50%"}}

How can I detect if a selector returns null?

if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}

How to view the list of compile errors in IntelliJ?

You should disable Power Save Mode

For me I clicked over this button

enter image description here

then disable Power Save Mode

How to print like printf in Python3?

The most recommended way to do is to use format method. Read more about it here

a, b = 1, 2

print("a={0},b={1}".format(a, b))

Professional jQuery based Combobox control?

Sexy-Combo has been deprecated. Further development exists in the Unobtrusive Fast-Filter Dropdown project. Looks promising, as i have similar requirements.

https://code.google.com/p/ufd/

How to replace a char in string with an Empty character in C#.NET

It always bothered me that I can't use the String.Remove method to get rid of instances of a string or character in a string so I usually add theses extension methods to my code base:

public static class StringExtensions
{
    public static string Remove(this string str, string toBeRemoved)
    {
        return str.Replace(toBeRemoved, "");
    }

    public static string RemoveChar(this string str, char toBeRemoved)
    {
        return str.Replace(toBeRemoved.ToString(), "");

    }
}

The one taking char can't use overload semantics unfortunately since it will resolve to string.Remove(int startIndex) since it is "closer"

This is of course purely esthetics, but I like it...

How to clear the Entry widget after a button is pressed in Tkinter?

After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text" button is pushed:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height=42, width=42)
        self.entry = tk.Entry(self)
        self.entry.focus()
        self.entry.pack()
        self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
        self.clear_button.pack()

    def clear_text(self):
        self.entry.delete(0, 'end')

def main():
    root = tk.Tk()
    App(root).pack(expand=True, fill='both')
    root.mainloop()

if __name__ == "__main__":
    main()

Installing a specific version of angular with angular cli

Specify the version you want in the 'dependencies' section of your package.json, then from your root project folder in the console/terminal run this:

npm install

For example, the following will specifically install v4.3.4

"dependencies": {
    "@angular/common": "4.3.4",
    "@angular/compiler": "4.3.4",
    "@angular/core": "4.3.4",
    "@angular/forms": "4.3.4",
    "@angular/http": "4.3.4",
    "@angular/platform-browser": "4.3.4",
    "@angular/platform-browser-dynamic": "4.3.4",
    "@angular/router": "4.3.4",
  }

You can also add the following modifiers to the version number to vary how specific you need the version to be:

caret ^

Updates you to the most recent major version, as specified by the first number:

^4.3.0

will load the latest 4.x.x release, but will not load 5.x.x

tilde ~

Update you to the most recent minor version, as specified by the second number:

~4.3.0

will load the latest 4.3.x release, but will not load 4.4.x

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

What is the documents directory (NSDocumentDirectory)?

Like others mentioned, your app runs in a sandboxed environment and you can use the documents directory to store images or other assets your app may use, eg. downloading offline-d files as user prefers - File System Basics - Apple Documentation - Which directory to use, for storing application specific files

Updated to swift 5, you can use one of these functions, as per requirement -

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

func getCacheDirectory() -> URL {
        let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
        return paths[0]
    }

func getApplicationSupportDirectory() -> URL {
        let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
        return paths[0]
    }

Usage:

let urlPath = "https://jumpcloud.com/wp-content/uploads/2017/06/SSH-Keys.png" //Or string path to some URL of valid image, for eg.

if let url = URL(string: urlPath){
    let destination = getDocumentsDirectory().appendingPathComponent(url.lastPathComponent)
    do {
        let data = try Data(contentsOf: url) //Synchronous call, just as an example
        try data.write(to: destination)
    } catch _ {
        //Do something to handle the error
    }
}

CSS for grabbing cursors (drag & drop)

In case anyone else stumbles across this question, this is probably what you were looking for:

.grabbable {
    cursor: move; /* fallback if grab cursor is unsupported */
    cursor: grab;
    cursor: -moz-grab;
    cursor: -webkit-grab;
}

 /* (Optional) Apply a "closed-hand" cursor during drag operation. */
.grabbable:active {
    cursor: grabbing;
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
}

JavaScript closure inside loops – simple practical example

var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function(param) {          // and store them in funcs
    console.log("My value: " + param); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j](j);                      // and now let's run each one to see with j
}

Subset and ggplot2

There's another solution that I find useful, especially when I want to plot multiple subsets of the same object:

myplot<-ggplot(df)+geom_line(aes(Value1, Value2, group=ID, colour=ID))
myplot %+% subset(df, ID %in% c("P1","P3"))
myplot %+% subset(df, ID %in% c("P2"))

How do I convert a IPython Notebook into a Python file via commandline?

I had this problem and tried to find the solution online. Though I found some solutions, they still have some problems, e.g., the annoying Untitled.txt auto-creation when you start a new notebook from the dashboard.

So eventually I wrote my own solution:

import io
import os
import re
from nbconvert.exporters.script import ScriptExporter
from notebook.utils import to_api_path


def script_post_save(model, os_path, contents_manager, **kwargs):
    """Save a copy of notebook to the corresponding language source script.

    For example, when you save a `foo.ipynb` file, a corresponding `foo.py`
    python script will also be saved in the same directory.

    However, existing config files I found online (including the one written in
    the official documentation), will also create an `Untitile.txt` file when
    you create a new notebook, even if you have not pressed the "save" button.
    This is annoying because we usually will rename the notebook with a more
    meaningful name later, and now we have to rename the generated script file,
    too!

    Therefore we make a change here to filter out the newly created notebooks
    by checking their names. For a notebook which has not been given a name,
    i.e., its name is `Untitled.*`, the corresponding source script will not be
    saved. Note that the behavior also applies even if you manually save an
    "Untitled" notebook. The rationale is that we usually do not want to save
    scripts with the useless "Untitled" names.
    """
    # only process for notebooks
    if model["type"] != "notebook":
        return

    script_exporter = ScriptExporter(parent=contents_manager)
    base, __ = os.path.splitext(os_path)

    # do nothing if the notebook name ends with `Untitled[0-9]*`
    regex = re.compile(r"Untitled[0-9]*$")
    if regex.search(base):
        return

    script, resources = script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')

    log = contents_manager.log
    log.info("Saving script at /%s",
             to_api_path(script_fname, contents_manager.root_dir))

    with io.open(script_fname, "w", encoding="utf-8") as f:
        f.write(script)

c.FileContentsManager.post_save_hook = script_post_save

To use this script, you can add it to ~/.jupyter/jupyter_notebook_config.py :)

Note that you may need to restart the jupyter notebook / lab for it to work.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

What you have written in your sql string is a Timestamp not Date. You must convert it to Date or change type of database field to Timestamp for it to be seen correctly.

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

How to suppress binary file matching results in grep

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *

JavaScript file not updating no matter what I do

1.Clear browser cache in browser developer tools 2.Under Network tab – select Disable cache option 3.Restarted browser 4.Force reload Js file command+shift+R in mac   Make sure the fresh war is deployed properly on the Server side

Error: Java: invalid target release: 11 - IntelliJ IDEA

If building a project through a build system (Maven, Gradle etc..) works but IntelliJ show Invalid target release error, then do the following,

  1. Close IntelliJ

  2. Go to the directory of the project

  3. Delete the .idea/ directory

  4. Start IntelliJ with the project's directory

This will re-create the .idea/ directory and will no longer show the error.

NOTE: Any repository specific IntelliJ settings that you have added would be deleted when the .idea/ directory is deleted and they will be re-created with the defaults.

Using IS NULL or IS NOT NULL on join conditions - Theory question

You're doing a LEFT OUTTER JOIN which indicates that you want every tuple from the table on the LEFT of the statement regardless of it has a matching record in the RIGHT table. This being the case, your results are being pruned from the RIGHT table but you're ending up with the same results as if you didn't include the AND at all within the ON clause.

Performing the AND in the WHERE clause causes the prune to happen after the LEFT JOIN takes place.

How to check 'undefined' value in jQuery

when I am testing "typeof obj === undefined", the alert(typeof obj) returning object, even though obj is undefined. Since obj is type of Object its returning Object, not undefined.

So after hours of testing I opted below technique.

if(document.getElementById(obj) !== null){
//do...
}else{
//do...
}

I am not sure why the first technique didn't work.But I get done my work using this.

Detecting Windows or Linux?

Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0

public class OSValidator {

    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void main(String[] args) {

        System.out.println(OS);

        if (isWindows()) {
            System.out.println("This is Windows");
        } else if (isMac()) {
            System.out.println("This is Mac");
        } else if (isUnix()) {
            System.out.println("This is Unix or Linux");
        } else if (isSolaris()) {
            System.out.println("This is Solaris");
        } else {
            System.out.println("Your OS is not support!!");
        }
    }

    public static boolean isWindows() {
        return OS.contains("win");
    }

    public static boolean isMac() {
        return OS.contains("mac");
    }

    public static boolean isUnix() {
        return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
    }

    public static boolean isSolaris() {
        return OS.contains("sunos");
    }
    public static String getOS(){
        if (isWindows()) {
            return "win";
        } else if (isMac()) {
            return "osx";
        } else if (isUnix()) {
            return "uni";
        } else if (isSolaris()) {
            return "sol";
        } else {
            return "err";
        }
    }

}

How to redirect the output of print to a TXT file

Usinge the file argument in the print function, you can have different files per print:

print('Redirect output to file', file=open('/tmp/example.log', 'w'))

where does MySQL store database files?

Check your my.cnf file in your MySQL program directory, look for

[mysqld]
datadir=

The datadir is the location where your MySQL database is stored.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

For anyone using MySQL:

If you head into your PHPMYADMIN webpage and navigate to the table that has the foreign key you want to update, all you have to do is click the Relational view located in the Structure tab and change the On delete select menu option to Cascade.

Image shown below:

enter image description here

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

How to use Bootstrap 4 in ASP.NET Core

As others already mentioned, the package manager Bower, that was usually used for dependencies like this in application that do not rely on heavy client-side scripting, is on the way out and actively recommending to move to other solutions:

..psst! While Bower is maintained, we recommend yarn and webpack for new front-end projects!

So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.

Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.

But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.

In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csproj format and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.

This leaves us with a few options how to add our dependencies:

One-time installation

This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwroot folder simply contains a folder lib that contains the dependencies:

wwwroot folder contains lib folder with static dependencies

If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied once to the wwwroot folder so you can depend on them.

To do this, we can simply follow Bootstrap’s introduction and download the compiled files directly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does contain Popper.js though if we choose to use the bootstrap.bundle file later—which we will do. For jQuery, we can simply get a single “compressed, production” file from the download site (right-click the link and select "Save link as..." from the menu).

This leaves us with a few files which will simply extract and copy into the wwwroot folder. We can also make a lib folder to make it clearer that these are external dependencies:

wwwroot folder contains lib folder with our installed dependencies

That’s all we need, so now we just need to adjust our _Layout.cshtml file to include those dependencies. For that, we add the following block to the <head>:

<environment include="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>

And the following block at the very end of the <body>:

<environment include="Development">
    <script src="~/lib/js/jquery-3.3.1.js"></script>
    <script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
    <script src="~/lib/js/jquery-3.3.1.min.js"></script>
    <script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>

You can also just include the minified versions and skip the <environment> tag helpers here to make it a bit simpler. But that’s all you need to do to keep you starting.

Dependencies from NPM

The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I’ll use NPM.

To start off, we need to create a package.json file for our project, so we can specify our dependencies. To do this, we simply do that from the “Add New Item” dialog:

Add New Item: npm Configuration file

Once we have that, we need to edit it to include our dependencies. It should something look like this:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modules folder. So what is left to do is to get the files from there into our wwwroot folder. There are a few options to do that:

bundleconfig.json for bundling and minification

We can use one of the various ways to consume a bundleconfig.json for bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet package which automatically sets up a build task for this.

After installing that package, we need to create a bundleconfig.json at the root of the project with the following contents:

[
  {
    "outputFileName": "wwwroot/vendor.min.css",
    "inputFiles": [
      "node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
    "minify": { "enabled": false }
  },
  {
    "outputFileName": "wwwroot/vendor.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/popper.js/dist/umd/popper.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ],
    "minify": { "enabled": false }
  }
]

This basically configures which files to combine into what. And when we build, we can see that the vendor.min.css and vendor.js.css are created correctly. So all we need to do is to adjust our _Layouts.html again to include those files:

<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />

<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>

Using a task manager like Gulp

If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpack which is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulp and do the few necessary steps ourselves.

For that, we add a gulpfile.js into our project root, with the following contents:

const gulp = require('gulp');
const concat = require('gulp-concat');

const vendorStyles = [
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js",
];

gulp.task('build-vendor-css', () => {
    return gulp.src(vendorStyles)
        .pipe(concat('vendor.min.css'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor-js', () => {
    return gulp.src(vendorScripts)
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor', gulp.parallel('build-vendor-css', 'build-vendor-js'));

gulp.task('default', gulp.series('build-vendor'));

Now, we also need to adjust our package.json to have dependencies on gulp and gulp-concat:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

Finally, we edit our .csproj to add the following task which makes sure that our Gulp task runs when we build the project:

<Target Name="RunGulp" BeforeTargets="Build">
  <Exec Command="node_modules\.bin\gulp.cmd" />
</Target>

Now, when we build, the default Gulp task runs, which runs the build-vendor tasks, which then builds our vendor.min.css and vendor.min.js just like we did before. So after adjusting our _Layout.cshtml just like above, we can make use of jQuery and Bootstrap.

While the initial setup of Gulp is a bit more complicated than the bundleconfig.json one above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.

Conclusion

While this suddenly got a lot more complicated than with just using Bower, we also do gain a lot of control with those new options. For example, we can now decide what files are actually included within the wwwroot folder and how those exactly look like. And we also can use this to make the first moves into the client-side development world with Node which at least should help a bit with the learning curve.

Namespace not recognized (even though it is there)

Check to make sure that your project isn't set up to use the .NET Framework 4 Client Profile.

You can check/change this by right-clicking your project (not the solution), select Properties -> Application -> Target framework. The target framework is a dropdown on that page.

This is a problem in Visual Studio (I would even go so far as to call it a bug). AutoMapper requires assemblies that are excluded from the .NET Framework 4 Client Profile. Since your project is using that version of the framework it breaks.

A similar error will propagate to the build process when the .NET Framework version for the project you are referencing is higher than the project making the reference. i.e. A project targeting 4.5 that references a project targeting 4.5.1 will give you this same error.

There needs to be a better error message when this happens because there is no rational explanation as to why it would not build as the error message tells you to reference an assembly you have clearly referenced.

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

In my case the problem was that I used notifyDataSetChanged when amount of newly loaded data was less than initial data. This approach helped me:

adapter.notifyItemRangeChanged(0, newAmountOfData + 1);
adapter.notifyItemRangeRemoved(newAmountOfData + 1, previousAmountOfData);

ActionController::InvalidAuthenticityToken

Following Chrome Lighthouse recommendations for a faster application load, I have asynced my Javascript:

views/layout/application.html.erb

<%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload', async: true %>

This broke everything and got that Token error for my remote forms. Removing async: true fixed the problem.

Plot multiple lines (data series) each with unique color in R

Using @Arun dummy data :) here a lattice solution :

xyplot(val~x,type=c('l','p'),groups= variable,data=df,auto.key=T)

enter image description here

Python 3 Building an array of bytes

agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html

How do I pass variables and data from PHP to JavaScript?

I'll assume that the data to transmit is a string.

As other commenters have stated, AJAX is one possible solution, but the cons outweigh the pros: it has a latency and it is harder to program (it needs the code to retrieve the value both server- and client-side), when a simpler escaping function should suffice.

So, we're back to escaping. json_encode($string) works if you encode the source string as UTF-8 first in case it is not already, because json_encode requires UTF-8 data. If the string is in ISO-8859-1 then you can simply use json_encode(utf8_encode($string)); otherwise you can always use iconv to do the conversion first.

But there's a big gotcha. If you're using it in events, you need to run htmlspecialchars() on the result in order to make it correct code. And then you have to either be careful to use double quotes to enclose the event, or always add ENT_QUOTES to htmlspecialchars. For example:

<?php
    $myvar = "I'm in \"UTF-8\" encoding and I have <script>script tags</script> & ampersand!";
    // Fails:
    //echo '<body onload="alert(', json_encode($myvar), ');">';
    // Fails:
    //echo "<body onload='alert(", json_encode($myvar), ");'>";
    // Fails:
    //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar)), ");'>";

    // Works:
    //echo "<body onload='alert(", htmlspecialchars(json_encode($myvar), ENT_QUOTES), ");'>";
    // Works:
    echo '<body onload="alert(', htmlspecialchars(json_encode($myvar)), ');">';

    echo "</body>";

However, you can't use htmlspecialchars on regular JavaScript code (code enclosed in <script>...</script> tags). That makes use of this function prone to mistakes, by forgetting to htmlspecialchars the result when writing event code.

It's possible to write a function that does not have that problem, and can be used both in events and in regular JavaScript code, as long as you enclose your events always in single quotes, or always in double quotes. Here is my proposal, requiring them to be in double quotes (which I prefer):

<?php
    // Optionally pass the encoding of the source string, if not UTF-8
    function escapeJSString($string, $encoding = 'UTF-8')
    {
        if ($encoding != 'UTF-8')
            $string = iconv($encoding, 'UTF-8', $string);
        $flags = JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_SLASHES;
        $string = substr(json_encode($string, $flags), 1, -1);
        return "'$string'";
    }

The function requires PHP 5.4+. Example usage:

<?php
    $myvar = "I'm in \"UTF-8\" encoding and I have <script>script tags</script> & ampersand!";
    // Note use of double quotes to enclose the event definition!
    echo '<body onload="alert(', escapeJSString($myvar), ');">';
    // Example with regular code:
    echo '<script>alert(', escapeJSString($myvar), ');</script>';
    echo '</body>';

What does "The APR based Apache Tomcat Native library was not found" mean?

Had this problem as well. If you do have the libraries, but still have this error, it may be a configuration error. Your server.xml may be missing the following line:

 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

(Alternatively, it may be commented out). This <Listener>, like other listeners is a child of the top-level <Server>.

Without the <Listener> line, there's no attempt to load the APR library, so LD_LIBRARY_PATH and -Djava.library.path= settings are ignored.

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

ReactJS call parent method

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;

Negative regex for Perl string pattern match

Your regex says the following:

/^         - if the line starts with
(          - start a capture group
Clinton|   - "Clinton" 
|          - or
[^Bush]    - Any single character except "B", "u", "s" or "h"
|          - or
Reagan)   - "Reagan". End capture group.
/i         - Make matches case-insensitive 

So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:

Our president, George Bush
In the news today, pigs can fly
012-3123 33

You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:

if( ($string =~ m/^(Clinton|Reagan)/i) and
    ($string !~ m/^Bush/i) ) {
   print "$string\n";
}

As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".

However, it would be valid without the carets.

Is it possible to put a ConstraintLayout inside a ScrollView?

Try adding android:fillViewport="true" to the ScrollView.

Found the solution here: LinearLayout not expanding inside a ScrollView

Android Studio says "cannot resolve symbol" but project compiles

For those, who tried the accepted answer and have no success,

I tried also the accepted answer and did not work for me. After that, I updated my project with the repository and synchronized the project and the could not resolve warnings are gone.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

Catch multiple exceptions in one line (except block)

If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data
    return(received_data)

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred

NOTES:

  1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

  2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

Bower: ENOGIT Git is not installed or not in the PATH

I had the same problem and needed to restart the cmd - and the problem goes away.

Grep only the first match and stop

You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

grep -m 1 -r "Not caching" * | head -1

How to read data From *.CSV file using javascript?

I am using d3.js for parsing csv file. Very easy to use. Here is the docs.

Steps:

  • npm install d3-request

Using Es6;

import { csv } from 'd3-request';
import url from 'path/to/data.csv';

csv(url, function(err, data) {
 console.log(data);
})

Please see docs for more.

Update - d3-request is deprecated. you can use d3-fetch

Why does GitHub recommend HTTPS over SSH?

GitHub have changed their recommendation several times (example).

It appears that they currently recommend HTTPS because it is the easiest to set up on the widest range of networks and platforms, and by users who are new to all this.

There is no inherent flaw in SSH (if there was they would disable it) -- in the links below, you will see that they still provide details about SSH connections too:

  1. HTTPS is less likely to be blocked by a firewall.

    https://help.github.com/articles/which-remote-url-should-i-use/

    The https:// clone URLs are available on all repositories, public and private. These URLs work everywhere--even if you are behind a firewall or proxy.

  2. An HTTPS connection allows credential.helper to cache your password.

    https://help.github.com/articles/set-up-git

    Good to know: The credential helper only works when you clone an HTTPS repo URL. If you use the SSH repo URL instead, SSH keys are used for authentication. While we do not recommend it, if you wish to use this method, check out this guide for help generating and using an SSH key.

Using helpers in model: how do I include helper dependencies?

If you want to use a the my_helper_method inside a model, you can write:

ApplicationController.helpers.my_helper_method

How to change the link color in a specific class for a div CSS

smaller-size version:

#register a:link {color: #fff}

Convert tabs to spaces in Notepad++

CLR Tabs to Spaces plugin should be a good option. I have used it and it worked.

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

How to get name of dataframe column in pyspark?

You can get the names from the schema by doing

spark_df.schema.names

Printing the schema can be useful to visualize it as well

spark_df.printSchema()

How to save a new sheet in an existing excel file, using Pandas?

I would strongly recommend you work directly with openpyxl since it now supports Pandas DataFrames.

This allows you to concentrate on the relevant Excel and Pandas code.