Programs & Examples On #Pdftk

A simple, GPL-licensed command-line tool for manipulating PDF documents.

pdftk compression option

The one-line pdf2ps option (by Lee) actually increased the pdf size. However, the two steps one did better. And it can be combined in a single one using redirection from & to standard input/output and pipes:

pdf2ps large.pdf - | ps2pdf - small.pdf

did reduce a PDF generated by xsane from 18 Mo to 630 ko!

Links are lost, but for the present example, it's not a concern... and was the easiest way to achieve the desired result.

How to get ° character in a string in python?

You can also use chr(176) to print the degree sign. Here is an example using python 3.6.5 interactive shell:

https://i.stack.imgur.com/spoWL.png

Programmatically change the src of an img tag

Give your image an id. Then you can do this in your javascript.

document.getElementById("blaah").src="blaah";

You can use the ".___" method to change the value of any attribute of any element.

Box shadow in IE7 and IE8

Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.

It supports box-shadow (except for the inset keyword).

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

AWK: Access captured group from line pattern

You can use GNU awk:

$ cat hta
RewriteCond %{HTTP_HOST} !^www\.mysite\.net$
RewriteRule (.*) http://www.mysite.net/$1 [R=301,L]

$ gawk 'match($0, /.*(http.*?)\$/, m) { print m[1]; }' < hta
http://www.mysite.net/

Is it possible to get an Excel document's row count without loading the entire document into memory?

https://pythonhosted.org/pyexcel/iapi/pyexcel.sheets.Sheet.html see : row_range() Utility function to get row range

if you use pyexcel, can call row_range get max rows.

python 3.4 test pass.

Add MIME mapping in web.config for IIS Express

To solve the problem, double-click the "MIME Types" configuration option while having IIS root node selected in the left panel and click "Add..." link in the Actions panel on the right. This will bring up the following dialog. Add .woff file extension and specify "application/x-font-woff" as the corresponding MIME type:

enter image description here

Follow same for woff2 with application/x-font-woff2

What's a good (free) visual merge tool for Git? (on windows)

What's wrong with using Git For Windows? From the repo view, there's an icon of the branch you're in (at the top), and if you click on manage you can drag&drop in a very visual and convenient way.

moment.js get current time in milliseconds?

Since this thread is the first one from Google I found, one accurate and lazy way I found is :

const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
//   -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;

const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()

now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !

Create a zip file and download it

I have experienced exactly the same problem. In my case, the source of it was the permissions of the folder in which I wanted to create the zip file that were all set to read only. I changed it to read and write and it worked.

If the file is not created on your local-server when you run the script, you most probably have the same problem as I did.

How can you make a custom keyboard in Android?

Well Suragch gave the best answer so far but he skipped certain minor stuff that was important to getting the app compiled.

I hope to make a better answer than Suragch by improving on his answer. I will add all the missing elements he didnt put.

I compiled my apk using the android app , APK Builder 1.1.0. So let's begin.

To build an Android app we need couple files and folders that are organized in a certain format and capitalized accordingly.

res layout -> xml files depicting how app will look on phone. Similar to how html shapes how web page looks on browser. Allowing your app to fit on screens accordingly.

values -> constant data such as colors.xml, strings.xml, styles.xml. These files must be properly spelt.

drawable -> pics{jpeg, png,...}; Name them anything.

mipmap -> more pics. used for app icon?

xml -> more xml files.

src -> acts like JavaScript in html. layout files will initiate the starting view and your java file will dynamically control the tag elements and trigger events. Events can also be activated directly in the layout.xml just like in html.

AndroidManifest.xml -> This file registers what your app is about. Application name, Type of program, permissions needed, etc. This seems to make Android rather safe. Programs literally cannot do what they didnt ask for in the Manifest.

Now there are 4 types of Android programs, an activity, a service, a content provider, and a broadcast reciever. Our keyboard will be a service, which allows it to run in the background. It will not appear in the list of apps to launch; but it can be uninstalled.

To compile your app, involves gradle, and apk signing. You can research that one or use APK Builder for android. It is super easy.

Now that we understand Android development, let us create the files and folders.

  1. Create the files and folders as I discussed above. My directory wil look as follows:

    • NumPad
      • AndroidManifest.xml
      • src
        • Saragch
          • num_pad
            • MyInputMethodService.java
      • res
        • drawable
          • Suragch_NumPad_icon.png
        • layout
          • key_preview.xml
          • keyboard_view.xml
        • xml
          • method.xml
          • number_pad.xml
        • values
          • colors.xml
          • strings.xml
          • styles.xml

Remember if you are using an ide such as Android Studio it may have a project file.

  1. Write files.

A: NumPad/res/layout/key_preview.xml

<?xml version="1.0" encoding="utf-8"?>
   <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:background="@android:color/white"
      android:textColor="@android:color/black"
      android:textSize="30sp">
</TextView>

B: NumPad/res/layout/keyboard_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

C: NumPad/res/xml/method.xml

<?xml version="1.0" encoding="utf-8"?>
<input-method  xmlns:android="http://schemas.android.com/apk/res/android">
    <subtype  android:imeSubtypeMode="keyboard"/>
</input-method>

D: Numpad/res/xml/number_pad.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Of course this can be easily edited to your liking. You can even use images instead lf words for the label.

Suragch didnt demonstrate the files in the values folder and assumed we had access to Android Studio; which automatically creates them. Good thing I have APK Builder.

E: NumPad/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

F: NumPad/res/values/strings.xml

<resources>
    <string name="app_name">Suragch NumPad</string>
</resources>

G: NumPad/res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

H: Numpad/AndroidManifest.xml

This is the file that was really up for contension. Here I felt I would never compile my program. sob. sob. If you check Suracgh's answer you see he leaves the first set of fields empty, and adds the activity tag in this file. As I said there are four types of Android programs. An activity is a regular app with a launcher icon. This numpad is not an activity! Further he didnt implement any activity.

My friends do not include the activity tag. Your program will compile, and when you try to launch it will crash! As for xmlns:android and uses-sdk; I cant help you there. Just try my settings if they work.

As you can see there is a service tag, which register it as a service. Also service.android:name must be name of public class extending service in our java file. It MUST be capitalized accordingly. Also package is the name of the package we declared in java file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Saragch.num_pad">

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="27" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/Suragch_NumPad_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">

            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>

            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>

        </service>

    </application>
</manifest>

I: NumPad/src/Saragch/num_pad/MyInputMethodService.java

Note: I think java is an alternative to src.

This was another problem file but not as contentious as the manifest file. As I know Java good enough to know what is what, what is not. I barely know xml and how it ties in with Android development!

The problem here was he didnt import anything! I mean, he gave us a "complete" file which uses names that couldnt be resolved! InputMethodService, Keyboard, etc. That is bad practice Mr. Suragch. Thanks for helping me out but how did you expect the code to compile if the names cant be resolved?

Following is the correctly edited version. I just happened to pounce upon couple hints to drove me to the right place to learn what exactly to import.

package Saragch.num_pad;

import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.Keyboard;

import android.text.TextUtils;
import android.view.inputmethod.InputConnection;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener 
{
    @Override
    public View onCreateInputView() 
    {
     // get the KeyboardView and add our Keyboard layout to it
     KeyboardView keyboardView = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view, null);
     Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
     keyboardView.setKeyboard(keyboard);
     keyboardView.setOnKeyboardActionListener(this);
     return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) 
    {

        InputConnection ic = getCurrentInputConnection();

        if (ic == null) return;

        switch (primaryCode)
        {
         case Keyboard.KEYCODE_DELETE:
            CharSequence selectedText = ic.getSelectedText(0);

            if (TextUtils.isEmpty(selectedText)) 
            {
             // no selection, so delete previous character
             ic.deleteSurroundingText(1, 0);
            }

            else 
            {
             // delete the selection
             ic.commitText("", 1);
            }

            ic.deleteSurroundingText(1, 0);
            break;

         default:
            char code = (char) primaryCode;
            ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}
  1. Compile and sign your project.

    This is where I am clueless as a newby Android developer. I would like to learn it manually, as I believe real programmers can compile manually.

I think gradle is one of the tools for compiling and packaging to apk. apk seems to be like a jar file or a rar for zip file. There are then two types of signing. debug key which is not alllowed on play store and private key.

Well lets give Mr. Saragch a hand. And thank you for watching my video. Like, subscribe.

NuGet Package Restore Not Working

None of the other solutions worked in my situation:

AspNetCore dependencies had been installed/uninstalled and were being cached. 'AspNetCore.All' would refuse to properly update/reinstall/remove. And regardless of what i did, it would use the cached dependencies (that it was not compatible with), because they were a higher version.

  1. Backup Everything. Note the list of Dependencies you'll need to reinstall, Exit VisualStudio
  2. Open up all .proj files in a text editor and remove all PackageReference
  3. In each project, delete the bin, obj folders
  4. Delete any "packages" folders you find in the solution.
  5. Open solution, go into Tools > Nuget Package Manager > Package Manager Settings and Clear all Nuget caches. Check the console because it may fail to remove some items - copy the folder path and exit visual studio.
  6. Delete anything from that folder Reopen solution and start installing nuget packages again from scratch.

If that still doesn't work, repeat but also search your drive in windows explorer for nuget and delete anything cachey looking.

Using ffmpeg to encode a high quality video

You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.

Try something like this:

ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg

How can I get a specific field of a csv file?

Finaly I got it!!!

import csv

def select_index(index):
    csv_file = open('oscar_age_female.csv', 'r')
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        l = line['Index']
        if l == index:
            print(line[' "Name"'])

select_index('11')

"Bette Davis"

Get integer value from string in swift

In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"
    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"
    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"
    if let stringToFloat = Float(stringNumb){
        let someNumb = Int(stringToFloat)// 13 as Integer
    }else{
       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
    }

C# ASP.NET Single Sign-On Implementation

There are multiple options to implement SSO for a .NET application.

Check out the following tutorials online:

Basics of Single Sign on, July 2012

http://www.codeproject.com/Articles/429166/Basics-of-Single-Sign-on-SSO

GaryMcAllisterOnline: ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2), Jan 2013

http://garymcallisteronline.blogspot.com/2013/01/aspnet-mvc-4-adfs-20-and-3rd-party-sts.html

The first one uses ASP.NET Web Forms, while the second one uses ASP.NET MVC4.

If your requirements allow you to use a third-party solution, also consider OpenID. There's an open source library called DotNetOpenAuth.

For further information, read MSDN blog post Integrate OpenAuth/OpenID with your existing ASP.NET application using Universal Providers.

Hope this helps!

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

This is just a workaround solution:

In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.

In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.

Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.

My solution:

Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"

Unix-Machines

  1. Add following lines to a config's [alias] section. This command lists all changed (i.e. modified/new) files:

    lc = "!f() { git status --porcelain \
                 | egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
                 | cut -c 4- ; }; f "
    
  2. Convert all those changed files into dos format:

    unix2dos $(git lc)
    
  3. Optionally ...

    1. Create a git hook for this action to automate this process

    2. Use params and include it and modify the grep function to match only particular filenames, e.g.:

      ... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
      
    3. Feel free to make it even more convenient by using an additional shortcut:

      c2dos = "!f() { unix2dos $(git lc) ; }; f "
      

      ... and fire the converted stuff by typing

      git c2dos
      

Counting the number of non-NaN elements in a numpy ndarray in Python

To determine if the array is sparse, it may help to get a proportion of nan values

np.isnan(ndarr).sum() / ndarr.size

If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/

Using sudo with Python script

I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for moreinformation.

#!/usr/bin/env python
import subprocess

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()

cmd1 = subprocess.Popen(['echo',sudoPassword], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = cmd2.stdout.read.decode()

How to download all files (but not HTML) from a website using wget?

You may try:

wget --user-agent=Mozilla --content-disposition --mirror --convert-links -E -K -p http://example.com/

Also you can add:

-A pdf,ps,djvu,tex,doc,docx,xls,xlsx,gz,ppt,mp4,avi,zip,rar

to accept the specific extensions, or to reject only specific extensions:

-R html,htm,asp,php

or to exclude the specific areas:

-X "search*,forum*"

If the files are ignored for robots (e.g. search engines), you've to add also: -e robots=off

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

I just made marc_s "presentation ready":

SELECT 
    c.name 'Column Name',
    t.name 'Data type',
    IIF(t.name = 'nvarchar', c.max_length / 2, c.max_length) 'Max Length',
    c.precision 'Precision',
    c.scale 'Scale',
    IIF(c.is_nullable = 0, 'No', 'Yes') 'Nullable',
    IIF(ISNULL(i.is_primary_key, 0) = 0, 'No', 'Yes') 'Primary Key'
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
    c.object_id = OBJECT_ID('YourTableName')

jQuery animate backgroundColor

I stumbled across this page with the same issue, but the following problems:

  1. I can't include an extra jQuery plugin file with my current set-up.
  2. I'm not comfortable pasting large blocks of code that I don't have time to read over and validate.
  3. I don't have access to the css.
  4. I hardly had any time for implementation (it was only a visual improvement to an admin page)

With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:

element
  .css('color','#FF0000')
;
$('<div />')
  .css('width',0)
  .animate(
    {'width':100},
    {
      duration: 3000,
      step:function(now){
        var v = (255 - 255/100 * now).toString(16);
        v = (v.length < 2 ? '0' : '') + v.substr(0,2);
        element.css('color','#'+v+'0000');
      }
    }
  )
;

The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width - which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.

The same could have been achieved with setInterval, but by using this method you can benefit from jQuery's animation methods - like .stop() - and you can use easing and duration.

Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)

No Multiline Lambda in Python: Why not?

[Edit] Read this answer. It explains why multiline lambda is not a thing.

Simply put, it's unpythonic. From Guido van Rossum's blog post:

I find any solution unacceptable that embeds an indentation-based block in the middle of an expression. Since I find alternative syntax for statement grouping (e.g. braces or begin/end keywords) equally unacceptable, this pretty much makes a multi-line lambda an unsolvable puzzle.

How to secure database passwords in PHP?

Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter

vb.net get file names in directory?

Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String

For Each fileName In fileEntries
    If (System.IO.File.Exists(fileName)) Then
        'Read File and Print Result if its true
        ReadFile(fileName)
    End If
    TransfereFile(fileName, 1)
Next

LINQ extension methods - Any() vs. Where() vs. Exists()

Just so you can find it next time, here is how you search for the enumerable Linq extensions. The methods are static methods of Enumerable, thus Enumerable.Any, Enumerable.Where and Enumerable.Exists.

As the third returns no usable result, I found that you meant List.Exists, thus:

I also recommend hookedonlinq.com as this is has very comprehensive and clear guides, as well clear explanations of the behavior of Linq methods in relation to deferness and lazyness.

Android: Expand/collapse animation

Here is my solution. I think it is simpler. It only expands the view but can easy be extended.

public class WidthExpandAnimation extends Animation
{
    int _targetWidth;
    View _view;

    public WidthExpandAnimation(View view)
    {
        _view = view;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t)
    {
        if (interpolatedTime < 1.f)
        {
            int newWidth = (int) (_targetWidth * interpolatedTime);

            _view.layout(_view.getLeft(), _view.getTop(),
                    _view.getLeft() + newWidth, _view.getBottom());
        }
        else
            _view.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight)
    {
        super.initialize(width, height, parentWidth, parentHeight);

        _targetWidth = width;
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Run command - npm init No file directory found issue got resolved

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

What would be the Unicode character for big bullet in the middle of the character?

You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.

Beware that few fonts contain these characters.

Vue.js redirection to another page

You can also use the v-bind directly to the template like ...

<a :href="'/path-to-route/' + IdVariable">

the : is the abbreviation of v-bind.

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

I am running WHM 10.2.15-MariaDB. To permanently disable strict mode first find out which configuration file our installation prefers. For that, we need the binary’s location:

$ which mysqld
/usr/sbin/mysqld

Then, we use this path to execute the lookup:

$ /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

We can see that the first favored configuration file is one in the root of the etc folder but that there is a second .cnf file hidden - ~/.my.cnf. Adding the following to the ~/.my.cnf file permanently disabled strict mode for me (needs to be within the mysqld section):

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

I found that adding the line to /etc/my.cnf had no effect at all apart from sending me crazy.

How to read a file into a variable in shell?

this works for me: v=$(cat <file_path>) echo $v

How to update a value, given a key in a hashmap?

Use Java8 built in fuction 'computeIfPresent'

Example:

public class ExampleToUpdateMapValue {

    public static void main(String[] args) {
        Map<String,String> bookAuthors = new TreeMap<>();
        bookAuthors.put("Genesis","Moses");
        bookAuthors.put("Joshua","Joshua");
        bookAuthors.put("Judges","Samuel");

        System.out.println("---------------------Before----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
        // To update the existing value using Java 8
        bookAuthors.computeIfPresent("Judges", (k,v) -> v = "Samuel/Nathan/Gad");

        System.out.println("---------------------After----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
    }
}

Spark: subtract two DataFrames

In pyspark DOCS it would be subtract

df1.subtract(df2)

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

wildcard * in CSS for classes

An alternative solution:

div[class|='tocolor'] will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.

Beware that this won't match

<div class="foo tocolor-">

Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation

[att|=val]

Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)

Git Diff with Beyond Compare

For MAC after doing lot of research it worked for me..! 1. Install the beyond compare and this will be installed in below location

/Applications/Beyond\ Compare.app/Contents/MacOS/bcomp

Please follow these steps to make bc as diff/merge tool in git http://www.scootersoftware.com/support.php?zz=kb_mac

How to Set Focus on JTextField?

If the page contains multiple item and like to set the tab sequence and focus I will suggest to use FocusTraversalPolicy.

grabFocus() will not work if you are using FocusTraversalPolicy.

Sample code

int focusNumber = 0;
Component[] focusList;
focusList = new Component[] { game, move, amount, saveButton,
            printButton, editButton, deleteButton, newButton,
            settingsButton };

frame.setFocusTraversalPolicy(new FocusTraversalPolicy() {

        @Override
        public Component getLastComponent(Container aContainer) {
            return focusList[focusList.length - 1];
        }

        @Override
        public Component getFirstComponent(Container aContainer) {
            return focusList[0];
        }

        @Override
        public Component getDefaultComponent(Container aContainer) {
            return focusList[1];
        }

        @Override
        public Component getComponentAfter(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusNumber + 1) % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentAfter(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }

        @Override
        public Component getComponentBefore(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusList.length + focusNumber - 1)
                    % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentBefore(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }
    });

Making a <button> that's a link in HTML

IMPORTANT: <button> should never be a descendent of <a>.

Try <a href="http://stackoverflow.com"><button>Link Text</button></a> in any html validator like https://validator.w3.org and you'll get an error. There's really no point in using a button if you're not using the button. Just style the <a> with css to look like a button. If you're using a framework like Bootstrap, you could apply the button style(s) btn, btn-primary etc.

jsfiddle : button styled link

_x000D_
_x000D_
.btnStack {_x000D_
  font-family: Oswald;_x000D_
  background-color: orange;_x000D_
  color: white;_x000D_
  text-decoration: none;_x000D_
  display: inline-block;_x000D_
  padding: 6px 12px;_x000D_
  margin-bottom: 0;_x000D_
  font-size: 14px;_x000D_
  font-weight: normal;_x000D_
  line-height: 1.428571429;_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  cursor: pointer;_x000D_
  border: 1px solid transparent;_x000D_
  border-radius: 4px;_x000D_
  -webkit-user-select: none;_x000D_
  -moz-user-select: none;_x000D_
  -ms-user-select: none;_x000D_
  -o-user-select: none;_x000D_
  user-select: none;_x000D_
}_x000D_
_x000D_
a.btnStack:hover {_x000D_
  background-color: #000;_x000D_
}
_x000D_
<link href='https://fonts.googleapis.com/css?family=Oswald:400' rel='stylesheet' type='text/css'>_x000D_
<a href="http://stackoverflow.com" class="btnStack">stackoverflow.com</a>
_x000D_
_x000D_
_x000D_

Search and replace part of string in database

update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')

and you do it in a single pass.

Check if a value is in an array (C#)

Add necessary namespace

using System.Linq;

Then you can use linq Contains() method

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

anaconda update all possible packages?

Imagine the dependency graph of packages, when the number of packages grows large, the chance of encountering a conflict when upgrading/adding packages is much higher. To avoid this, simply create a new environment in Anaconda.

Be frugal, install only what you need. For me, I installed the following packages in my new environment:

  • pandas
  • scikit-learn
  • matplotlib
  • notebook
  • keras

And I have 84 packages in total.

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

if __name__ == '__main__':
    Example().main()

But you really shouldn't be using a class just to run your main code.

How do I replace multiple spaces with a single space in C#?

no Regex, no Linq... removes leading and trailing spaces as well as reducing any embedded multiple space segments to one space

string myString = "   0 1 2  3   4               5  ";
myString = string.Join(" ", myString.Split(new char[] { ' ' }, 
StringSplitOptions.RemoveEmptyEntries));

result:"0 1 2 3 4 5"

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

What are the use cases for selecting CHAR over VARCHAR in SQL?

It's the classic space versus performance tradeoff.

In MS SQL 2005, Varchar (or NVarchar for lanuagues requiring two bytes per character ie Chinese) are variable length. If you add to the row after it has been written to the hard disk it will locate the data in a non-contigious location to the original row and lead to fragmentation of your data files. This will affect performance.

So, if space is not an issue then Char are better for performance but if you want to keep the database size down then varchars are better.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

What is the difference between the HashMap and Map objects in Java?

I was just going to do this as a comment on the accepted answer but it got too funky (I hate not having line breaks)

ah, so the difference is that in general, Map has certain methods associated with it. but there are different ways or creating a map, such as a HashMap, and these different ways provide unique methods that not all maps have.

Exactly--and you always want to use the most general interface you possibly can. Consider ArrayList vs LinkedList. Huge difference in how you use them, but if you use "List" you can switch between them readily.

In fact, you can replace the right-hand side of the initializer with a more dynamic statement. how about something like this:

List collection;
if(keepSorted)
    collection=new LinkedList();
else
    collection=new ArrayList();

This way if you are going to fill in the collection with an insertion sort, you would use a linked list (an insertion sort into an array list is criminal.) But if you don't need to keep it sorted and are just appending, you use an ArrayList (More efficient for other operations).

This is a pretty big stretch here because collections aren't the best example, but in OO design one of the most important concepts is using the interface facade to access different objects with the exact same code.

Edit responding to comment:

As for your map comment below, Yes using the "Map" interface restricts you to only those methods unless you cast the collection back from Map to HashMap (which COMPLETELY defeats the purpose).

Often what you will do is create an object and fill it in using it's specific type (HashMap), in some kind of "create" or "initialize" method, but that method will return a "Map" that doesn't need to be manipulated as a HashMap any more.

If you ever have to cast by the way, you are probably using the wrong interface or your code isn't structured well enough. Note that it is acceptable to have one section of your code treat it as a "HashMap" while the other treats it as a "Map", but this should flow "down". so that you are never casting.

Also notice the semi-neat aspect of roles indicated by interfaces. A LinkedList makes a good stack or queue, an ArrayList makes a good stack but a horrific queue (again, a remove would cause a shift of the entire list) so LinkedList implements the Queue interface, ArrayList does not.

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

Decreasing for loops in Python impossible?

For python3 where -1 indicate the value that to be decremented in each step for n in range(6,0,-1): print(n)

How to npm install to a specified directory?

I am using a powershell build and couldn't get npm to run without changing the current directory.

Ended up using the start command and just specifying the working directory:

start "npm" -ArgumentList "install --warn" -wo $buildFolder

On postback, how can I check which control cause postback in Page_Init event

if (Request.Params["__EVENTTARGET"] != null)
{
  if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
  {
    DoWhateverYouWant();
  }
}

Bootstrap: How do I identify the Bootstrap version?

The easiest would be to locate the bootstrap file (bootstrap.css OR bootstrap.min.css) and read through the docblock, you'll see something like this

Bootstrap v3.3.6 (http://getbootstrap.com)

CSS Margin: 0 is not setting to 0

You need to set the actual page to margin:0 and padding: 0 to the actual html, not just the body.

use this in your css stylesheet.

*, html {
    margin:0;
    padding:0;  
}

that will set the whole page to 0, for a fresh clean start with no margin or paddings.

Make Axios send cookies in its requests automatically

What worked for me:

Client Side:

import axios from 'axios';

const url = 'http://127.0.0.1:5000/api/v1';

export default {
  login(credentials) {
    return axios
      .post(`${url}/users/login/`, credentials, {
        withCredentials: true,
        credentials: 'include',
      })
      .then((response) => response.data);
  },
};

Server Side:

const express = require('express');
const cors = require('cors');

const app = express();
const port = process.env.PORT || 5000;

app.use(
  cors({
    origin: [`http://localhost:${port}`, `https://localhost:${port}`],
    credentials: 'true',
  })
);

How to install easy_install in Python 2.7.1 on Windows 7

I recently used ez_setup.py as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:

Installing easy_install Using ez_setup.py

I hope you find this helpful.

Set new id with jQuery

Did you try

$(this).val('test');

instead of

$(this).attr('value', 'test');

val() is generally easier, since the attribute you need to change may be different on different DOM elements.

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

How to change row color in datagridview?

You're looking for the CellFormatting event.
Here is an example.

How to parse JSON using Node.js?

Using JSON for your configuration with Node.js? Read this and get your configuration skills over 9000...

Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!

Proper applications come in 3+ layers of configuration:

  1. Server/Container config
  2. Application config
  3. (optional) Tenant/Community/Organization config
  4. User config

Most developers treat their server and app config as if it can change. It can't. You can layer changes from higher layers on top of each other, but you're modifying base requirements. Some things need to exist! Make your config act like it's immutable, because some of it basically is, just like your source code.

Failing to see that lots of your stuff isn't going to change after startup leads to anti-patterns like littering your config loading with try/catch blocks, and pretending you can continue without your properly setup application. You can't. If you can, that belongs in the community/user config layer, not the server/app config layer. You're just doing it wrong. The optional stuff should be layered on top when the application finishes it's bootstrap.

Stop banging your head against the wall: Your config should be ultra simple.

Take a look at how easy it is to setup something as complex as a protocol-agnostic and datasource-agnostic service framework using a simple json config file and simple app.js file...

container-config.js...

{
    "service": {
        "type"  : "http",
        "name"  : "login",
        "port"  : 8085
    },
    "data": {
        "type"  : "mysql",
        "host"  : "localhost",
        "user"  : "notRoot",
        "pass"  : "oober1337",
        "name"  : "connect"
    }
}

index.js... (the engine that powers everything)

var config      = require('./container-config.json');       // Get our service configuration.
var data        = require(config.data.type);            // Load our data source plugin ('npm install mysql' for mysql).
var service     = require(config.service.type);         // Load our service plugin ('http' is built-in to node).
var processor   = require('./app.js');                  // Load our processor (the code you write).

var connection  = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server      = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });

app.js... (the code that powers your protocol-agnostic and data-source agnostic service)

module.exports = function(request, response){
    response.end('Responding to: ' + request.url);
}

Using this pattern, you can now load community and user config stuff on top of your booted app, dev ops is ready to shove your work into a container and scale it. You're read for multitenant. Userland is isolated. You can now separate the concerns of which service protocol you're using, which database type you're using, and just focus on writing good code.

Because you're using layers, you can rely on a single source of truth for everything, at any time (the layered config object), and avoid error checks at every step, worrying about "oh crap, how am I going to make this work without proper config?!?".

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I didn't have an issue with this until I tried to use the Location Services, at which point I had to put the apply plugin: 'com.google.gms.google-services' at the bottom of the file, rather than the top. The reason being that when you have it at the top there are collision issues, and by placing it at the bottom, you avoid those issue.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Can I pass an array as arguments to a method with variable arguments in Java?

Yes, a T... is only a syntactic sugar for a T[].

JLS 8.4.1 Format parameters

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.

Here's an example to illustrate:

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("\0", "[ %s ]");
    return String.format(format, args);
}
public static void main(String... args) {
    System.out.println(ezFormat("A", "B", "C"));
    // prints "[ A ][ B ][ C ]"
}

And yes, the above main method is valid, because again, String... is just String[]. Also, because arrays are covariant, a String[] is an Object[], so you can also call ezFormat(args) either way.

See also


Varargs gotchas #1: passing null

How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.

Consider this example:

static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!

Due to how varargs are resolved, the last statement invokes with objs = null, which of course would cause NullPointerException with objs.length. If you want to give one null argument to a varargs parameter, you can do either of the following:

count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"

Related questions

The following is a sample of some of the questions people have asked when dealing with varargs:


Vararg gotchas #2: adding extra arguments

As you've found out, the following doesn't "work":

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(myArgs, "Z"));
    // prints "[ [Ljava.lang.String;@13c5982 ][ Z ]"

Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[], the second being a String. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

Here are some useful helper methods:

static <T> T[] append(T[] arr, T lastElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    arr[N] = lastElement;
    return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    System.arraycopy(arr, 0, arr, 1, N);
    arr[0] = firstElement;
    return arr;
}

Now you can do the following:

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(append(myArgs, "Z")));
    // prints "[ A ][ B ][ C ][ Z ]"

    System.out.println(ezFormat(prepend(myArgs, "Z")));
    // prints "[ Z ][ A ][ B ][ C ]"

Varargs gotchas #3: passing an array of primitives

It doesn't "work":

    int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:

    Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had this error when I tried to create a replicationcontroller. The issue was, I wrongly spelt the nginx image name in template definition.

Note: This error occurs when kubernetes is unable to pull the specified image from the repository.

Convert a Unicode string to an escaped ASCII string

Here is my current implementation:

public static class UnicodeStringExtensions
{
    public static string EncodeNonAsciiCharacters(this string value) {
        var bytes = Encoding.Unicode.GetBytes(value);
        var sb = StringBuilderCache.Acquire(value.Length);
        bool encodedsomething = false;
        for (int i = 0; i < bytes.Length; i += 2) {
            var c = BitConverter.ToUInt16(bytes, i);
            if ((c >= 0x20 && c <= 0x7f) || c == 0x0A || c == 0x0D) {
                sb.Append((char) c);
            } else {
                sb.Append($"\\u{c:x4}");
                encodedsomething = true;
            }
        }
        if (!encodedsomething) {
            StringBuilderCache.Release(sb);
            return value;
        }
        return StringBuilderCache.GetStringAndRelease(sb);
    }


    public static string DecodeEncodedNonAsciiCharacters(this string value)
      => Regex.Replace(value,/*language=regexp*/@"(?:\\u[a-fA-F0-9]{4})+", Decode);

    static readonly string[] Splitsequence = new [] { "\\u" };
    private static string Decode(Match m) {
        var bytes = m.Value.Split(Splitsequence, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => ushort.Parse(s, NumberStyles.HexNumber)).SelectMany(BitConverter.GetBytes).ToArray();
        return Encoding.Unicode.GetString(bytes);
    }
}

This passes a test:

public void TestBigUnicode() {
    var s = "\U00020000";
    var encoded = s.EncodeNonAsciiCharacters();
    var decoded = encoded.DecodeEncodedNonAsciiCharacters();
    Assert.Equals(s, decoded);
}

with the encoded value: "\ud840\udc00"

This implementation makes use of a StringBuilderCache (reference source link)

Split a string by another string in C#

string data = "THExxQUICKxxBROWNxxFOX";

return data.Replace("xx","|").Split('|');

Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!

How to create streams from string in Node.Js?

Do not use Jo Liss's resumer answer. It will work in most cases, but in my case it lost me a good 4 or 5 hours bug finding. There is no need for third party modules to do this.

NEW ANSWER:

var Readable = require('stream').Readable

var s = new Readable()
s.push('beep')    // the string you want
s.push(null)      // indicates end-of-file basically - the end of the stream

This should be a fully compliant Readable stream. See here for more info on how to use streams properly.

OLD ANSWER: Just use the native PassThrough stream:

var stream = require("stream")
var a = new stream.PassThrough()
a.write("your string")
a.end()

a.pipe(process.stdout) // piping will work as normal
/*stream.on('data', function(x) {
   // using the 'data' event works too
   console.log('data '+x)
})*/
/*setTimeout(function() {
   // you can even pipe after the scheduler has had time to do other things
   a.pipe(process.stdout) 
},100)*/

a.on('end', function() {
    console.log('ended') // the end event will be called properly
})

Note that the 'close' event is not emitted (which is not required by the stream interfaces).

Can't push to GitHub because of large file which I already deleted

My unorthodox but simple solution from scratch:

  • just forget about your recent problematic local git repository and git clone your repository into a fresh new directory.
  • git remote add upstream <your github rep here>
  • git pull upstream master
  • at this point just copy your new files to commit, to your new local rep from the old one may be including your now reduced giant file(s).
  • git add .
  • git commit -m "your commit text here"
  • git push origin master

voila! worked like a charm in my case.

How to convert minutes to hours/minutes and add various time values together using jQuery?

I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.

function minutesToHHMM (mins, twentyFour = false) {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  m = m < 10 ? '0' + m : m;

  if (twentyFour) {
    h = h < 10 ? '0' + h : h;
    return `${h}:${m}`;
  } else {
    let a = 'am';
    if (h >= 12) a = 'pm';
    if (h > 12) h = h - 12;
    return `${h}:${m} ${a}`;
  }
}

.setAttribute("disabled", false); changes editable attribute to false

Just set the property directly: .

eleman.disabled = false;

List of enum values in java

Yes it is definitely possible, but you will have to do

List<MyEnum> al = new ArrayList<MyEnum>();

You can then add elements to al: al.add(ONE) or al.add(TWO).

How do I empty an input value with jQuery?

You could try:

$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');

Using Python's os.path, how do I go up one directory?

To get the folder of a file just use:

os.path.dirname(path) 

To get a folder up just use os.path.dirname again

os.path.dirname(os.path.dirname(path))

You might want to check if __file__ is a symlink:

if os.path.islink(__file__): path = os.readlink (__file__)

Word wrap for a label in Windows Forms

Have a better one based on @hypo 's answer

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

int width = this.Parent == null ? this.Width : this.Parent.Width; this allows you to use auto-grow label when docked to a parent, e.g. a panel.

this.Height = sz.Height + Padding.Bottom + Padding.Top; here we take care of padding for top and bottom.

Eclipse error: 'Failed to create the Java Virtual Machine'

I know this is pretty old now but I have just had the same issue and the problem was I was allocating to much memory to eclipse that it could not get hold of. So open eclipse.ini and lower the amount of memory that is being allocated to -Xmx XXMaxPermSize I changed mine to -Xmx512m and XXMaxPermSize256m

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.

Your module should be :

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ContactComponent
  ]
})
export class ContactModule {}

Make: how to continue after a command fails?

Put an -f option in your rm command.

rm -f .lambda .lambda_t .activity .activity_t_lambda

Laravel assets url

You have to do two steps:

  1. Put all your files (css,js,html code, etc.) into the public folder.
  2. Use url({{ URL::asset('images/slides/2.jpg') }}) where images/slides/2.jpg is path of your content.

Similarly you can call js, css etc.

What's the difference between %s and %d in Python string formatting?

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

obviously

print('%d' % (name))

will generate an exception; you cannot convert string to number

How to configure Fiddler to listen to localhost?

You cannot. Instead if you machine is named "myMachine", point your browser to http://mymachine instead of http://localhost

Running Python on Windows for Node.js dependencies

Here is the correct command: set path=%path%;C:\Python34 [Replace with the correct path of your python installation]

I had the same problem and I just solved this like that.

As some other people pointed out, this is volatile configuration, it only works for the current cmd session, and (obviously) you have to set your path before you run npm install.

I hope this helps.

SVG rounded corner

I'd also consider using a plain old <rect> which provides the rx and ry attributes

MDN SVG docs <- note the second drawn rect element

Display Adobe pdf inside a div

You could create an image thumbnail, and link it to the actual pdf as an inline popup using something like http://orangoo.com/labs/GreyBox/

Implement a simple factory pattern with Spring 3 annotations

I suppose you to use org.springframework.beans.factory.config.ServiceLocatorFactoryBean. It will much simplify your code. Except MyServiceAdapter u can only create interface MyServiceAdapter with method MyService getMyService and with alies to register your classes

Code

bean id="printStrategyFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
        <property name="YourInterface" value="factory.MyServiceAdapter" />
    </bean>

    <alias name="myServiceOne" alias="one" />
    <alias name="myServiceTwo" alias="two" />

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

angular 2 sort and filter

This is my sort. It will do number sort , string sort and date sort .

import { Pipe , PipeTransform  } from "@angular/core";

@Pipe({
  name: 'sortPipe'
 })

export class SortPipe implements PipeTransform {

    transform(array: Array<string>, key: string): Array<string> {

        console.log("Entered in pipe*******  "+ key);


        if(key === undefined || key == '' ){
            return array;
        }

        var arr = key.split("-");
        var keyString = arr[0];   // string or column name to sort(name or age or date)
        var sortOrder = arr[1];   // asc or desc order
        var byVal = 1;


        array.sort((a: any, b: any) => {

            if(keyString === 'date' ){

                let left    = Number(new Date(a[keyString]));
                let right   = Number(new Date(b[keyString]));

                return (sortOrder === "asc") ? right - left : left - right;
            }
            else if(keyString === 'name'){

                if(a[keyString] < b[keyString]) {
                    return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
                } else if (a[keyString] > b[keyString]) {
                    return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
                } else {
                    return 0;
                }  
            }
            else if(keyString === 'age'){
                return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
            }

        });

        return array;

  }

}

How to TryParse for Enum value?

enum EnumStatus
{
    NAO_INFORMADO = 0,
    ENCONTRADO = 1,
    BLOQUEADA_PELO_ENTREGADOR = 2,
    DISPOSITIVO_DESABILITADO = 3,
    ERRO_INTERNO = 4,
    AGARDANDO = 5
}

...

if (Enum.TryParse<EnumStatus>(item.status, out status)) {

}

How can I truncate a datetime in SQL Server?

Oracle:

TRUNC(SYSDATE, 'MONTH')

SQL Server:

DATEADD(DAY, - DATEPART(DAY, DateField) + 1, DateField)

Could be similarly used for truncating minutes or hours from a date.

How should I throw a divide by zero exception in Java without actually dividing by zero?

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");
}

Android Studio not showing modules in project structure

If you moved the modules, modify your workspace.xml file and settings.gradle file to use the new paths of your module. Otherwise you will need to try using the import module feature.

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

How to disable/enable a button with a checkbox if checked

You can use onchangeevent of the checkbox to enable/disable button based on checked value

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

<input type="checkbox"  onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />

Print Html template in Angular 2 (ng-print in Angular 2)

Shortest solution to be assign the window to a typescript variable then call the print method on that, like below

in template file

<button ... (click)="window.print()" ...>Submit</button>

and, in typescript file

window: any;
constructor() {
  this.window = window;
}

Styling input buttons for iPad and iPhone

Use the below css

_x000D_
_x000D_
input[type="submit"] {_x000D_
  font-size: 20px;_x000D_
  background: pink;_x000D_
  border: none;_x000D_
  padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
   appearance: none;_x000D_
   border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  margin: 25px 0 10px;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
_x000D_
_x000D_

Excel VBA - How to Redim a 2D array?

Here ya go.

Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

Yarn install command error No such file or directory: 'install'

The following steps worked on Pop!_OS 20.10 & ubuntu 20.04

  1. sudo apt remove cmdtest
  2. sudo apt remove yarn
  3. curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
  4. echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
  5. sudo apt-get update
  6. sudo apt-get install yarn -y
  7. yarn install

Export P7b file with all the certificate chain into CER file

The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try

openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM

and see for yourself.

How to change Status Bar text color in iOS

This worked for me:

  1. Set the UIViewControllerBasedStatusBarAppearance to YES in the plist

  2. The rootViewController needs the method implementation for

    -(UIStatusBarStyle)preferredStatusBarStyle
    

Because my rootViewController is managed by Cocoapods (JASidePanelController) I added this method through a category:

#import "JASidePanelController+StatusBarStyle.h"

@implementation JASidePanelController (StatusBarStyle)

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

@end

How to display HTML <FORM> as inline element?

You can try this code:

<form action="#" method="get" id="login" style=" display:inline!important;">

  <label for='User'>User:</label> 
  <input type='text' name='User' id='User'>

  <label for='password'>Password:</label><input type='password' name='password' id='password'>
  <input type="submit" name="log" id="log" class="botton" value="Login" />

</form> 

The important thing to note is the css style property in the <form> tag.

display:inline!important;

Node.js get file extension

import extname in order to return the extension the file:

import { extname } from 'path';
extname(file.originalname);

where file is the file 'name' of form

When to use std::size_t?

Use std::size_t for indexing/counting C-style arrays.

For STL containers, you'll have (for example) vector<int>::size_type, which should be used for indexing and counting vector elements.

In practice, they are usually both unsigned ints, but it isn't guaranteed, especially when using custom allocators.

Single statement across multiple lines in VB.NET without the underscore character

No, the underscore is the only continuation character. Personally I prefer the occasional use of a continuation character to being forced to use it always as in C#, but apart from the comments issue (which I'd agree is sometimes annoying), getting things to line up is not an issue.

With VS2008 at any rate, just select the second and following lines, hit the tab key several times, and it moves the whole lot across.

If it goes a tiny bit too far, you can delete the excess space a character at a time. It's a little fiddly, but it stays put once it's saved.

On the rare cases where this isn't good enough, I sometimes use the following technique to get it all to line up:

dim results as String = ""
results += "from a in articles "
results += "where a.articleID = 4 " 'and now you can add comments
results += "select a.articleName"

It's not perfect, and I know those that prefer C# will be tut-tutting, but there it is. It's a style choice, but I still prefer it to endless semi-colons.

Now I'm just waiting for someone to tell me I should have used a StringBuilder ;-)

How do I run msbuild from the command line using Windows SDK 7.1?

From Visual Studio 2013 onwards, MSbuild comes as a part of Visual Studio. Earlier, MSBuild was installed as a part of. NET Framework.

MSBuild is installed directly under %ProgramFiles%. So, the path for MSBuild might be different depending on the version of Visual Studio.

For Visual Studio 2015, Path of MSBuild is "%ProgramFiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe"

For Visual Studio 15 Preview, Path of MSBuild is "%ProgramFiles(x86)%\MSBuild\15.0\Bin\MSBuild.exe"

Also, Some new MSBuild properties has been added and some have been modified. For more information look here

Update 1: VS 2017

The location for the MSBuild has changed again with the release of Visual Studio 2017. Now the installation directory is under the %ProgramFiles(x86)%\Microsoft Visual Studio\2017\[VS Edition]\MSBuild\15.0\Bin\. Since, i have an Enterprise edition, the MSBuild location for my machine is "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSbuild.exe"

Changing navigation title programmatically

and also if you will try to create Navigation Bar manually this code will help you

func setNavBarToTheView() {
    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64.0))
    self.view.addSubview(navBar);
    let navItem = UINavigationItem(title: "Camera");
    let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(CameraViewController.onClickBack));
    navItem.leftBarButtonItem = doneItem;
    navBar.setItems([navItem], animated: true);
}

MySQL config file location - redhat linux server

On RH systems, MySQL configuration file is located under /etc/my.cnf by default.

Checking if a collection is empty in Java: which is the best method?

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:

Beware that, unlike in most collections, the size method is not a constant-time operation.

This is a clear case where isEmpty() is much more efficient than checking whether size()==0.

You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

How can I format a list to print each element on a separate line in python?

You can just use a simple loop: -

>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
        print elem 

10
12
14

Create a directly-executable cross-platform GUI app using Python

First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.

Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)

Of course, there are many, but the most popular that I've seen in wild are:

Complete list is at http://wiki.python.org/moin/GuiProgramming

Single executable (all platforms)

  • PyInstaller - the most active(Could also be used with PyQt)
  • fbs - if you chose Qt above

Single executable (Windows)

  • py2exe - used to be the most popular

Single executable (Linux)

  • Freeze - works the same way like py2exe but targets Linux platform

Single executable (Mac)

  • py2app - again, works like py2exe but targets Mac OS

How do I access an access array item by index in handlebars?

In my case I wanted to access an array inside a custom helper like so,

{{#ifCond arr.[@index] "foo" }}

Which did not work, but the answer suggested by @julesbou worked.

Working code:

{{#ifCond (lookup arr @index) "" }}

Hope this helps! Cheers.

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

MySQL - UPDATE multiple rows with different values in one query

I did it this way:

<update id="updateSettings" parameterType="PushSettings">
    <foreach collection="settings" item="setting">
        UPDATE push_setting SET status = #{setting.status}
        WHERE type = #{setting.type} AND user_id = #{userId};
    </foreach>
</update>

where PushSettings is

public class PushSettings {

    private List<PushSetting> settings;
    private String userId;
}

it works fine

How to change the background color of a UIButton while it's highlighted?

Try this if you have an image:

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

or see if showsTouchWhenHighlighted is enough for you.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

We may need more information. Here is what I did to reproduce on SQL Server 2008:

CREATE DATABASE [Test] ON  PRIMARY 
    ( 
    NAME = N'Test'
    , FILENAME = N'...Test.mdf' 
    , SIZE = 3072KB 
    , FILEGROWTH = 1024KB 
    )
    LOG ON 
    ( 
    NAME = N'Test_log'
    , FILENAME = N'...Test_log.ldf' 
    , SIZE = 1024KB 
    , FILEGROWTH = 10%
    )
    COLLATE SQL_Latin1_General_CP850_BIN2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyTable]
    (
    [SomeCol] [varchar](50) NULL
    ) ON [PRIMARY]
GO
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
GO
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable

Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Using the Script console at https://my-jenkins/script

import hudson.model.Job
import org.jenkinsci.plugins.workflow.job.WorkflowRun

Collection<Job> jobs = Jenkins.instance.getItem('My-Folder').getAllJobs()
for (int i = 0; i < jobs.size(); i++) {
  def job = jobs[i]
  for (int j = 0; j < job.builds.size(); j++) {
    WorkflowRun build = job.builds[j]
    if (build.isBuilding()) {
      println("Stopping $job ${build.number}")
      build.setResult(Result.FAILURE)
    }
  }
}

apache mod_rewrite is not working or not enabled

It's working.

my solution is:

1.create a test.conf into /etc/httpd/conf.d/test.conf

2.wrote some rule, like:

<Directory "/var/www/html/test">
RewriteEngine On
RewriteRule ^link([^/]*).html$ rewrite.php?link=$1 [L]
</Directory>

3.restart your Apache server.

4.try again yourself.

Home does not contain an export named Home

You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:

import Home from './layouts/Home'

or export your component without default which is called named export like this

import React, { Component } from 'react';

class Home extends Component{
    render(){
        return(
        <p className="App-intro">
          Hello Man
        </p>
        )
    }
} 

export {Home};

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

JQuery select2 set default value from an option in list?

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

Redirect to new Page in AngularJS using $location

this worked for me inside a directive and works without refreshing the baseurl (just adds the endpoint).Good for Single Page Apps with routing mechanism.

  $(location).attr('href', 'http://localhost:10005/#/endpoint') 

How can I convert a date to GMT?

After searching for an hour or two ,I've found a simple solution below.

const date = new Date(`${date from client} GMT`);

inside double ticks, there is a date from client side plust GMT.

I'm first time commenting, constructive criticism will be welcomed.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

c# search string in txt file

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

                foreach (var line in File.ReadLines(pathToFile))
                {
                    if (line.Contains("CustomerEN") && current == null)
                    {
                        current = new List<string>();
                        current.Add(line);
                    }
                    else if (line.Contains("CustomerEN") && current != null)
                    {
                        current.Add(line);
                    }
                }
                string s = String.Join(",", current);
                MessageBox.Show(s);

Format in kotlin string templates

A couple of examples:

infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)

val pi = 3.14159265358979323

println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

How do I execute a program from Python? os.system fails due to spaces in path

No need for sub-process, It can be simply achieved by

GitPath="C:\\Program Files\\Git\\git-bash.exe"# Application File Path in mycase its GITBASH
os.startfile(GitPath)

Dart SDK is not configured

Run this command:

$ echo "$(dirname $(which flutter))/cache/dart-sdk"

You'll get something like:

/home/lex/opt/flutter/bin/cache/dart-sdk

Enter that value as your Dart SDK path.

Export to csv/excel from kibana

I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

How to center the elements in ConstraintLayout

add these tag in your view

    app:layout_constraintCircleRadius="0dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"

and you can right click in design mode and choose center.

Is there a command for formatting HTML in the Atom editor?

There are a few packages for prettifying HTML. You can find them by searching the Atom package archive:

  1. Navigate to the Atom site
  2. Click the Packages link
  3. Enter "prettify" in the search box

Or just go to this link: https://atom.io/packages/search?q=prettify

Once you've selected a package that does what you want you can install it by using the command: apm install [package name] from the command line or install it using the interface in Preferences.

When the package is installed, follow its instructions for how to activate its capabilities.

How to merge remote changes at GitHub?

If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:

Switch to branch "foo" and update it:

$ git checkout foo
$ git pull

You can see the branches you've got by issuing command:

$ git branch

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add a list item to an existing unordered list?

Instead of

$("#header ul li:last")

try

$("#header ul")

Difference between "read commited" and "repeatable read"

Trying to explain this doubt with simple diagrams.

Read Committed: Here in this isolation level, Transaction T1 will be reading the updated value of the X committed by Transaction T2.

Read Committed

Repeatable Read: In this isolation level, Transaction T1 will not consider the changes committed by the Transaction T2.

enter image description here

How do I show the changes which have been staged?

The --cached didn't work for me, ... where, inspired by git log

git diff origin/<branch>..<branch> did.

Styling a input type=number

For Mozilla

input[type=number] { 
    -moz-appearance: textfield;
    appearance: textfield;
    margin: 0; 
}

For Chrome

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
      -webkit-appearance: none; 
      margin: 0; 
}

Compute mean and standard deviation by group for multiple variables in a data.frame

There are a few different ways to go about it. reshape2 is a helpful package. Personally, I like using data.table

Below is a step-by-step

If myDF is your data.frame:

library(data.table)
DT <- data.table(myDF)

DT

# this will get you your mean and SD's for each column
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x)))]

# adding a `by` argument will give you the groupings
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x))), by=ID]

# If you would like to round the values: 
DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID]

# If we want to add names to the columns 
wide <- setnames(DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID], c("ID", sapply(names(DT)[-1], paste0, c(".men", ".SD"))))

wide

   ID Obs.1.men Obs.1.SD Obs.2.men Obs.2.SD Obs.3.men Obs.3.SD
1:  1    35.333    8.021    36.333   10.214      33.0    9.644
2:  2    29.750    3.594    32.250    4.193      30.5    5.916
3:  3    41.500    4.950    43.500    4.950      39.0    4.243

Also, this may or may not be helpful

> DT[, sapply(.SD, summary), .SDcols=names(DT)[-1]]
        Obs.1 Obs.2 Obs.3
Min.    25.00 28.00 22.00
1st Qu. 29.00 31.00 27.00
Median  33.00 32.00 36.00
Mean    34.22 36.11 33.22
3rd Qu. 38.00 40.00 37.00
Max.    45.00 48.00 42.00

scp copy directory to another server with private key auth

or you can also do ( for pem file )

 scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/

Make new column in Panda dataframe by adding values from other columns

As of Pandas version 0.16.0 you can use assign as follows:

df = pd.DataFrame({"A": [1,2,3], "B": [4,6,9]})
df.assign(C = df.A + df.B)

# Out[383]: 
#    A  B   C
# 0  1  4   5
# 1  2  6   8
# 2  3  9  12

You can add multiple columns this way as follows:

df.assign(C = df.A + df.B,
          Diff = df.B - df.A,
          Mult = df.A * df.B)
# Out[379]: 
#    A  B   C  Diff  Mult
# 0  1  4   5     3     4
# 1  2  6   8     4    12
# 2  3  9  12     6    27

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

Lat Long calculations require precision, so use some type of decimal type and make the precision at least 2 higher than the number you will store in order to perform math calculations. I don't know about the my sql datatypes but in SQL server people often use float or real instead of decimal and get into trouble because these are are estimated numbers not real ones. So just make sure the data type you use is a true decimal type and not a floating decimal type and you should be fine.

How to pass parameters to a modal?

If you're not using AngularJS UI Bootstrap, here's how I did it.

I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.

angular.module('yourApp', []).
directive('myModal',
       ['$rootScope','$log','$compile',
function($rootScope,  $log,  $compile) {
    var _scope = null;
    var _element = null;
    var _onModalShow = function(event) {
        _element.after($compile(event.target)(_scope));
    };

    return {
        link: function(scope, element, attributes) {
            _scope = scope;
            _element = element;
            $(element).on('show.bs.modal',_onModalShow);
        }
    };
}]);

I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.

Note: The entire scope is now visible to your modal so you can also access $scope.users in it.

<div my-modal id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{aModel.userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

Remove insignificant trailing zeros from a number?

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

Changing default encoding of Python?

This fixed the issue for me.

import os
os.environ["PYTHONIOENCODING"] = "utf-8"

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

Set NOW() as Default Value for datetime datatype?

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

it should work for updates too

Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.

Upload failed You need to use a different version code for your APK because you already have one with version code 2

if you are using phonegap / cordova applications, just edit your config.xml and add the android-versionCode and version in the widget.

<widget id="com.xxx.yyy" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" android-versionCode="100001" version="1.0.1">

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

<hr> tag in Twitter Bootstrap not functioning correctly?

It is because Bootstrap's DEFAULT CSS for <hr /> is ::

hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eeeeee;
}

it creates 40px gap between those two lines

so if you want to change any particular <hr /> margin style in your page you may try something like this ::

<hr style="margin-bottom:5px !important; margin-top:5px !important; " />

if you want to change appearance/other styles of any particular <hr /> in your page like color and border type or thickness the you may try something like :

<hr style="border-top: 1px dotted #000000 !important; " />

for all <hr /> in your page

<style>
   hr {
       border-top: 1px dotted #000000 !important;
       margin-bottom:5px !important; 
       margin-top:5px !important;
   }
</style>

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Change the Bootstrap Modal effect

Modal In Out Effect with Animate.css and jquery Very easy and short code.

In HTML:

<div class="modal fade" id="DirectorModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog bounceInDown animated"><!-- Add here Modal COME Effect "Animate.css" -->
        <div class="modal-content">
         <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Modal Header</h4>
          </div>
          <div class="modal-body">
          </div>
        </div>
    </div>
</div>

this bellow jquery code i got from: https://codepen.io/nhembram/pen/PzyYLL

i am modify this for regular use.

jquery code:

<script>
    $(document).ready(function () {
    // BS MODAL OPEN CLOSE EFFECT  ---------------------------------
        var timeoutHandler = null;
        $('.modal').on('hide.bs.modal', function (e) {
            var anim = $('.modal-dialog').removeClass('bounceInDown').addClass('fadeOutDownBig'); // Model Come class Remove & Out effect class add
            if (timeoutHandler) clearTimeout(timeoutHandler);
            timeoutHandler = setTimeout(function() {
                $('.modal-dialog').removeClass('fadeOutDownBig').addClass('bounceInDown'); // Model Out class Remove & Come effect class add
            }, 500); // some delay for complete Animation
        });
    });
    </script>

Multidimensional Array [][] vs [,]

double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]

for (int i = 0; i < matrix.Length; i++)
{
    matrix[i] = new int [3]; // Create inner array
    for (int j = 0; j < matrix[i].Length; j++)
        matrix[i][j] = i * 3 + j;
}

double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:

int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
        matrix [i, j] = i * 3 + j;

Search a whole table in mySQL for a string

Identify all the fields that could be related to your search and then use a query like:

SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
   OR field2 LIKE '%Mary%'
   OR field3 LIKE '%Mary%'
   OR field4 LIKE '%Mary%'
   ....
   (do that for each field you want to check)

Using LIKE '%Mary%' instead of = 'Mary' will look for the fields that contains someCaracters + 'Mary' + someCaracters.

Disabling vertical scrolling in UIScrollView

I updated the content size to disable vertical scrolling, and the ability to scroll still remained. Then I figured out that I needed to disable vertical bounce too, to disable completly the scroll.

Maybe there are people with this problem too.

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Iterating through a range of dates in Python

import datetime

def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
  # inclusive=False to behave like range by default
  if step.days > 0:
    while start < stop:
      yield start
      start = start + step
      # not +=! don't modify object passed in if it's mutable
      # since this function is not restricted to
      # only types from datetime module
  elif step.days < 0:
    while start > stop:
      yield start
      start = start + step
  if inclusive and start == stop:
    yield start

# ...

for date in daterange(start_date, end_date, inclusive=True):
  print strftime("%Y-%m-%d", date.timetuple())

This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count and most importantly the code becomes easier to read as you call the function from multiple places.

How to prevent colliders from passing through each other?

So I haven't been able to get the Mesh Colliders to work. I created a composite collider using simple box colliders and it worked exactly as expected.

Other tests with simple Mesh Colliders have come out the same.

It looks like the best answer is to build a composite collider out of simple box/sphere colliders.

For my specific case I wrote a Wizard that creates a Pipe shaped compound collider.

@script AddComponentMenu("Colliders/Pipe Collider");
class WizardCreatePipeCollider extends ScriptableWizard
{
    public var outterRadius : float = 200;
    public var innerRadius : float = 190;
    public var sections : int = 12;
    public var height : float = 20;

    @MenuItem("GameObject/Colliders/Create Pipe Collider")
    static function CreateWizard()
    {
        ScriptableWizard.DisplayWizard.<WizardCreatePipeCollider>("Create Pipe Collider");
    }

    public function OnWizardUpdate() {
        helpString = "Creates a Pipe Collider";
    }

    public function OnWizardCreate() {
        var theta : float = 360f / sections;
        var width : float = outterRadius - innerRadius;

        var sectionLength : float = 2 * outterRadius * Mathf.Sin((theta / 2) * Mathf.Deg2Rad);

        var container : GameObject = new GameObject("Pipe Collider");
        var section : GameObject;
        var sectionCollider : GameObject;
        var boxCollider : BoxCollider;

        for(var i = 0; i < sections; i++)
        {
            section = new GameObject("Section " + (i + 1));

            sectionCollider = new GameObject("SectionCollider " + (i + 1));
            section.transform.parent = container.transform;
            sectionCollider.transform.parent = section.transform;

            section.transform.localPosition = Vector3.zero;
            section.transform.localRotation.eulerAngles.y = i * theta;

            boxCollider = sectionCollider.AddComponent.<BoxCollider>();
            boxCollider.center = Vector3.zero;
            boxCollider.size = new Vector3(width, height, sectionLength);

            sectionCollider.transform.localPosition = new Vector3(innerRadius + (width / 2), 0, 0);
        }
    }
}

Move seaborn plot legend to a different position?

Check out the docs here: https://matplotlib.org/users/legend_guide.html#legend-location

adding this simply worked to bring legend out of the plot:

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Resize HTML5 canvas to fit window

If you're interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom on the ::content element that sizes the container element. This is sized relative to its parent's width, which is 100% by default. The ratio specified here has to match up with the ratio of the sizes on the canvas element.

_x000D_
_x000D_
// Javascript_x000D_
_x000D_
var canvas = document.querySelector('canvas'),_x000D_
    context = canvas.getContext('2d');_x000D_
_x000D_
context.fillStyle = '#ff0000';_x000D_
context.fillRect(500, 200, 200, 200);_x000D_
_x000D_
context.fillStyle = '#000000';_x000D_
context.font = '30px serif';_x000D_
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
_x000D_
/*CSS*/_x000D_
_x000D_
.container {_x000D_
  position: relative; _x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
  content: ' ';_x000D_
  display: block;_x000D_
  padding: 0 0 50%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
_x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class=container>_x000D_
  <div class=wrapper>_x000D_
    <canvas width=1200 height=600></canvas>  _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set mouse focus and move cursor to end of input using jQuery

I have found the same thing as suggested above by a few folks. If you focus() first, then push the val() into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val() into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus().

$('element_identifier').focus().val('some_value') 

should do the trick (it always has for me anyway).

Trying to start a service on boot on Android

Before mounting external storage BOOT_COMPLETE is sent execute.if your app is installed to external storage it won't receive BOOT_COMPLETE broadcast message. To prevent this you can install your application in internal storage. you can do this just adding this line in menifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
... >

Some HTC devices can enable a "fast boot" feature that is more like a deep hibernation and not a real reboot and therefore should not give the BOOT_COMPLETE intent. To recover this you can add this intent filter inside your receiver:

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

in_array multiple values

if(empty(array_intersect([21,22,23,24], $check_with_this)) {
 print "Not found even a single element";
} else {
 print "Found an element";
}

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

Returns an array containing all of the values in array1 whose values exist in all of the parameters.


empty() — Determine whether a variable is empty

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

Laravel Rule Validation for Numbers

Also, there was just a typo in your original post.

'min:2|max5' should have been 'min:2|max:5'.
Notice the ":" for the "max" rule.

How to see which flags -march=native will activate?

If you want to find out how to set-up a non-native cross compile, I found this useful:

On the target machine,

% gcc -march=native -Q --help=target | grep march
-march=                               core-avx-i

Then use this on the build machine:

% gcc -march=core-avx-i ...

How does Junit @Rule work?

Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.

For example, Using @Timeout rule we can set the timeout for all the tests.

public class TestApp {
    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

    ......
    ......

 }

@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.

public class TempFolderTest {

 @Rule
 public TemporaryFolder tempFolder= new TemporaryFolder();

 @Test
 public void testTempFolder() throws IOException {
  File folder = tempFolder.newFolder("demos");
  File file = tempFolder.newFile("Hello.txt");

  assertEquals(folder.getName(), "demos");
  assertEquals(file.getName(), "Hello.txt");

 }


}

You can see examples of some in-built rules provided by junit at this link.

How to override toString() properly in Java?

  1. if you are use using notepad: then

    public String toString(){
    
     return ""; ---now here you can use variables which you have created for your class
    
    }
    
  2. if you are using eclipse IDE then press

    -alt +shift +s 
    

    -click on override toString method here you will get options to select what type of variables you want to select.

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

How to print a number with commas as thousands separators in JavaScript

The following code uses char scan, so there's no regex.

function commafy( num){
  var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
  while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
  return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}

It shows promising performance: http://jsperf.com/number-formatting-with-commas/5

2015.4.26: Minor fix to resolve issue when num<0. See https://jsfiddle.net/runsun/p5tqqvs3/

How to define a circle shape in an Android XML drawable file?

If you want a circle like this

enter image description here

Try using the code below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="2"
    android:useLevel="false" >
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dp"
        android:color="@android:color/darker_gray" />
</shape>

How can I create a text box for a note in markdown?

Another solution is to use CSS adjacency and use h4 (or higher):

#### note

This is the note content
h4 {
  display: none; /* hide */
}

h4 + p {
  /* style the note however you want */
}

How to make php display \t \n as tab and new line instead of characters

"\t" not '\t', php doesnt escape in single quotes

How do you get the current page number of a ViewPager for Android?

There is a method object_of_ViewPager.getCurrentItem() which returns the position of currently Viewed page of view pager

how to use php DateTime() function in Laravel 5

Best way is to use the Carbon dependency.

With Carbon\Carbon::now(); you get the current Datetime.

With Carbon you can do like enything with the DateTime. Event things like this:

$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

How to increase heap size for jBoss server

You can set it as JVM arguments the usual way, e.g. -Xms1024m -Xmx2048m for a minimum heap of 1GB and maximum heap of 2GB. JBoss will use the JAVA_OPTS environment variable to include additional JVM arguments, you could specify it in the /bin/run.conf.bat file:

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

However, this is more a workaround than a real solution. If multiple users concurrently uploads big files, you'll hit the same problem sooner or later. You would need to keep increasing memory for nothing. You should rather configure your file upload parser to store the uploaded file on temp disk instead of entirely in memory. As long as it's unclear which parser you're using, no suitable answer can be given. However, more than often Apache Commons FileUpload is used under the covers, you should then read the documentation with "threshold size" as keyword to configure the memory limit for uploaded files. When the file size is beyond the threshold, it would then be written to disk.

How to add a button dynamically in Android?

Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.

Here is an example:

((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

How do I add slashes to a string in Javascript?

var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'

Parsing a CSV file using NodeJS

The fast-csv npm module can read data line-by-line from csv file.

Here is an example:

let csv= require('fast-csv');

var stream = fs.createReadStream("my.csv");

csv
 .parseStream(stream, {headers : true})
 .on("data", function(data){
     console.log('I am one line of data', data);
 })
 .on("end", function(){
     console.log("done");
 });

IndexOf function in T-SQL

You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

What is the difference between 'protected' and 'protected internal'?

In practice, about methods:

protected - accessible for inherited classes, otherwise private.

internal - public only for classes inside the assembly, otherwise private.

protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.

WPF Image Dynamically changing Image source during runtime

Here is how it worked beautifully for me. In the window resources add the image.

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

Then the code goes like this.

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

"this" is referring to the Window object

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Use json.loads not json.load.

(load loads from a file-like object, loads from a string. So you could just as well omit the .read() call instead.)

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Running multiple commands with xargs

My current BKM for this is

... | xargs -n1 -I % perl -e 'system("echo 1 %"); system("echo 2 %");'

It is unfortunate that this uses perl, which is less likely to be installed than bash; but it handles more input that the accepted answer. (I welcome a ubiquitous version that does not rely on perl.)

@KeithThompson's suggestion of

 ... | xargs -I % sh -c 'command1; command2; ...'

is great - unless you have the shell comment character # in your input, in which case part of the first command and all of the second command will be truncated.

Hashes # can be quite common, if the input is derived from a filesystem listing, such as ls or find, and your editor creates temporary files with # in their name.

Example of the problem:

$ bash 1366 $>  /bin/ls | cat
#Makefile#
#README#
Makefile
README

Oops, here is the problem:

$ bash 1367 $>  ls | xargs -n1 -I % sh -i -c 'echo 1 %; echo 2 %'
1
1
1
1 Makefile
2 Makefile
1 README
2 README

Ahh, that's better:

$ bash 1368 $>  ls | xargs -n1 -I % perl -e 'system("echo 1 %"); system("echo 2 %");'
1 #Makefile#
2 #Makefile#
1 #README#
2 #README#
1 Makefile
2 Makefile
1 README
2 README
$ bash 1369 $>  

Returning a value from callback function in Node.js

Example code for node.js - async function to sync function:

var deasync = require('deasync');

function syncFunc()
{
    var ret = null;
    asyncFunc(function(err, result){
        ret = {err : err, result : result}
    });

    while((ret == null))
    {
         deasync.runLoopOnce();
    }

    return (ret.err || ret.result);
}

Remove part of string in Java

originalString.replaceFirst("[(].*?[)]", "");

https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()

Preferred way of loading resources in Java

I search three places as shown below. Comments welcome.

public URL getResource(String resource){

    URL url ;

    //Try with the Thread Context Loader. 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if(classLoader != null){
        url = classLoader.getResource(resource);
        if(url != null){
            return url;
        }
    }

    //Let's now try with the classloader that loaded this class.
    classLoader = Loader.class.getClassLoader();
    if(classLoader != null){
        url = classLoader.getResource(resource);
        if(url != null){
            return url;
        }
    }

    //Last ditch attempt. Get the resource from the classpath.
    return ClassLoader.getSystemResource(resource);
}