Programs & Examples On #Lighting

Related to computer games' engines and 3d graphics software. For the use of both shadow and light in GUIs and for the use of lighting with respect to programs using hardware such as cameras, that requires code to control the lighting. Must be used with other relevant tags distinguishing the programming language and framework being used. e.g. unity 3d Not to be used with light, as is used in physics having wave and particle characteristics.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Also happened to me while trying to run the project inside of another directory.

Worked by using the root directory of the main project

Making a Bootstrap table column fit to content

Make a class that will fit table cell width to content

.table td.fit, 
.table th.fit {
    white-space: nowrap;
    width: 1%;
}

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

intellij incorrectly saying no beans of type found for autowired repository

I had this same issue when creating a Spring Boot application using their @SpringBootApplication annotation. This annotation represents @Configuration, @EnableAutoConfiguration and @ComponentScan according to the spring reference.

As expected, the new annotation worked properly and my application ran smoothly but, Intellij kept complaining about unfulfilled @Autowire dependencies. As soon as I changed back to using @Configuration, @EnableAutoConfiguration and @ComponentScan separately, the errors ceased. It seems Intellij 14.0.3 (and most likely, earlier versions too) is not yet configured to recognise the @SpringBootApplication annotation.

For now, if the errors disturb you that much, then revert back to those three separate annotations. Otherwise, ignore Intellij...your dependency resolution is correctly configured, since your test passes.

Always remember...

Man is always greater than machine.

Xamarin.Forms ListView: Set the highlight color of a tapped item

The easiest way to accomplish this on android is by adding the following code to your custom style :

@android:color/transparent

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

How can I include null values in a MIN or MAX?

Use IsNull

SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp 
GROUP BY recordid

I've modified MIN in the second instruction to MAX

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

Try creating a handler for select event on those elements and in the handler you can clear the selection.

Take a look at this:

Clear Text Selection with JavaScript

It's an example of clearing the selection. You'd only need to modify it to work only on the specific element that you need.

Comparing two dataframes and getting the differences

Since pandas >= 1.1.0 we have DataFrame.compare and Series.compare.

Note: the method can only compare identically-labeled DataFrame objects, this means DataFrames with identical row and column labels.

df1 = pd.DataFrame({'A': [1, 2, 3],
                    'B': [4, 5, 6],
                    'C': [7, np.NaN, 9]})

df2 = pd.DataFrame({'A': [1, 99, 3],
                    'B': [4, 5, 81],
                    'C': [7, 8, 9]})

   A  B    C
0  1  4  7.0
1  2  5  NaN
2  3  6  9.0 

    A   B  C
0   1   4  7
1  99   5  8
2   3  81  9
df1.compare(df2)

     A          B          C      
  self other self other self other
1  2.0  99.0  NaN   NaN  NaN   8.0
2  NaN   NaN  6.0  81.0  NaN   NaN

install beautiful soup using pip

import os

os.system("pip install beautifulsoup4")

or

import subprocess

exe = subprocess.Popen("pip install beautifulsoup4")

exe_out = exe.communicate()

print(exe_out)

Why is Visual Studio 2013 very slow?

I too have struggled a bit with bad performance in Visual Studio 2013 (Premium). Pretty much the same issues as TS had. Slow navigation, scrolling, building... just about everything. Luckily I have manage to solve my own problem by disabling Synchronized Settings in Visual Studio. Go to menu ToolsOptionsEnvironment-Synchronized Settings and remove this option by unchecking the checkbox.

Disable Synchronized Settings

Android button background color

Just use a MaterialButton and the app:backgroundTint attribute:

<MaterialButton
  app:backgroundTint="@color/my_color_selector"

enter image description here

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

Preventing an image from being draggable or selectable without using JS

A generic solution especially for Windows Edge browser (as the -ms-user-select: none; CSS rule doesn't work):

window.ondragstart = function() {return false}

Note: This can save you having to add draggable="false" to every img tag when you still need the click event (i.e. you can't use pointer-events: none), but don't want the drag icon image to appear.

Reference - What does this error mean in PHP?

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

First and foremost:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result of mysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned by mysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Other mysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

PyCharm shows unresolved references error for valid code

In my case the inspection error shows up due to a very specific case of python code. A min function that contains two numpy functions and two list accesses makes my code inspection give this kind of errors.

Removing the 'd=0' line in the following example gives an unresolved reference error as expected, but readding doesn't make the error go away for the code inspector. I can still execute the code without problems afterwards.

import numpy as np
def strange(S, T, U, V):
    d = 0
    print min(np.abs(S[d]), np.abs(T[d]), U[d], V[d])

Clearing caches and reloading list of paths doesn't work. Only altering the code with one of the following example patches does work:

  • Another ordering of the 'min' parameters: schematically S U T V but not S T U V or T S U V
  • Using a method instead of the function: S[d].abs() instead of np.abs(S[d])
  • Using the built-in abs() function
  • Adding a number to a parameter of choice: U[d] + 0.

Rules for C++ string literals escape character

Control characters:

(Hex codes assume an ASCII-compatible character encoding.)

  • \a = \x07 = alert (bell)
  • \b = \x08 = backspace
  • \t = \x09 = horizonal tab
  • \n = \x0A = newline (or line feed)
  • \v = \x0B = vertical tab
  • \f = \x0C = form feed
  • \r = \x0D = carriage return
  • \e = \x1B = escape (non-standard GCC extension)

Punctuation characters:

  • \" = quotation mark (backslash not required for '"')
  • \' = apostrophe (backslash not required for "'")
  • \? = question mark (used to avoid trigraphs)
  • \\ = backslash

Numeric character references:

  • \ + up to 3 octal digits
  • \x + any number of hex digits
  • \u + 4 hex digits (Unicode BMP, new in C++11)
  • \U + 8 hex digits (Unicode astral planes, new in C++11)

\0 = \00 = \000 = octal ecape for null character

If you do want an actual digit character after a \0, then yes, I recommend string concatenation. Note that the whitespace between the parts of the literal is optional, so you can write "\0""0".

Eclipse does not highlight matching variables

I just unchecked all, applied, checked all again, applied and it worked :) hopefully helps others.

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.

jquery datatables default sort

I had this problem too. I had used stateSave option and that made this problem.
Remove this option and problem is solved.

Disable hover effects on mobile browsers

I really wanted a pure css solution to this myself, since sprinkling a weighty javascript solution around all of my views seemed like an unpleasant option. Finally found the @media.hover query, which can detect "whether the primary input mechanism allows the user to hover over elements." This avoids touch devices where "hovering" is more of an emulated action than a direct capability of the input device.

So for example, if I have a link:

<a href="/" class="link">Home</a>

Then I can safely style it to only :hover when the device easily supports it with this css:

@media (hover: hover) {
  .link:hover { /* hover styles */ }
}

While most modern browsers support interaction media feature queries, some popular browsers such as IE and Firefox do not. In my case this works fine, since I only intended to support Chrome on desktop and Chrome and Safari on mobile.

Set default syntax to different filetype in Sublime Text 2

You can turn on syntax highlighting based on the contents of the file.

For example, my Makefiles regardless of their extension the first line as follows:

#-*-Makefile-*- vim:syntax=make

This is typical practice for other editors such as vim.

However, for this to work you need to modify the Makefile.tmLanguage file.

  1. Find the file (for Sublime Text 3 in Ubuntu) at:

    /opt/sublime_text/Packages/Makefile.sublime-package
    

Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.

  1. Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".

    ...
    <key>fileTypes</key>
    <array>
        <string>GNUmakefile</string>
        <string>makefile</string>
        <string>Makefile</string>
        <string>OCamlMakefile</string>
        <string>make</string>
    </array>
    
    <key>firstLineMatch</key>
    <string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
    
  2. Place the modified Makefile.tmLanguage in the User settings directory:

    ~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
    

All the files matching the first line rule should turn the syntax highlighting on when opened.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

you forgot for Java Desktop Aplication based on JSR296 as built-in Swing Framework in NetBeans

excluding AWT and JavaFX are all of your desribed frameworks are based on Swing, if you'll start with Swing then you'd be understand (clearly) for all these Swing's (Based Frameworks)

ATW, SWT (Eclipse), Java Desktop Aplication(Netbeans), SwingX, JGoodies

all there frameworks (I don't know something more about JGoodies) incl. JavaFX haven't long time any progress, lots of Swing's Based Frameworks are stoped, if not then without newest version

just my view - best of them is SwingX, but required deepest knowledge about Swing,

Look and Feel for Swing's Based Frameworks

Clearing coverage highlighting in Eclipse

I found a workaround over on GitHub: https://github.com/jmhofer/eCobertura/issues/8

For those who don't want to click the link, here's the text of the comment:

Good workaround: Create a run configuration with a filter, that excludes everything ("*") and let it run just a single test. Name it "Undo coverage".

I did this and it worked quite well in Eclipse Juno.

Credit for this goes to UsulSK.

UIView with rounded corners and drop shadow?

This worked for me. Trick was to move the background color from the main view to the layer.

CALayer *layer = view.layer;
layer.cornerRadius = 15.0f;
layer.masksToBounds = NO;

layer.shadowOffset = CGSizeMake(0, 3);
layer.shadowColor = [[UIColor blackColor] CGColor];
layer.shadowRadius = 2.0f;
layer.shadowOpacity = 0.35f;
layer.shadowPath = [[UIBezierPath bezierPathWithRoundedRect:layer.bounds cornerRadius:layer.cornerRadius] CGPath];

CGColorRef  bColor = view.backgroundColor.CGColor;
view.backgroundColor = nil;
layer.backgroundColor =  bColor ;

Color text in terminal applications in UNIX

Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main() {
  printf(RED "red\n"     RESET);
  printf(GRN "green\n"   RESET);
  printf(YEL "yellow\n"  RESET);
  printf(BLU "blue\n"    RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n"    RESET);
  printf(WHT "white\n"   RESET);

  return 0;
}

This program gives the following output:

enter image description here


Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output

Inserting code in this LaTeX document with indentation

A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:

\documentclass[11pt]{article}  
\usepackage{pythonhighlight}

\begin{document}

The following is some Python code

\begin{python}
# A comment
x = [5, 7, 10]
y = 0

for num in x:
    y += num
    
print(y)
\end{python}

\end{document}

which looks like: enter image description here

Unfortunately, this only works for Python.

How to reset / remove chrome's input highlighting / focus border?

I had to do all of the following to completely remove it:

outline-style: none;
box-shadow: none;
border-color: transparent;

Example:

_x000D_
_x000D_
button {_x000D_
  border-radius: 20px;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.no-focusborder:focus {_x000D_
  outline-style: none;_x000D_
  box-shadow: none;_x000D_
  border-color: transparent;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
}
_x000D_
<p>Click in the white space, then press the "Tab" key.</p>_x000D_
<button>Button 1 (unchanged)</button>_x000D_
<button class="no-focusborder">Button 2 (no focus border, custom focus indicator to show focus is present but the unwanted highlight is gone)</button>_x000D_
<br/><br/><br/><br/><br/><br/>
_x000D_
_x000D_
_x000D_

How to make links in a TextView clickable?

I added this line to the TextView: android:autoLink="web"
Below is an example of usage in a layout file.

layout.xml sample

    <TextView
        android:id="@+id/txtLostpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:autoLink="email"
        android:gravity="center"
        android:padding="20px"
        android:text="@string/lostpassword"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/txtDefaultpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:autoLink="web"
        android:gravity="center"
        android:padding="20px"
        android:text="@string/defaultpassword"
        android:textAppearance="?android:attr/textAppearanceSmall" />

string.xml

<string name="lostpassword">If you lost your password please contact <a href="mailto:[email protected]?Subject=Lost%20Password" target="_top">[email protected]</a></string>

<string name="defaultpassword">User Guide <a href="http://www.cleverfinger.com.au/user-guide/">http://www.cleverfinger.com.au/user-guide/</a></string>

Highlighting Text Color using Html.fromHtml() in Android?

Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

Override browser form-filling and input highlighting with HTML/CSS

You can also change the name attribute of your form elements to be something generated so that the browser won't keep track of it. HOWEVER firefox 2.x+ and google chrome seems to not have much problems with that if the request url is identical. Try basically adding a salt request param and a salt field name for the sign-up form.

However I think autocomplete="off" is still top solution :)

How do I prevent 'git diff' from using a pager?

For a quick-and-dirty script I wrote, I did it this way:

PAGER=cat git diff ...

UITableView Cell selected Color?

Swift 3: for me it worked when you put it in the cellForRowAtIndexPath: method

let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view

How do I install a plugin for vim?

Make sure that the actual .vim file is in ~/.vim/plugin/

Is it possible to have multiple styles inside a TextView?

Me Too

How about using some beautiful markup with Kotlin and Anko -

import org.jetbrains.anko.*
override fun onCreate(savedInstanceState: Bundle?) {
    title = "Created with Beautiful Markup"
    super.onCreate(savedInstanceState)

    verticalLayout {
        editText {
            hint = buildSpanned {
                append("Italic, ", Italic)
                append("highlighted", backgroundColor(0xFFFFFF00.toInt()))
                append(", Bold", Bold)
            }
        }
    }
}

Created with Beautiful Markup

Go to Matching Brace in Visual Studio?

If for some reason this is NOT working for you, something may have messed up your keyboard bindings (it didn't work for me). You can re-enable the binding easy enough though - at least so I thought:

I tried this procedure:

  • Go to menu Tools -> Options -> Environment -> Keyboard
  • Scroll to, or search for the command Edit.GotoBrace
  • Assign the desired shortcut (mine was empty, so I put in CTRL    + ])
  • Be sure to click the "Assign Button"

I tried it, and it still didn't work. I restarted Visual Studio, and it still didn't work - well it ONLY worked for .cs files, but I need it to work for .vb files and text files, and...well ALL files!

Bash script plugin for Eclipse?

I tried ShellEd, but it wouldn't recognize any of my shell scripts, even when I restarted eclipse. I added the ksh interpreter and made it the default, but it made no diffence.

Finally, I closed the tab that was open and displaying a ksh file, then re-opened it. That made it work correctly. After having used it for a while, I can also recommend it.

Selecting text in an element (akin to highlighting with your mouse)

Have a look at the Selection object (Gecko engine) and the TextRange object (Trident engine.) I don't know about any JavaScript frameworks that have cross-browser support for this implemented, but I've never looked for it either, so it's possible that even jQuery has it.

Colorized grep -- viewing the entire file with highlighted matches

If you want highlight several patterns with different colors see this bash script.

Basic usage:

echo warn error debug info 10 nil | colog

You can change patterns and colors while running pressing one key and then enter key.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

There is a history in C of doing things like:

while (*a++ = *b++);

to copy a string, perhaps this is the source of the excessive trickery he is referring to.

And there's always the question of what

++i = i++;

or

i = i++ + ++i;

actually do. It's defined in some languages, and in other's there's no guarantee what will happen.

Those examples aside, I don't think there's anything more idiomatic than a for loop that uses ++ to increment. In some cases you could get away with a foreach loop, or a while loop that checked a different condtion. But contorting your code to try and avoid using incrementing is ridiculous.

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

Display JSON as HTML

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. To get an idea of what SyntaxHighlighter is capable of, have a look at the demo page.

How to disable text selection highlighting

For Internet Explorer in addition, you need to add pseudo class focus (.ClassName:focus) and outline-style: none.

.ClassName,
.ClassName:focus {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    outline-style: none; /* Internet Explorer  */
}

Vim clear last search highlighting

I found this answer years ago on vim.org:

Add the following to your .vimrc:

"This unsets the "last search pattern" register by hitting return
nnoremap <CR> :noh<CR><CR>

Thus, after your search, just hit return again in command mode, and the highlighting disappears.

How do you display code snippets in MS Word preserving format and syntax highlighting?

If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!

Pretty printing XML with javascript

If you are looking for a JavaScript solution just take the code from the Pretty Diff tool at http://prettydiff.com/?m=beautify

You can also send files to the tool using the s parameter, such as: http://prettydiff.com/?m=beautify&s=https://stackoverflow.com/

LaTeX package for syntax highlighting of code in various languages

I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:

listing package

The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.

Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.

The following code

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

produces the following image:

enter image description here

minted package

The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with

python --version

and you can install pygments with

sudo apt-get install python-pygments

Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this

pdflatex -shell-escape yourfile.tex

If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.

The following code

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}{html}
    <!DOCTYPE html>
    <html>
       <head>
           <title>Hello</title>
       </head>

       <body>Hello</body>
    </html>
\end{minted}
\end{document}

produces the following image:

enter image description here

How To Format A Block of Code Within a Presentation?

Check out http://codepad.org. It probably won't solve the poster's problem; but, I think it will be of use to others who read this article.

Tips for using Vim as a Java IDE?

Use vim. ^-^ (gVim, to be precise)

You'll have it all (with some plugins).

Btw, snippetsEmu is a nice tool for coding with useful snippets (like in TextMate). You can use (or modify) a pre-made package or make your own.

What is in your .vimrc?

Use the first available 'tags' file in the directory tree:

:set tags=tags;/

Left and right are for switching buffers, not moving the cursor:

map <right> <ESC>:bn<RETURN>
map <left> <ESC>:bp<RETURN>

Disable search highlighting with a single keypress:

map - :nohls<cr>

How do you make Vim unhighlight what you searched for?

Also, if you want to have a toogle and be sure that the highlight will be reactivate for the next time you search something, you can use this

nmap <F12> :set hls!<CR>
nnoremap / :set hls<CR>/

C++ IDE for Linux?

Just a quick follow up for this question...

It's been a month since I started using Vim as my main 'GUI' tool for programming C++ in Linux. At first the learning curve was indeed a bit steep but after a while and with the right options turned on and scripts running I really got the hang of it!

I love the way how you can shape Vim to suite your needs; just add/change key mappings and Vim is turned into a highly productive 'IDE'.

The toolchain to build and compile a C++ program on Linux is also really intuitive. make and g++ are the tools you'll use.

The debugger ddd is however not really that good, but maybe that's because I haven't had the time to master it properly.

So to anyone who is, or was looking for a good C++ IDE in Linux, just like I was, your best bet lays with the standard available tools in Linux itself (Vim, g++, ddd) and you should really at least try to use them, before looking for sonething else...

Last but not least, I really want to thank konrad for his answer here, It really helped me find my way in the Linux development environment, thank you!

I'm also not closing this question, so people can still react or maybe even add new suggestions or additions to the already really nice answers...

How to draw a filled triangle in android canvas?

private void drawArrows(Point[] point, Canvas canvas, Paint paint) {

    float [] points  = new float[8];             
    points[0] = point[0].x;      
    points[1] = point[0].y;      
    points[2] = point[1].x;      
    points[3] = point[1].y;         
    points[4] = point[2].x;      
    points[5] = point[2].y;              
    points[6] = point[0].x;      
    points[7] = point[0].y;

    canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
    Path path = new Path();
    path.moveTo(point[0].x , point[0].y);
    path.lineTo(point[1].x,point[1].y);
    path.lineTo(point[2].x,point[2].y);
    canvas.drawPath(path,paint);

}

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

Sounds like your initialized AudioElement class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress in state.

You can either initialize the AudioElement class object in a new React component or just convert that class to a React component.

class MyAudioPlayer extends React.Component {
  constructor(props) {
    super(props);

    this.player = new AudioElement('test.mp3');

    this.player.audio.ontimeupdate = this.updateProgress;
  }

  updateProgress () {
    // Dispatch action to reducer with updated progress.
    // You might want to actually send the current time and do the
    // calculation from within the reducer.
    this.props.updateProgressAction();
  }

  render () {
    // Render the audio player controls, progress bar, whatever else
    return <p>Progress: {this.props.progress}</p>;
  }
}

class MyContainer extends React.Component {
   render() {
     return <MyAudioPlayer updateProgress={this.props.updateProgress} />
   }
}

function mapStateToProps (state) { return {}; }

return connect(mapStateToProps, {
  updateProgressAction
})(MyContainer);

Note that the updateProgressAction is automatically wrapped with dispatch so you don't need to call dispatch directly.

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

How do you attach and detach from Docker's process?

I'm on a Mac, and for some reason, Ctrl-p Ctrl-q would only work if I also held Shift

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

how to pass command line arguments to main method dynamically

Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab

enter image description here

Why can't I define a static method in a Java interface?

Commenting EDIT: As of Java 8, static methods are now allowed in interfaces.

It is right, static methods since Java 8 are allowed in interfaces, but your example still won't work. You cannot just define a static method: you have to implement it or you will obtain a compilation error.

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

How to return temporary table from stored procedure

What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.

An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.

You can find an example here

How to properly use jsPDF library

This is finally what did it for me (and triggers a disposition):

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

how to get program files x86 env variable?

On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

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

1 To 1 Relationships in SQL are made by merging the field of both table in one !

I know you can split a Table in two entity with a 1 to 1 relation. Most of time you use this because you want to use lazy loading on "heavy field of binary data in a table".

Exemple: You have a table containing pictures with a name column (string), maybe some metadata column, a thumbnail column and the picture itself varbinary(max). In your application, you will certainly display first only the name and the thumbnail in a collection control and then load the "full picture data" only if needed.

If it is what your are looking for. It is something called "table splitting" or "horizontal splitting".

https://visualstudiomagazine.com/articles/2014/09/01/splitting-tables.aspx

Limiting the number of characters in a JTextField

Since the introduction of the DocumentFilter in Java 1.4, the need to override Document has been lessoned.

DocumentFilter provides the means for filtering content been passed to the Document before it actually reaches it.

These allows the field to continue to maintain what ever document it needs, while providing the means to filter the input from the user.

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class LimitTextField {

    public static void main(String[] args) {
        new LimitTextField();
    }

    public LimitTextField() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTextField pfPassword = new JTextField(20);
                ((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(pfPassword);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class LimitDocumentFilter extends DocumentFilter {

        private int limit;

        public LimitDocumentFilter(int limit) {
            if (limit <= 0) {
                throw new IllegalArgumentException("Limit can not be <= 0");
            }
            this.limit = limit;
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int currentLength = fb.getDocument().getLength();
            int overLimit = (currentLength + text.length()) - limit - length;
            if (overLimit > 0) {
                text = text.substring(0, text.length() - overLimit);
            }
            if (text.length() > 0) {
                super.replace(fb, offset, length, text, attrs); 
            }
        }

    }

}

Could not find module FindOpenCV.cmake ( Error in configuration process)

If you are on Linux, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)

export OpenCV_DIR=<path_of_opencv>

How to detect if user select cancel InputBox VBA Excel

The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.

For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:

Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then  'I also tried with sRange.address and vbNullString
    MsgBox ("Cancel pressed!")
    Exit Sub
End If
    MsgBox ("Your custom range is " & sRange.Address)
End Sub

The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:

Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
    "Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
    MsgBox ("Cancel pressed")
End Sub

So, the question is how to detect either an error or StrPtr()=0 with an If statement?

Python: how to print range a-z?

Get a list with the desired values

small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))

or

import string
string.letters
string.uppercase
string.digits

This solution uses the ASCII table. ord gets the ascii value from a character and chr vice versa.

Apply what you know about lists

>>> small_letters = map(chr, range(ord('a'), ord('z')+1))

>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n

>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y

>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m

>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

Error: Cannot invoke an expression whose type lacks a call signature

Add a type to your variable and then return.

Eg:

const myVariable : string [] = ['hello', 'there'];

const result = myVaraible.map(x=> {
  return
  {
    x.id
  }
});

=> Important part is adding the string[] type etc:

SyntaxError: Unexpected Identifier in Chrome's Javascript console

copy this line and replace in your project

var myNewString = myOldString.replace ("username", visitorName);

there is a simple problem with coma (,)

How can I decode HTML characters in C#?

It is also worth mentioning that if you're using HtmlAgilityPack like I was, you should use HtmlAgilityPack.HtmlEntity.DeEntitize(). It takes a string and returns a string.

Window.open and pass parameters by post method

Even though I am 3 years late, but to simplify Guffa's example, you don't even need to have the form on the page at all:

$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">
       ...
   </form>').submit();

Edited:

$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">
       ...
   </form>').appendTo('body').submit().remove();

Maybe a helpful tip for someone :)

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

How to count how many values per level in a given factor?

Using plyr package:

library(plyr)

count(mydf$V1)

It will return you a frequency of each value.

Django development IDE

Now you can also use Visual Studio 2010. Here's how:

  • Download and install Python Tools for Visual Studio.
  • Create a new project from existing code (menu File ? New ? Project From Existing Code...)
  • Specify your Django project folder and use the defaults.
  • Right-click on manage.py and choose Set as Startup File.
  • In your project properties Debug tab, add "runserver" in Script Arguments.
  • You can set break points, and attach to the Python process for debugging. If you want to debug without having to "attach to process," use "runserver --noreload" in your script arguments. However, the "--noreload" means you'll have to stop and restart the Django development web server manually (to recognize your code changes).

This is a nice setup if you already use Visual Studio.

Python Tools has been updated. It has built in support for Django now.

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

This problem occurs when you already had MySQL installed on your machine or in case you have changed the post number of the MySql service which is 3306(Default). In order to solve this, you have to tell the phpMyAdmin to look for another port instead of 3306. To do so go to C:\xampp\phpMyAdmin(default location) and open Config.inc and add this line $cfg['Servers'][$i]['port'] = '3307'; after $cfg['Servers'][$i]['AllowNoPassword'] = true; Restart the services and now it should work.

What is the backslash character (\\)?

\ is used as for escape sequence in many programming languages, including Java.

If you want to

  • go to next line then use \n or \r,
  • for tab use \t
  • likewise to print a \ or " which are special in string literal you have to escape it with another \ which gives us \\ and \"

How to control the line spacing in UILabel

Starting from iOS 6 you can set an attributed string to the UILabel. Check the following :

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];

label.attributedText = attributedString;

find difference between two text files with one item per line

an awk answer:

awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2

Interview question: Check if one string is a rotation of other string

C#:

s1 == null && s2 == null || s1.Length == s2.Length && (s1 + s1).Contains(s2)

dyld: Library not loaded: @rpath/libswiftCore.dylib

In my case,

I have set @executable_path/Frameworks

But I have to also set "Framework search paths"

$(PROJECT_DIR)/Frameworks

change as recursive

Which works for me.

Why Is `Export Default Const` invalid?

const is like let, it is a LexicalDeclaration (VariableStatement, Declaration) used to define an identifier in your block.

You are trying to mix this with the default keyword, which expects a HoistableDeclaration, ClassDeclaration or AssignmentExpression to follow it.

Therefore it is a SyntaxError.


If you want to const something you need to provide the identifier and not use default.

export by itself accepts a VariableStatement or Declaration to its right.


AFAIK the export in itself should not add anything to your current scope.


The following is fineexport default Tab;

Tab becomes an AssignmentExpression as it's given the name default ?

export default Tab = connect( mapState, mapDispatch )( Tabs ); is fine

Here Tab = connect( mapState, mapDispatch )( Tabs ); is an AssignmentExpression.

How to add a footer to the UITableView?

instead of

self.theTable.tableFooterView = tableFooter;

try

[self.theTable.tableFooterView addSubview:tableFooter];

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

How do I use Safe Area Layout programmatically?

Use UIWindow or UIView's safeAreaInsets .bottom .top .left .right

// #available(iOS 11.0, *)
// height - UIApplication.shared.keyWindow!.safeAreaInsets.bottom

// On iPhoneX
// UIApplication.shared.keyWindow!.safeAreaInsets.top =  44
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 34

// Other devices
// UIApplication.shared.keyWindow!.safeAreaInsets.top =  0
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 0

// example
let window = UIApplication.shared.keyWindow!
let viewWidth = window.frame.size.width
let viewHeight = window.frame.size.height - window.safeAreaInsets.bottom
let viewFrame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
let aView = UIView(frame: viewFrame)
aView.backgroundColor = .red
view.addSubview(aView)
aView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Jackson Vs. Gson

Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

  • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
  • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
  • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
  • Can use any constructors (or static factory methods), not just default constructor
  • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
  • Out-of-box JAX-RS support
  • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
  • Ability to force static (declared) type handling for output
  • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
  • Integrated support for binary content (base64 to/from JSON Strings)

Calculate average in java

This

for (int i = 0; i<args.length -1; ++i)
    count++;

basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?

Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?

Using os.walk() to recursively traverse directories in Python

Recursive walk through a directory where you get ALL files from all dirs in the current directory and you get ALL dirs from the current directory - because codes above don't have a simplicity (imho):

for root, dirs, files in os.walk(rootFolderPath):
    for filename in files:
        doSomethingWithFile(os.path.join(root, filename))
    for dirname in dirs:
        doSomewthingWithDir(os.path.join(root, dirname))

"Least Astonishment" and the Mutable Default Argument

The solutions here are:

  1. Use None as your default value (or a nonce object), and switch on that to create your values at runtime; or
  2. Use a lambda as your default parameter, and call it within a try block to get the default value (this is the sort of thing that lambda abstraction is for).

The second option is nice because users of the function can pass in a callable, which may be already existing (such as a type)

How do I get the parent directory in Python?

os.path.split(os.path.abspath(mydir))[0]

Run command on the Ansible host

I've found a couple other ways you can write these which are a bit more readable IMHO.

- name: check out a git repository
  local_action: 
    module: git
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

OR

- name: check out a git repository
  local_action: git
  args:
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

How to append a char to a std::string?

y += d;

I would use += operator instead of named functions.

In-place edits with sed on OS X

sed -i -- "s/https/http/g" file.txt

Resizing an iframe based on content

Finally I found some other solution for sending data to parent website from iframe using window.postMessage(message, targetOrigin);. Here I explain How I did.

Site A = http://foo.com Site B = http://bar.com

SiteB is loading inside the siteA website

SiteB website have this line

window.parent.postMessage("Hello From IFrame", "*"); 

or

window.parent.postMessage("Hello From IFrame", "http://foo.com");

Then siteA have this following code

// Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];


var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child IFrame window
eventer(messageEvent, function (e) {
   alert(e.data);
   // Do whatever you want to do with the data got from IFrame in Parent form.
}, false); 

If you want to add security connection you can use this if condition in eventer(messageEvent, function (e) {})

if (e.origin == 'http://iframe.example.com') {
    alert(e.data); 
    // Do whatever you want to do with the data got from IFrame in Parent form.
}

For IE

Inside IFrame:

 window.parent.postMessage('{"key":"value"}','*');

Outside:

 eventer(messageEvent, function (e) {
   var data = jQuery.parseJSON(e.data);
   doSomething(data.key);
 }, false);

convert float into varchar in SQL server without scientific notation

Casting or converting to VARCHAR(MAX) or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.

What did work was STR().

start/play embedded (iframe) youtube-video on click of an image

You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

Map a 2D array onto a 1D array

As other have said C maps in row order

   #include <stdio.h>

   int main(int argc, char **argv) {
   int i, j, k;
   int arr[5][3];
   int *arr2 = (int*)arr;

       for (k=0; k<15; k++) {
          arr2[k] = k;
          printf("arr[%d] = %2d\n", k, arr2[k]);
       }

       for (i=0; i<5; i++) {
         for (j=0; j< 3; j++) {
            printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
         }
       } 
    } 

Output:

arr[0] =  0
arr[1] =  1
arr[2] =  2
arr[3] =  3
arr[4] =  4
arr[5] =  5
arr[6] =  6
arr[7] =  7
arr[8] =  8
arr[9] =  9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] =  0
arr2[0][1] =  1
arr2[0][2] =  2
arr2[1][0] =  3
arr2[1][1] =  4
arr2[1][2] =  5
arr2[2][0] =  6
arr2[2][1] =  7
arr2[2][2] =  8
arr2[3][0] =  9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14

jQuery add class .active on menu

Setting the active menu, they have the many ways to do that. Now, I share you a way to set active menu by CSS.

    <a href="index.php?id=home">Home</a>
    <a href="index.php?id=news">News</a>
    <a href="index.php?id=about">About</a>

Now, you only set $_request["id"] == "home" thì echo "class='active'" , then we can do same with others.

<a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
<a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
<a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>

I think it is useful with you.

Best practices to test protected methods with PHPUnit

You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

class Foo {
  protected function stuff() {
    // secret stuff, you want to test
  }
}

class SubFoo extends Foo {
  public function exposedStuff() {
    return $this->stuff();
  }
}

Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

How to search a Git repository by commit message?

This:

git log --oneline --grep='Searched phrase'

or this:

git log --oneline --name-status --grep='Searched phrase'

commands work best for me.

Catching access violation exceptions?

Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.

> man signal

     11    SIGSEGV      create core image    segmentation violation

Writing to a NULL pointer is probably going to cause a SIGSEGV signal

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

Is there a way to make HTML5 video fullscreen?

Firefox 3.6 has a full screen option for HTML5 video's, right-click on the video and select 'full screen'.

The latest Webkit nightlies also support full screen HTML5 video, try the Sublime player with the latest nightly and hold Cmd / Ctrl while selecting the full screen option.

I guess Chrome / Opera will also support something like this. Hopefully IE9 will also support full screen HTML5 video.

How do I delete everything below row X in VBA/Excel?

Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents (or .Clear). The reason you might want to use this method instead of .Delete is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF. This method will preserve formula references to the cleared cells.

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

What's the syntax to import a class in a default package in Java?

It is not a compilation error at all! You can import a default package to a default package class only.

If you do so for another package, then it shall be a compilation error.

Removing All Items From A ComboBox?

I could not get clear to work. (Mac Excel) but this does.

ActiveSheet.DropDowns("CollectionComboBox").RemoveAllItems

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop

```

Most recent previous business day in Python

timeboard package does this.

Suppose your date is 04 Sep 2017. In spite of being a Monday, it was a holiday in the US (the Labor Day). So, the most recent business day was Friday, Sep 1.

>>> import timeboard.calendars.US as US
>>> clnd = US.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 1)

In UK, 04 Sep 2017 was the regular business day, so the most recent business day was itself.

>>> import timeboard.calendars.UK as UK
>>> clnd = UK.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 4)

DISCLAIMER: I am the author of timeboard.

Eloquent ->first() if ->exists()

get returns Collection and is rather supposed to fetch multiple rows.

count is a generic way of checking the result:

$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user

// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException

// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users

Jenkins Host key verification failed

issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).

Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to set selected item of Spinner by value, not by position?

you have to pass your custom adapter with position like REPEAT[position]. and it works properly.

php check if array contains all array values from another array

I think you're looking for the intersect function

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

array_intersect() returns an array containing all values of array1 that are present in all the arguments. Note that keys are preserved.

http://www.php.net/manual/en/function.array-intersect.php

Converting year and month ("yyyy-mm" format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

How to detect scroll direction

This one deserves an update - nowadays we have the wheel event :

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
_x000D_
 var delta = e.originalEvent.deltaY;_x000D_
_x000D_
 if (delta > 0) $('body').text('down');_x000D_
 else $('body').text('up');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Support has been pretty good on modern browsers for quite a while already :

  • Chrome 31+
  • Firefox 17+
  • IE9+
  • Opera 18+
  • Safari 7+

https://developer.mozilla.org/en-US/docs/Web/Events/wheel

If deeper browser support is required, probably best to use mousewheel.js instead of messing about :

https://plugins.jquery.com/mousewheel/

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
$(window).mousewheel(function(turn, delta) {_x000D_
_x000D_
 if (delta > 0) $('body').text('up');_x000D_
 else $('body').text('down');_x000D_
_x000D_
 return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
  font-size: 22px;_x000D_
  text-align: center;_x000D_
  color: white;_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
_x000D_
_x000D_
_x000D_

What is a method group in C#?

A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".

It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.

Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

To remotely capture http or https traffic with charles you will need to do the following:

HOST - Machine running Charles and hosting the proxy CLIENT – User’s machine generating the traffic you will capture

Host Machine

  1. Install fully licensed charles version
  2. Proxy -> Proxy Settings -> check “Enable Transparent HTTP Proxying”
  3. Proxy -> SSL Proxying Settings -> check “enable SSL Proxying”
  4. Proxy -> SSL Proxying Settings -> click Add button and input * in both fields
  5. Proxy -> Access Control Settings -> Add your local subnet (ex: 192.168.2.0/24) to authorize all machines on your local network to use the proxy from another machine
  6. It might be advisable to set up the “auto save tool” in charles, this will auto save and rotate the charles logs.

Client Machine:

  1. Install and permanently accept/trust the charles SSL certificate
    http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
  2. Configure IE, Firefox, and Chrome to use the socket charles is hosting the proxy on (ex: 192.168.1.100:8888)

When I tested this out I picked up two lines of a Facebook HTTPS chat (one was a line TO someone, and the other FROM)

you can also capture android emulator traffic this way if you start the emulator with:

emulator -avd <avd name> -http-proxy http://local_ip:8888/

Where LOCAL_IP is the IP address of your computer, not 127.0.0.1 as that is the IP address of the emulated phone.

Source: http://brakertech.com/capture-https-traffic-remotely-with-charles/

Python multiprocessing PicklingError: Can't pickle <type 'function'>

Here is a list of what can be pickled. In particular, functions are only picklable if they are defined at the top-level of a module.

This piece of code:

import multiprocessing as mp

class Foo():
    @staticmethod
    def work(self):
        pass

if __name__ == '__main__':   
    pool = mp.Pool()
    foo = Foo()
    pool.apply_async(foo.work)
    pool.close()
    pool.join()

yields an error almost identical to the one you posted:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 505, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib/python2.7/multiprocessing/pool.py", line 315, in _handle_tasks
    put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

The problem is that the pool methods all use a mp.SimpleQueue to pass tasks to the worker processes. Everything that goes through the mp.SimpleQueue must be pickable, and foo.work is not picklable since it is not defined at the top level of the module.

It can be fixed by defining a function at the top level, which calls foo.work():

def work(foo):
    foo.work()

pool.apply_async(work,args=(foo,))

Notice that foo is pickable, since Foo is defined at the top level and foo.__dict__ is picklable.

failed to find target with hash string 'android-22'

Just click on the link written in the error:

Open Android SDK Manager

and it will show you the dialogs that will help you to install the required sdk for your project.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How do I use the conditional operator (? :) in Ruby?

Your use of ERB suggests that you are in Rails. If so, then consider truncate, a built-in helper which will do the job for you:

<% question = truncate(question, :length=>30) %>

How do I concatenate strings?

2020 Update: Concatenation by String Interpolation

RFC 2795 issued 2019-10-27: Suggests support for implicit arguments to do what many people would know as "string interpolation" -- a way of embedding arguments within a string to concatenate them.

RFC: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

Latest issue status can be found here: https://github.com/rust-lang/rust/issues/67984

At the time of this writing (2020-9-24), I believe this feature should be available in the Rust Nightly build.

This will allow you to concatenate via the following shorthand:

format_args!("hello {person}")

It is equivalent to this:

format_args!("hello {person}", person=person)

There is also the "ifmt" crate, which provides its own kind of string interpolation:

https://crates.io/crates/ifmt

plot.new has not been called yet

As a newbie, I faced the same 'problem'.

In newbie terms : when you call plot(), the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R. However, some commands, like identify(), act on open/active graph windows. When identify() cannot find an open/active graph window, it gives this error message.

However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify() etc.

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

Best way to "push" into C# array

As per comment "That is not pushing to an array. It is merely assigning to it"

If you looking for the best practice to assign value to array then its only way that you can assign value.

Array[index]= value;

there is only way to assign value when you do not want to use List.

How can I check for NaN values?

All the methods to tell if the variable is NaN or None:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

How do I execute a PowerShell script automatically using Windows task scheduler?

In my case, my script has parameters, so I set:

Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"

How to iterate over the keys and values with ng-repeat in AngularJS?

How about:

<table>
  <tr ng-repeat="(key, value) in data">
    <td> {{key}} </td> <td> {{ value }} </td>
  </tr>
</table>

This method is listed in the docs: https://docs.angularjs.org/api/ng/directive/ngRepeat

add new row in gridview after binding C#, ASP.net

You can run this example directly.

aspx page:

<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
            <ItemTemplate>
                <asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
            <ItemTemplate>
                <asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
            <ItemTemplate>
                <asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />

C# code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        grd.DataSource = GetTableWithInitialData(); // get first initial data
        grd.DataBind();
    }
}

public DataTable GetTableWithInitialData() // this might be your sp for select
{
    DataTable table = new DataTable();
    table.Columns.Add("PayScale", typeof(string));
    table.Columns.Add("IncrementAmount", typeof(string));
    table.Columns.Add("Period", typeof(string));

    table.Rows.Add(1, "David", "1");
    table.Rows.Add(2, "Sam", "2");
    table.Rows.Add(3, "Christoff", "1.5");
    return table;
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    DataTable dt = GetTableWithNoData(); // get select column header only records not required
    DataRow dr;

    foreach (GridViewRow gvr in grd.Rows)
    {
        dr = dt.NewRow();

        TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
        TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
        TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;

        dr[0] = txtPayScale.Text;
        dr[1] = txtIncrementAmount.Text;
        dr[2] = txtPeriod.Text;

        dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
    }

    dr = dt.NewRow(); // add last empty row
    dt.Rows.Add(dr);

    grd.DataSource = dt; // bind new datatable to grid
    grd.DataBind();
}

public DataTable GetTableWithNoData() // returns only structure if the select columns
{
    DataTable table = new DataTable();
    table.Columns.Add("PayScale", typeof(string));
    table.Columns.Add("IncrementAmount", typeof(string));
    table.Columns.Add("Period", typeof(string));
    return table;
}

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

How to get "GET" request parameters in JavaScript?

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.

With an example:

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else

var _GET = (function() {
    var _get = {};
    var re = /[?&]([^=&]+)(=?)([^&]*)/g;
    while (m = re.exec(location.search))
        _get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
    return _get;
})();

console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123

Count how many files in directory PHP

You should have :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

Connect to Oracle DB using sqlplus

sqlplus username/password@database

Eg:

sqlplus hr/hr@orcl

PHP - auto refreshing page

use this code ,it will automatically refresh in 5 seconds, you can change time in refresh

<?php $url1=$_SERVER['REQUEST_URI']; header("Refresh: 5; URL=$url1"); ?>

Change default text in input type="file"?

Here is how its done with bootstrap, only u should put the original input somewhere...idk in head and delete the < br > if you have it, because its only hidden and its taking space anyway :)

_x000D_
_x000D_
 <head> _x000D_
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
 </head>_x000D_
 _x000D_
 <label for="file" button type="file" name="image" class="btn btn-secondary">Secondary</button> </label>_x000D_
    _x000D_
 <input type="file" id="file" name="image" value="Prebrskaj" style="visibility:hidden;">_x000D_
 _x000D_
 _x000D_
 <footer>_x000D_
 _x000D_
 <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
 _x000D_
 </footer>
_x000D_
_x000D_
_x000D_

PHP: How to send HTTP response code?

since PHP 5.4 you can use http_response_code() for get and set header status code.

here an example:

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

here is the document of this function in php.net:

http_response_code

(13: Permission denied) while connecting to upstream:[nginx]

  1. Check the user in /etc/nginx/nginx.conf
  2. Change ownership to user.
sudo chown -R nginx:nginx /var/lib/nginx

Now see the magic.

Using CSS in Laravel views?

your css file belongs into the public folder or a subfolder of it.

f.e if you put your css in

public/css/common.css

you would use

HTML::style('css/common.css');

In your blade view...

Or you could also use the Asset class http://laravel.com/docs/views/assets...

Format date as dd/MM/yyyy using pipes

Date pipes does not behave correctly in Angular 2 with Typescript for Safari browser on MacOS and iOS. I faced this issue recently. I had to use moment js here for resolving the issue. Mentioning what I have done in short...

  1. Add momentjs npm package in your project.

  2. Under xyz.component.html, (Note here that startDateTime is of data type string)

{{ convertDateToString(objectName.startDateTime) }}

  1. Under xyz.component.ts,

import * as moment from 'moment';

convertDateToString(dateToBeConverted: string) {
return moment(dateToBeConverted, "YYYY-MM-DD HH:mm:ss").format("DD-MMM-YYYY");
}

How to prevent downloading images and video files from my website?

You can't stop image/video theft but you can make harder for normal users but you can't make it harder for the programmers like us (I mean thieves that know little web programming).

There are some tricks you can try:

1.) Using flash as YouTube and many others sites like http://www.funnenjoy.com does.

2.) Div overlaping or background pic setting (but users with little sense can easily save all resources by opening inspect element or other developer option).

3.) You can disable right click and specific keys like CTRL + S and others possibles with JavaScript but main drawback is that if user disable JavaScript our all tricks fail down.

4.) Save image in none online directories (if you have full access to web server) and read that files with server side languages like PHP every time when image / video is required and change image id time to time or create script that can automatically change ID after every access.

5.) Use .htaccess in apache to prevent linking of your images by others sites. you can use this site to automatically generate .htacess http://www.htaccesstools.com/hotlink-protection/

View stored procedure/function definition in MySQL

If you want to know the list of procedures you can run the following command -

show procedure status;

It will give you the list of procedures and their definers Then you can run the show create procedure <procedurename>;

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

For me, I didn't have xcode installed (on Mojave OS). I went to the App Store on my mac and downloaded it, then went back to terminal and typed git and hit enter, then it worked.

boundingRectWithSize for NSAttributedString returning wrong size

I'd like to add my thoughts since I had exactly the same problem.

I was using UITextView since it had nicer text alignment (justify, which at the time was not available in UILabel), but in order to "simulate" non-interactive-non-scrollable UILabel, I'd switch off completely scrolling, bouncing, and user interaction.

Of course, problem was that text was dynamic, and while width would be fixed, height should be recalculated every time I'd set new text value.

boundingRectWithSize didn't work well for me at all, from what I could see, UITextView was adding some margin on top which boundingRectWithSize would not get into a count, hence, height retrieved from boundingRectWithSize was smaller than it should be.

Since text was not to be updated rapidly, it's just used for some information that may update every 2-3 seconds the most, I've decided following approach:

/* This f is nested in a custom UIView-inherited class that is built using xib file */
-(void) setTextAndAutoSize:(NSString*)text inTextView:(UITextView*)tv
{
    CGFloat msgWidth = tv.frame.size.width; // get target's width

    // Make "test" UITextView to calculate correct size
    UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, msgWidth, 300)]; // we set some height, really doesn't matter, just put some value like this one.
    // Set all font and text related parameters to be exact as the ones in targeted text view
    [temp setFont:tv.font];
    [temp setTextAlignment:tv.textAlignment];
    [temp setTextColor:tv.textColor];
    [temp setText:text];

    // Ask for size that fits :P
    CGSize tv_size = [temp sizeThatFits:CGSizeMake(msgWidth, 300)];

    // kill this "test" UITextView, it's purpose is over
    [temp release];
    temp = nil;

    // apply calculated size. if calcualted width differs, I choose to ignore it anyway and use only height because I want to have width absolutely fixed to designed value
    tv.frame = CGRectMake(tv.frame.origin.x, tv.frame.origin.y, msgWidth, tv_size.height );
}

*Above code is not directly copied from my source, I had to adjust it / clear it from bunch of other stuff not needed for this article. Don't take it for copy-paste-and-it-will-work-code.

Obvious disadvantage is that it has alloc and release, for each call.

But, advantage is that you avoid depending on compatibility between how boundingRectWithSize draws text and calculates it's size and implementation of text drawing in UITextView (or UILabel which also you can use just replace UITextView with UILabel). Any "bugs" that Apple may have are this way avoided.

P.S. It would seem that you shouldn't need this "temp" UITextView and can just ask sizeThatFits directly from target, however that didn't work for me. Though logic would say it should work and alloc/release of temporary UITextView are not needed, it did not. But this solution worked flawlessly for any text I would set in.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

Create a shortcut on Desktop

If you want a simple code to put on other location, take this:

using IWshRuntimeLibrary;

WshShell shell = new WshShell();
IWshShortcut shortcut = shell.CreateShortcut(@"C:\FOLDER\SOFTWARENAME.lnk");
shortcut.TargetPath = @"C:\FOLDER\SOFTWARE.exe";
shortcut.Save();

key_load_public: invalid format

I had the same warning. It was a very old key. I regenerated a key on the current OpenSSH 7, and the error was gone.

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

How to change lowercase chars to uppercase using the 'keyup' event?

As placeholder text is becoming more commonly supported, this update may be relevant.

My issue with the other answers is that applying the text-transform: uppercase css would also uppercase the placeholder text, which we didn't want.

To work around this, it was a little tricky but worth the net effect.

  1. Create the text-uppercase class.

    .text-uppercase {
        text-transform:uppercase;
    }
    
  2. Bind to the keydown event.

    Binding to the keydown event was important to get the class to be added before the character was visible. Binding to keypress or keyup left the brief flicker of the lowercase letter.

    $('input').on('keydown', function(e)
    {
        // Visually Friendly Auto-Uppercase
        var $this = $(this);
    
        // 1. Length of 1, hitting backspace, remove class.
        if ($this.val().length == 1 && e.which == 8)
        {
            $this.removeClass('text-uppercase');
        }
    
        // 2. Length of 0, hitting character, add class.
        if ($this.val().length == 0 && e.which >= 65 && e.which <= 90)
        {
            $this.addClass('text-uppercase');
        }
    });
    
  3. Transform to uppercase when submitting to server.

    var myValue = this.value.toUpperCase();
    

YMMV, you may find that cutting text or deleting text with the delete key may not remove the class. You can modify the keydown to also take the delete character into account.

Also, if you only have one character, and your current cursor position is in position 0, hitting backspace will remove the text-transform class, but since the cursor position is in position 0, it doesn't delete the single character.

This would require a bit more work to also check the current character position and determine if the delete or backspace key will actually delete the single remaining character.

Although it was worth the extra effort to make this seemless and visually appealing for our most common use case, going beyond this wasn't necessary. :)

Change the color of a checked menu item in a navigation drawer

Well you can achieve this using Color State Resource. If you notice inside your NavigationView you're using

app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"

Here instead of using @color/black or @color/primary_test, use a Color State List Resource. For that, first create a new xml (e.g drawer_item.xml) inside color directory (which should be inside res directory.) If you don't have a directory named color already, create one.

Now inside drawer_item.xml do something like this

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="checked state color" android:state_checked="true" />
    <item android:color="your default color" />
</selector>

Final step would be to change your NavigationView

<android.support.design.widget.NavigationView
    android:id="@+id/activity_main_navigationview"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:itemIconTint="@color/drawer_item"  // notice here
    app:itemTextColor="@color/drawer_item" // and here
    app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
    app:menu="@menu/menu_drawer">

Like this you can use separate Color State List Resources for IconTint, ItemTextColor, ItemBackground.

Now when you set an item as checked (either in xml or programmatically), the particular item will have different color than the unchecked ones.

Getting index value on razor foreach

I prefer to use this extension method:

public static class Extensions
{
    public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
        => self.Select((item, index) => (item, index));
}

Source:

https://stackoverflow.com/a/39997157/3850405

Razor:

@using Project.Shared.Helpers 

@foreach (var (item, index) in collection.WithIndex())
{
<p>
    Name: @item.Name Index: @index
</p>
}

How to filter JSON Data in JavaScript or jQuery?

No need for jQuery unless you target old browsers and don't want to use shims.

var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
    return entry.website === 'yahoo';
});

In ES2015:

const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');

How to send email using simple SMTP commands via Gmail?

Unfortunately as I am forced to use a windows server I have been unable to get openssl working in the way the above answer suggests.

However I was able to get a similar program called stunnel (which can be downloaded from here) to work. I got the idea from www.tech-and-dev.com but I had to change the instructions slightly. Here is what I did:

  1. Install telnet client on the windows box.
  2. Download stunnel. (I downloaded and installed a file called stunnel-4.56-installer.exe).
  3. Once installed you then needed to locate the stunnel.conf config file, which in my case I installed to C:\Program Files (x86)\stunnel
  4. Then, you need to open this file in a text viewer such as notepad. Look for [gmail-smtp] and remove the semicolon on the client line below (in the stunnel.conf file, every line that starts with a semicolon is a comment). You should end up with something like:

    [gmail-smtp]
    client = yes
    accept = 127.0.0.1:25
    connect = smtp.gmail.com:465
    

    Once you have done this save the stunnel.conf file and reload the config (to do this use the stunnel GUI program, and click on configuration=>Reload).

Now you should be ready to send email in the windows telnet client!
Go to Start=>run=>cmd.

Once cmd is open type in the following and press Enter:

telnet localhost 25

You should then see something similar to the following:

220 mx.google.com ESMTP f14sm1400408wbe.2

You will then need to reply by typing the following and pressing enter:

helo google

This should give you the following response:

250 mx.google.com at your service

If you get this you then need to type the following and press enter:

ehlo google

This should then give you the following response:

250-mx.google.com at your service, [212.28.228.49]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES

Now you should be ready to authenticate with your Gmail details. To do this type the following and press enter:

AUTH LOGIN

This should then give you the following response:

334 VXNlcm5hbWU6

This means that we are ready to authenticate by using our gmail address and password.

However since this is an encrypted session, we're going to have to send the email and password encoded in base64. To encode your email and password, you can use a converter program or an online website to encode it (for example base64 or search on google for ’base64 online encoding’). I reccomend you do not touch the cmd/telnet session again until you have done this.

For example [email protected] would become dGVzdEBnbWFpbC5jb20= and password would become cGFzc3dvcmQ=

Once you have done this copy and paste your converted base64 username into the cmd/telnet session and press enter. This should give you following response:

334 UGFzc3dvcmQ6

Now copy and paste your converted base64 password into the cmd/telnet session and press enter. This should give you following response if both login credentials are correct:

235 2.7.0 Accepted

You should now enter the sender email (should be the same as the username) in the following format and press enter:

MAIL FROM:<[email protected]>

This should give you the following response:

250 2.1.0 OK x23sm1104292weq.10

You can now enter the recipient email address in a similar format and press enter:

RCPT TO:<[email protected]>

This should give you the following response:

250 2.1.5 OK x23sm1104292weq.10

Now you will need to type the following and press enter:

DATA

Which should give you the following response:

354  Go ahead x23sm1104292weq.10

Now we can start to compose the message! To do this enter your message in the following format (Tip: do this in notepad and copy the entire message into the cmd/telnet session):

From: Test <[email protected]>
To: Me <[email protected]>
Subject: Testing email from telnet
This is the body

Adding more lines to the body message.

When you have finished the email enter a dot:

.

This should give you the following response:

250 2.0.0 OK 1288307376 x23sm1104292weq.10

And now you need to end your session by typing the following and pressing enter:

QUIT

This should give you the following response:

221 2.0.0 closing connection x23sm1104292weq.10
Connection to host lost.

And your email should now be in the recipient’s mailbox!

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How to get HQ youtube thumbnails?

YouTube resolutions and images

http://img.youtube.com/vi/<video-id>/<resolution><image>.jpg

Resolution
- lowest resolution
sd - Standard Definition
mq - Medium Quality
hq - High Quality
maxres - MAXimum RESolution

Image
default - Default image (1, 2, 3 shot from video, or custom uploaded)
1 - First shot from video
2 - Second shot from video
3 - Third shot from video

Confirm deletion in modal / dialog using Twitter Bootstrap?

http://bootboxjs.com/ - latest works with Bootstrap 3.0.0

The simplest possible example:

bootbox.alert("Hello world!"); 

From the site:

The library exposes three methods designed to mimic their native JavaScript equivalents. Their exact method signatures are flexible as each can take various parameters to customise labels and specify defaults, but they are most commonly called like so:

bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)

Here's a snippet of it in action (click "Run code snippet" below):

_x000D_
_x000D_
$(function() {_x000D_
  bootbox.alert("Hello world!");_x000D_
});
_x000D_
<!-- required includes -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- bootbox.js at 4.4.0 -->_x000D_
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>
_x000D_
_x000D_
_x000D_

Add number of days to a date

I know this is an old question, but for PHP <5.3 you could try this:

$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');

CSS text-overflow: ellipsis; not working?

I have been having this problem and I wanted a solution that could easily work with dynamic widths. The solution use css grid. This is how the code looks like:

// css 
.parent{
      display: grid; 
      grid-template-columns: auto 1fr;
}      
.dynamic-width-child{
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
}
.fixed-width-child{
      white-space: nowrap;
}

.

// html
<div class="parent">
  <div class="dynamic-width-child">
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii asdfhlhlafh;lshd;flhsd;lhfaaaaaaaaaaaaaaaaaaaa
  </div>
  <div class="fixed-width-child">Why?-Zed</div>

Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

Where are the Properties.Settings.Default stored?

it is saved in your Documents and Settings\%user%\Local Settings\Application Data......etc search for a file called user.config there

the location may change however.

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

How can I get the index from a JSON object with value?

Function base solution for get index from a JSON object with value by VanillaJS.

Exemple: https://codepen.io/gmkhussain/pen/mgmEEW

_x000D_
_x000D_
    var data= [{_x000D_
      "name": "placeHolder",_x000D_
      "section": "right"_x000D_
    }, {_x000D_
      "name": "Overview",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "ByFunction",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "Time",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allFit",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allbMatches",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allOffers",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allInterests",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allResponses",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "divChanged",_x000D_
      "section": "right"_x000D_
    }];_x000D_
    _x000D_
    _x000D_
    // create function_x000D_
    function findIndex(jsonData, findThis){_x000D_
      var indexNum = jsonData.findIndex(obj => obj.name==findThis);  _x000D_
_x000D_
    //Output of result_x000D_
          document.querySelector("#output").innerHTML=indexNum;_x000D_
          console.log(" Array Index number: " + indexNum + " , value of " + findThis );_x000D_
    }_x000D_
    _x000D_
    _x000D_
    /* call function */_x000D_
    findIndex(data, "allOffers");
_x000D_
Output of index number : <h1 id="output"></h1>
_x000D_
_x000D_
_x000D_

Can jQuery provide the tag name?

Yes. You could use the below code:

this.tagName

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Across all browsers and simple. this did it for me

_x000D_
_x000D_
$(function () {_x000D_
     $('input[type="file"]').change(function () {_x000D_
          if ($(this).val() != "") {_x000D_
                 $(this).css('color', '#333');_x000D_
          }else{_x000D_
                 $(this).css('color', 'transparent');_x000D_
          }_x000D_
     });_x000D_
})
_x000D_
input[type="file"]{_x000D_
    color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" name="app_cvupload" class="fullwidth input rqd">
_x000D_
_x000D_
_x000D_

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Passing multiple parameters to pool.map() function in Python

In case you don't have access to functools.partial, you could use a wrapper function for this, as well.

def target(lock):
    def wrapped_func(items):
        for item in items:
            # Do cool stuff
            if (... some condition here ...):
                lock.acquire()
                # Write to stdout or logfile, etc.
                lock.release()
    return wrapped_func

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    lck = multiprocessing.Lock()
    pool.map(target(lck), iterable)
    pool.close()
    pool.join()

This makes target() into a function that accepts a lock (or whatever parameters you want to give), and it will return a function that only takes in an iterable as input, but can still use all your other parameters. That's what is ultimately passed in to pool.map(), which then should execute with no problems.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I was facing the same error. The solution that worked for me is:

From the server end, while returning JSON response, change the content-type: text/html

Now the browsers (Chrome, Firefox and IE8) do not give an error.

How do I tar a directory of files and folders without including the directory itself?

# tar all files within and deeper in a given directory
# with no prefixes ( neither <directory>/ nor ./ )
# parameters: <source directory> <target archive file>
function tar_all_in_dir {
    { cd "$1" && find -type f -print0; } \
    | cut --zero-terminated --characters=3- \
    | tar --create --file="$2" --directory="$1" --null --files-from=-
}

Safely handles filenames with spaces or other unusual characters. You can optionally add a -name '*.sql' or similar filter to the find command to limit the files included.

ExecutorService, how to wait for all tasks to finish

Root cause for IllegalMonitorStateException:

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

From your code, you have just called wait() on ExecutorService without owning the lock.

Below code will fix IllegalMonitorStateException

try 
{
    synchronized(es){
        es.wait(); // Add some condition before you call wait()
    }
} 

Follow one of below approaches to wait for completion of all tasks, which have been submitted to ExecutorService.

  1. Iterate through all Future tasks from submit on ExecutorService and check the status with blocking call get() on Future object

  2. Using invokeAll on ExecutorService

  3. Using CountDownLatch

  4. Using ForkJoinPool or newWorkStealingPool of Executors(since java 8)

  5. Shutdown the pool as recommended in oracle documentation page

    void shutdownAndAwaitTermination(ExecutorService pool) {
       pool.shutdown(); // Disable new tasks from being submitted
       try {
       // Wait a while for existing tasks to terminate
       if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
           pool.shutdownNow(); // Cancel currently executing tasks
           // Wait a while for tasks to respond to being cancelled
           if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
       }
    } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
    }
    

    If you want to gracefully wait for all tasks for completion when you are using option 5 instead of options 1 to 4, change

    if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
    

    to

    a while(condition) which checks for every 1 minute.

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How do I create a random alpha-numeric string in C++?

Here's my adaptation of Ates Goral's answer using C++11. I've added the lambda in here, but the principle is that you could pass it in and thereby control what characters your string contains:

std::string random_string( size_t length )
{
    auto randchar = []() -> char
    {
        const char charset[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    std::string str(length,0);
    std::generate_n( str.begin(), length, randchar );
    return str;
}

Here is an example of passing in a lambda to the random string function: http://ideone.com/Ya8EKf

Why would you use C++11?

  1. Because you can produce strings that follow a certain probability distribution (or distribution combination) for the character set you're interested in.
  2. Because it has built-in support for non-deterministic random numbers
  3. Because it supports unicode, so you could change this to an internationalized version.

For example:

#include <iostream>
#include <vector>
#include <random>
#include <functional> //for std::function
#include <algorithm>  //for std::generate_n

typedef std::vector<char> char_array;

char_array charset()
{
    //Change this to suit
    return char_array( 
    {'0','1','2','3','4',
    '5','6','7','8','9',
    'A','B','C','D','E','F',
    'G','H','I','J','K',
    'L','M','N','O','P',
    'Q','R','S','T','U',
    'V','W','X','Y','Z',
    'a','b','c','d','e','f',
    'g','h','i','j','k',
    'l','m','n','o','p',
    'q','r','s','t','u',
    'v','w','x','y','z'
    });
};    

// given a function that generates a random character,
// return a string of the requested length
std::string random_string( size_t length, std::function<char(void)> rand_char )
{
    std::string str(length,0);
    std::generate_n( str.begin(), length, rand_char );
    return str;
}

int main()
{
    //0) create the character set.
    //   yes, you can use an array here, 
    //   but a function is cleaner and more flexible
    const auto ch_set = charset();

    //1) create a non-deterministic random number generator      
    std::default_random_engine rng(std::random_device{}());

    //2) create a random number "shaper" that will give
    //   us uniformly distributed indices into the character set
    std::uniform_int_distribution<> dist(0, ch_set.size()-1);

    //3) create a function that ties them together, to get:
    //   a non-deterministic uniform distribution from the 
    //   character set of your choice.
    auto randchar = [ ch_set,&dist,&rng ](){return ch_set[ dist(rng) ];};

    //4) set the length of the string you want and profit!        
    auto length = 5;
    std::cout<<random_string(length,randchar)<<std::endl;
    return 0;
}

Sample output.

How to change DatePicker dialog color for Android 5.0

You don't have create theme just write it in your dialog creation object

DatePickerDialog datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this, mYear, mMonth, mDay);

follow this it will give you all type date picker style it's really work

http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

SQL Server remove milliseconds from datetime

Use CAST with following parameters:

Date

select Cast('2017-10-11 14:38:50.440' as date)

Output: 2017-10-11

Datetime

select Cast('2017-10-11 14:38:50.440' as datetime)

Output: 2017-10-11 14:38:50.440

SmallDatetime

select Cast('2017-10-11 14:38:50.440' as smalldatetime)

Output: 2017-10-11 14:39:00

DatetimeOffset

select Cast('2017-10-11 14:38:50.440' as datetimeoffset)

Output: 2017-10-11 14:38:50.4400000 +00:00

Datetime2

select Cast('2017-10-11 14:38:50.440' as datetime2)

Output: 2017-10-11 14:38:50.4400000

How to use Apple's new .p8 certificate for APNs in firebase console

When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.

enter image description here

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

remove borders around html input

border: 0 should be enough, but if it isn't, perhaps the button's browser-default styling in interfering. Have you tried setting appearance to none (e.g. -webkit-appearance: none)

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

read string from .resx file in C#

This works for me. say you have a strings.resx file with string ok in it. to read it

String varOk = My.Resources.strings.ok

gradle build fails on lint task

Add these lines to your build.gradle file:

android { 
  lintOptions { 
    abortOnError false 
  }
}

Then clean your project :D

Virtual Memory Usage from Java under Linux, too much memory used

The Sun JVM requires a lot of memory for HotSpot and it maps in the runtime libraries in shared memory.

If memory is an issue consider using another JVM suitable for embedding. IBM has j9, and there is the Open Source "jamvm" which uses GNU classpath libraries. Also Sun has the Squeak JVM running on the SunSPOTS so there are alternatives.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

How to do encryption using AES in Openssl

My suggestion is to run

openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin

under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.

U1: My guess is that you are not setting some other required options, like mode of operation (padding).

U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.

Fixing npm path in Windows 8 and 10

If after installing your npm successfully, and you want to install VueJS then this is what you should do

after running the following command (as Admin)

npm install --global vue-cli

It will place the vue.cmd in the following directory C:\Users\YourUserName\AppData\Roaming\npm

you will see this in your directory.

Now to use vue as a command in cmd. Open the cmd as admin and run the following command.

setx /M path "%path%;%appdata%\npm"

Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.

I hope this helps.

How to disable clicking inside div

The CSS property that can be used is:

pointer-events:none

!IMPORTANT Keep in mind that this property is not supported by Opera Mini and IE 10 and below (inclusive). Another solution is needed for these browsers.

jQuery METHOD If you want to disable it via script and not CSS property, these can help you out: If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

You can re-enable clicks with pointer-events: auto; (Documentation)

Note that pointer-events overrides the cursor property, so if you want the cursor to be something other than the standard cursor, your css should be place after pointer-events.

React JSX: selecting "selected" on selected <select> option

Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

Align button to the right

The bootstrap 4.0.0 file you are getting from cdn doesn't have a pull-right (or pull-left) class. The v4 is in alpha, so there are many issues like that.

There are 2 options:

1) Reverse to bootstrap 3.3.7

2) Write your own CSS.

Navigation Controller Push View Controller

UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];

How to remove gaps between subplots in matplotlib?

Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:

import matplotlib.pyplot as plt

plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})

for i, ax in enumerate(f.axes):
    ax.grid('on', linestyle='--')
    ax.set_xticklabels([])
    ax.set_yticklabels([])

plt.show()
plt.close()

Resulting in:

.

Upload file to FTP using C#

publish date: 06/26/2018

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = 
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("anonymous", 
"[email protected]");

        // Copy the contents of the file to the request stream.
        byte[] fileContents;
        using (StreamReader sourceStream = new StreamReader("testfile.txt"))
        {
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status 
{response.StatusDescription}");
        }
    }
}
}

Determine which MySQL configuration file is being used

Taken from the fantastic "High Performance MySQL" O'Reilly book:

$ which mysqld
/usr/sbin/mysqld

$ /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
Default options are read from the following files in the given order:
/etc/mysql/my.cnf ~/.my.cnf /usr/etc/my.cnf

How can I use "e" (Euler's number) and power operation in python 2.7

You can use exp(x) function of math library, which is same as e^x. Hence you may write your code as:

import math
x.append(1 - math.exp( -0.5 * (value1*value2)**2))

I have modified the equation by replacing 1/2 as 0.5. Else for Python <2.7, we'll have to explicitly type cast the division value to float because Python round of the result of division of two int as integer. For example: 1/2 gives 0 in python 2.7 and below.

How to append a date in batch files

I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19

http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc

Here's the code from that site:

::~~Author~~.          Brett Middleton
::~~Email_Address~~. [email protected]
::~~Script_Type~~.   nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables

::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command.  These variables can be used to name files, control the flow of execution, etc.

::~~Script~~.

@echo off

::-----------------------------------------------------------------------------
::  SetEnvDate1.CMD                                                     6/30/98
::-----------------------------------------------------------------------------
::  Description  :  Sets or clears a group of environment variables containing
::               :  components of the current date extracted from the string
::               :  returned by the DATE /T command.  These variables can be
::               :  used to name files, control the flow of execution, etc.
::               :
::  Requires     :  Windows NT with command extensions enabled
::               :
::  Tested       :  Yes, as demonstration
::               :
::  Contact      :  Brett Middleton <[email protected]>
::               :  Animal and Dairy Science Department
::               :  University of Georgia, Athens
::-----------------------------------------------------------------------------
::  USAGE
::
::  SetEnvDate1 can be used as a model for coding date/time routines in
::  other scripts, or can be used by itself as a utility that is called
::  from other scripts.
::  
::  Run or call SetEnvDate1 without arguments to set the date variables.
::  Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
::  day number (DT_DD) and four-digit year (DT_YYYY).
::
::  When the variables are no longer needed, clean up the environment by
::  calling the script again with the CLEAR argument.  E.g.,
::
::       call SetEnvDate1 clear
::-----------------------------------------------------------------------------
::  NOTES
::
::  A time variable could be added by parsing the string returned by the
::  built-in TIME /T command.  This is left as an exercise for the reader. B-)
::
::  This script illustrates the following NT command extensions:
::
::  1.  Use of the extended IF command to do case-insensitive comparisons.
::
::  2.  Use of the extended DATE command.
::
::  3.  Use of the extended FOR command to parse a string returned by a
::      command or program.
::
::  4.  Use of the "()" conditional processing symbols to group commands
::      for conditional execution.  All commands between the parens will
::      be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------

if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo    SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit

::-----------------------------------------------------------------------------
::  Check arguments and select SET or CLEAR routine.  Unrecognized arguments
::  are ignored and SET is assumed.
::-----------------------------------------------------------------------------

:chkarg

if /I "%1" == "CLEAR" goto clrvar
goto setvar

::-----------------------------------------------------------------------------
::  Set variables for the day abbreviation (DAY), month number (MM), 
::  day number (DD) and 4-digit year (YYYY). 
::-----------------------------------------------------------------------------

:setvar

for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)

goto endit

::-----------------------------------------------------------------------------
::  Clear all variables from the environment.
::-----------------------------------------------------------------------------

:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit

:endit

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Enable IIS7 gzip

If you use YSlow with Firebug and analyse your page performance, YSlow will certainly tell you what artifacts on your page are not gzip'd!

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

Set color of TextView span in Android

If you want more control, you might want to check the TextPaint class. Here is how to use it:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

Procedure or function !!! has too many arguments specified

Use the following command before defining them:

cmd.Parameters.Clear()

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

Block direct access to a file over http but allow php script access

If you have access to you httpd.conf file (in ubuntu it is in the /etc/apache2 directory), you should add the same lines that you would to the .htaccess file in the specific directory. That is (for example):

ServerName YOURSERVERNAMEHERE
<Directory /var/www/>
AllowOverride None
order deny,allow
Options -Indexes FollowSymLinks
</Directory>

Do this for every directory that you want to control the information, and you will have one file in one spot to manage all access. It the example above, I did it for the root directory, /var/www.

This option may not be available with outsourced hosting, especially shared hosting. But it is a better option than adding many .htaccess files.

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG

Example:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

What does it mean by select 1 from table?

select 1 from table is used by some databases as a query to test a connection to see if it's alive, often used when retrieving or returning a connection to / from a connection pool.

Facebook share button and custom text

You have several options:

  1. Use the standard FB Share button and set text via Open Graph API and meta tags on your page.
  2. Instead of Share, use FB.ui's stream.publish method, which let's you control the URL, title, caption, description and thumbnail at run-time.
  3. Or use http://www.facebook.com/sharer.php with appropriate parameters.

What is parsing in terms that a new programmer would understand?

I'd explain parsing as the process of turning some kind of data into another kind of data.

In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.

For example, turning

":Nick!User@Host PRIVMSG #channel :Hello!"

into (C)

struct irc_line {
    char *nick;
    char *user;
    char *host;
    char *command;
    char **arguments;
    char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }

How to write lists inside a markdown table?

If you want a no-bullet list (or any other non-standard usage) or more lines in a cell use <br />

| Event         | Platform      | Description |
| ------------- |-----------| -----:|
| `message_received`| `facebook-messenger`<br/>`skype`|

Oracle DateTime in Where Clause?

You could also do:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = DATE '2011-01-26'

Unity Scripts edited in Visual studio don't provide autocomplete

I found an another way to fix this issue in a more convenient manner:

  1. Select the broken file in Solution Explorer.
  2. Open its Properties.
  3. Switch field "Build Action" from "Compile" to "None".
  4. Then switch it back to "Compile".

This will kill the synchronization between Unity and Visual Studio somehow.

The next time Visual Studio will reload the project, it will prompt a warning. Just click on "Discard".

Understanding events and event handlers in C#

Here is a code example which may help:

using System;
using System.Collections.Generic;
using System.Text;

namespace Event_Example
{
  // First we have to define a delegate that acts as a signature for the
  // function that is ultimately called when the event is triggered.
  // You will notice that the second parameter is of MyEventArgs type.
  // This object will contain information about the triggered event.

  public delegate void MyEventHandler(object source, MyEventArgs e);

  // This is a class which describes the event to the class that receives it.
  // An EventArgs class must always derive from System.EventArgs.

  public class MyEventArgs : EventArgs
  {
    private string EventInfo;

    public MyEventArgs(string Text) {
      EventInfo = Text;
    }

    public string GetInfo() {
      return EventInfo;
    }
  }

  // This next class is the one which contains an event and triggers it
  // once an action is performed. For example, lets trigger this event
  // once a variable is incremented over a particular value. Notice the
  // event uses the MyEventHandler delegate to create a signature
  // for the called function.

  public class MyClass
  {
    public event MyEventHandler OnMaximum;

    private int i;
    private int Maximum = 10;

    public int MyValue
    {
      get { return i; }
      set
      {
        if(value <= Maximum) {
          i = value;
        }
        else 
        {
          // To make sure we only trigger the event if a handler is present
          // we check the event to make sure it's not null.
          if(OnMaximum != null) {
            OnMaximum(this, new MyEventArgs("You've entered " +
              value.ToString() +
              ", but the maximum is " +
              Maximum.ToString()));
          }
        }
      }
    }
  }

  class Program
  {
    // This is the actual method that will be assigned to the event handler
    // within the above class. This is where we perform an action once the
    // event has been triggered.

    static void MaximumReached(object source, MyEventArgs e) {
      Console.WriteLine(e.GetInfo());
    }

    static void Main(string[] args) {
      // Now lets test the event contained in the above class.
      MyClass MyObject = new MyClass();
      MyObject.OnMaximum += new MyEventHandler(MaximumReached);
      for(int x = 0; x <= 15; x++) {
        MyObject.MyValue = x;
      }
      Console.ReadLine();
    }
  }
}

Best practice to validate null and empty collection in Java

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

Laravel-5 'LIKE' equivalent (Eloquent)

I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes

public function scopeWhereLike($query, $column, $value)
{
    return $query->where($column, 'like', '%'.$value.'%');
}

public function scopeOrWhereLike($query, $column, $value)
{
    return $query->orWhere($column, 'like', '%'.$value.'%');
}

Usage:

$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();

Change default icon

Go to form's properties, ICON ... Choose an icon you want.

EDIT: try this

  1. Edit App.Ico to make it look like you want.
  2. In the property pane for your form, set the Icon property to your project's App.Ico file.
  3. Rebuild solution.

And read this one icons

Generate an integer that is not among four billion given ones

For some reason, as soon as I read this problem I thought of diagonalization. I'm assuming arbitrarily large integers.

Read the first number. Left-pad it with zero bits until you have 4 billion bits. If the first (high-order) bit is 0, output 1; else output 0. (You don't really have to left-pad: you just output a 1 if there are not enough bits in the number.) Do the same with the second number, except use its second bit. Continue through the file in this way. You will output a 4-billion bit number one bit at a time, and that number will not be the same as any in the file. Proof: it were the same as the nth number, then they would agree on the nth bit, but they don't by construction.

How can I change all input values to uppercase using Jquery?

use css :

input.upper { text-transform: uppercase; }

probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase: http://plugins.jquery.com/plugin-tags/uppercase

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

Find location of a removable SD card

The only working solution I found was this one that uses reflection

 /**
 * Get external sd card path using reflection
 * @param mContext
 * @param is_removable is external storage removable
 * @return
 */
private static String getExternalStoragePath(Context mContext, boolean is_removable) {

    StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
    Class<?> storageVolumeClazz = null;
    try {
        storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
        Object result = getVolumeList.invoke(mStorageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String path = (String) getPath.invoke(storageVolumeElement);
            boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
            if (is_removable == removable) {
                return path;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

How to initialize struct?

Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

How to get current screen width in CSS?

this can be achieved with the css calc() operator

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
        zoom:calc(100% / 480);
    }
}

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How do I upload a file to an SFTP server in C# (.NET)?

Unfortunately, it's not in the .NET Framework itself. My wish is that you could integrate with FileZilla, but I don't think it exposes an interface. They do have scripting I think, but it won't be as clean obviously.

I've used CuteFTP in a project which does SFTP. It exposes a COM component which I created a .NET wrapper around. The catch, you'll find, is permissions. It runs beautifully under the Windows credentials which installed CuteFTP, but running under other credentials requires permissions to be set in DCOM.

xcode-select active developer directory error

I was having the same problem in high sierra. running the following command solved it

npm explore npm -g -- npm install node-gyp@latest

How to install the Raspberry Pi cross compiler on my Linux host machine?

For Windows host, I want to highly recommend this tutorial::

  • Download and install the toolchain
  • Sync sysroot with your RPi include/lib directories
  • Compile your code
  • Drag and drop the executable to your RPi using SmarTTY
  • Run it!

Nothing more, nothing less!

Prebuilt GNU Toolchains available for Raspberry, Beaglebone, Cubieboard, AVR (Atmel) and more

Excel to JSON javascript code?

js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.

Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file

<!doctype html>
<html>

<head>
    <title>Excel to JSON Demo</title>
    <script src="xlsx.full.min.js"></script>
</head>

<body>

    <script>
        /* set up XMLHttpRequest */
        var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert data to binary string */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            /* Call XLSX */
            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            /* DO SOMETHING WITH workbook HERE */
            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();
    </script>
</body>
</html>

Input:
Click here to see the input Excel file

Output:
Click here to see the output of above code

Django DateField default options

You could also use lambda. Useful if you're using django.utils.timezone.now

date = models.DateField(_("Date"), default=lambda: now().date())

Mac install and open mysql using terminal

try with either of the 2 below commands

/usr/local/mysql/bin/mysql -uroot
-- OR --
/usr/local/Cellar/mysql/<version>/bin/mysql -uroot

Is an empty href valid?

As others have said, it is valid.

There are some downsides to each approach though:

href="#" adds an extra entry to the browser history (which is annoying when e.g. back-buttoning).

href="" reloads the page

href="javascript:;" does not seem to have any problems (other than looking messy and meaningless) - anyone know of any?

How to open a new window on form submit

i believe this jquery work for you well please check a code below.

this will make your submit action works and open a link in new tab whether you want to open action url again or a new link

jQuery('form').on('submit',function(e){
setTimeout(function () { window.open('https://www.google.com','_blank');}, 1000);});})

This code works for me perfect..

How does String substring work in Swift

I had the same initial reaction. I too was frustrated at how syntax and objects change so drastically in every major release.

However, I realized from experience how I always eventually suffer the consequences of trying to fight "change" like dealing with multi-byte characters which is inevitable if you're looking at a global audience.

So I decided to recognize and respect the efforts exerted by Apple engineers and do my part by understanding their mindset when they came up with this "horrific" approach.

Instead of creating extensions which is just a workaround to make your life easier (I'm not saying they're wrong or expensive), why not figure out how Strings are now designed to work.

For instance, I had this code which was working on Swift 2.2:

let rString = cString.substringToIndex(2)
let gString = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
let bString = (cString.substringFromIndex(4) as NSString).substringToIndex(2)

and after giving up trying to get the same approach working e.g. using Substrings, I finally understood the concept of treating Strings as a bidirectional collection for which I ended up with this version of the same code:

let rString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let gString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let bString = String(cString.characters.prefix(2))

I hope this contributes...

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

jQuery: go to URL with target="_blank"

The .ready function is used to insert the attribute once the page has finished loading.

$(document).ready(function() {
     $("class name or id a.your class name").attr({"target" : "_blank"})
})

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')