Programs & Examples On #Document

Is a term that in computer science can refer to various file types containing information usually readable by a human.

How to get the entire document HTML as a string?

MS added the outerHTML and innerHTML properties some time ago.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

See quirksmode for browser compatibility for what will work for you. All support innerHTML.

var markup = document.documentElement.innerHTML;
alert(markup);

MongoDB: How to update multiple documents with a single command?

All latest versions of mongodb updateMany() is working fine

db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

Create Word Document using PHP in Linux

PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}

It has an LGPL license and the examples that came with the code worked nicely for me.

Difference between $(document.body) and $('body')

$(document.body) is using the global reference document to get a reference to the body, whereas $('body') is a selector in which jQuery will get the reference to the <body> element on the document.

No major difference that I can see, not any noticeable performance gain from one to the other.

Selenium wait until document is ready

I tried this code and it works for me. I call this function every time I move to another page

public static void waitForPageToBeReady() 
{
    JavascriptExecutor js = (JavascriptExecutor)driver;

    //This loop will rotate for 100 times to check If page Is ready after every 1 second.
    //You can replace your if you wants to Increase or decrease wait time.
    for (int i=0; i<400; i++)
    { 
        try 
        {
            Thread.sleep(1000);
        }catch (InterruptedException e) {} 
        //To check page ready state.

        if (js.executeScript("return document.readyState").toString().equals("complete"))
        { 
            break; 
        }   
      }
 }

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

How do I convert a org.w3c.dom.Document object to a String?

This worked for me, as documented on this page:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();

GetElementByID - Multiple IDs

getElementByID is exactly that - get an element by id.

Maybe you want to give those elements a circle class and getElementsByClassName

Convert Mongoose docs to json

First of all, try toObject() instead of toJSON() maybe?

Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:

var flatUsers = users.map(function() {
  return user.toObject();
})
return res.end(JSON.stringify(flatUsers));

It's a guess, but I hope it helps

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

Create a folder inside documents folder in iOS apps

I do that the following way:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

$(window).scrollTop() vs. $(document).scrollTop()

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Python string.join(list) on object array rather than string array

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.

no target device found android studio 2.1.1

After i changed my target to usb. i had to create the file /etc/udev/rules.d/51-android.rules with vendor details .Click for Solution

Map implementation with duplicate keys

We don't need to depend on the Google Collections external library. You can simply implement the following Map:

Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>();

public static void main(String... arg) {
   // Add data with duplicate keys
   addValues("A", "a1");
   addValues("A", "a2");
   addValues("B", "b");
   // View data.
   Iterator it = hashMap.keySet().iterator();
   ArrayList tempList = null;

   while (it.hasNext()) {
      String key = it.next().toString();             
      tempList = hashMap.get(key);
      if (tempList != null) {
         for (String value: tempList) {
            System.out.println("Key : "+key+ " , Value : "+value);
         }
      }
   }
}

private void addValues(String key, String value) {
   ArrayList tempList = null;
   if (hashMap.containsKey(key)) {
      tempList = hashMap.get(key);
      if(tempList == null)
         tempList = new ArrayList();
      tempList.add(value);  
   } else {
      tempList = new ArrayList();
      tempList.add(value);               
   }
   hashMap.put(key,tempList);
}

Please make sure to fine tune the code.

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

Checking Value of Radio Button Group via JavaScript?

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

Java: how do I check if a Date is within a certain range?

Doesnn't care which date boundry is which.

Math.abs(date1.getTime() - date2.getTime()) == 
    Math.abs(date1.getTime() - dateBetween.getTime()) + Math.abs(dateBetween.getTime() - date2.getTime());

How do I align a label and a textarea?

  1. Set the height of your label to the same height as the multiline textbox.
  2. Add the cssClass .alignTop{vertical-align: middle;} for the label control.

    <p>
        <asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
        <asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
        <asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
        ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">    
    </asp:RequiredFieldValidator>
    

Lollipop : draw behind statusBar with its color set to transparent

Instead of

<item name="android:statusBarColor">@android:color/transparent</item>

Use the following:

<item name="android:windowTranslucentStatus">true</item>

And make sure to remove the top padding (which is added by default) on your 'MainActivity' layout.

Note that this does not make the status bar fully transparent, and there will still be a "faded black" overlay over your status bar.

How can you integrate a custom file browser/uploader with CKEditor?

For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.

1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.

2) This part is where it tripped me up:

The Ckeditor website documentation says you need to use these two methods:

function getUrlParam( paramName ) {
    var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
    var match = window.location.search.match( reParam );
    return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
    var funcNum = getUrlParam( 'CKEditorFuncNum' );
    var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
    window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
    window.close();
}

What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.

So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.

editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.

CKEDITOR.replace( 'editor', {
    filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
    filebrowserUploadUrl: '../UploadImage', //servlet

});

filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)

<head>
<script src="../../ckeditor/ckeditor.js"></script>
</head>
<body>
<script>


function getUrlParam( paramName ) {
    var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
    var match = window.location.search.match( reParam );
    return ( match && match.length > 1 ) ? match[1] : null;
}

function returnFileUrl() {
    var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
    window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
    window.close();
}


//when this window opens it will load all the images which you send from the FileBrowser Servlet. 
getImages();
function getImages(){
    $.get("../FileBrowser", function(responseJson) {    
        //do something with responseJson (like create <img> tags and update the src attributes) 
    });
}

   //you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
returnFileUrl();
</script>
</body>

3) The FileBrowser Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Images i = new Images();
    List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
    String json = new Gson().toJson(images);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

4) UploadImage Servlet

Go back to your config.js file for ckeditor and add the following line:

//https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
config.uploadUrl = '/UploadImage';

Then you can drag and drop files also:

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


                Images i = new Images();

   //do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database. 

   //Now this part is important. You need to return the response in json format. And it has to look like this:

//      https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
//      response must be in this format:
//      {
//          "uploaded": 1,
//          "fileName": "example.png",
//          "url": "https://www.cats.com/example.png"
//      }

                    String image = "https://www.cats.com/example.png";
                        ImageObject objResponse = i.getCkEditorObjectResponse(image);
                        String json = new Gson().toJson(objResponse);
                        response.setContentType("application/json");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(json);
                    }
                }

And that's all folks. Hope it helps someone.

High Quality Image Scaling Library

Try This basic code snippet:

private static Bitmap ResizeBitmap(Bitmap srcbmp, int width, int height )
{
    Bitmap newimage = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(newimage))
           g.DrawImage(srcbmp, 0, 0, width, height);
    return newimage;
}

Creating temporary files in bash

Yes, use mktemp.

It will create a temporary file inside a folder that is designed for storing temporary files, and it will guarantee you a unique name. It outputs the name of that file:

> mktemp
/tmp/tmp.xx4mM3ePQY
>

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

The type or namespace name 'System' could not be found

I attempted to re-create your issue and came up with a similar error when the solution was created in visual studio 2013 and then tried building it in in vs 2015.

I was able to get a successful build once I reinstalled NuGet Package Manager (and closed, then reopened VS 2015).

References / Credit

There are several SO questions relating to build issues via with earlier version of NPM for VS 2015 (i.e. I'm just passing along what I've tried and worked out). Recurring resolution is usually update / reinstall NPM or change execution policy in power shell. I tend to like the update + restart approach to avoid tinkering with the black boxes in windows. one source: https://stackoverflow.com/a/32251092/1158842 There may also be an issue of MSBuild Integrated solutions, in which case migrating away from the NuGet resources in the solution could do the trick.

Source: https://stackoverflow.com/a/31811461/1158842

Quicker way to get all unique values of a column in VBA?

Try this

Option Explicit

Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long

myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs

Set uniqueRng = GetUniqueValues(ws, myCol)

End Sub


Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long

With ws
    .Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo

    firstRow = 1
    If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row

    Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With

End Function

it should be quite fast and without the drawback NeepNeepNeep told about

Local file access with JavaScript

Just an update of the HTML5 features is in http://www.html5rocks.com/en/tutorials/file/dndfiles/. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:

The specification provides several interfaces for accessing files from a 'local' filesystem:

  1. File - an individual file; provides readonly information such as name, file size, MIME type, and a reference to the file handle.
  2. FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  3. Blob - Allows for slicing a file into byte ranges.

See Paul D. Waite's comment below.

How to declare a variable in SQL Server and use it in the same Stored Procedure

None of the above methods worked for me so i'm posting the way i did

DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN 

DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID  int;
SELECT BrandID = BrandID FROM tblBrand 
WHERE BrandName = BrandName;

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (CategoryID, BrandID);
END$$

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

What does [object Object] mean?

[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:

alert({}); // [object Object]

You can change the default representation by overriding the toString method like so:

var o = {toString: function(){ return "foo" }};
alert(o); // foo

How to display 3 buttons on the same line in css

You need to float all the buttons to left and make sure its width to fit within outer container.

CSS:

.btn{

   float:left;
}

HTML:

    <button type="submit" class="btn" onClick="return false;" >Save</button>
    <button type="submit" class="btn" onClick="return false;">Publish</button>
    <button class="btn">Back</button>

How to detect running app using ADB command

Alternatively, you could go with pgrep or Process Grep. (Busybox is needed)

You could do a adb shell pgrep com.example.app and it would display just the process Id.

As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell to navigate/control around. :D

What is a good naming convention for vars, methods, etc in C++?

It really doesn't matter. Just make sure you name your variables and functions descriptively. Also be consistent.

Nowt worse than seeing code like this:

int anInt;                  // Great name for a variable there ...
int myVar = Func( anInt );  // And on this line a great name for a function and myVar
                            // lacks the consistency already, poorly, laid out! 

Edit: As pointed out by my commenter that consistency needs to be maintained across an entire team. As such it doesn't matter WHAT method you chose, as long as that consistency is maintained. There is no right or wrong method, however. Every team I've worked in has had different ideas and I've adapted to those.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This is another version which work in case you have some tasks to cleanup. Code will leave clean up process in their method.

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

)



func main() {

    _,done1:=doSomething1()
    _,done2:=doSomething2()

    //do main thread


    println("wait for finish")
    <-done1
    <-done2
    fmt.Print("clean up done, can exit safely")

}

func doSomething1() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something1
        done<-true
    }()
    return nil,done
}


func doSomething2() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something2
        done<-true
    }()
    return nil,done
}

in case you need to clean main function you need to capture signal in main thread using go func() as well.

How to calculate the time interval between two time strings

    import datetime
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    start_date = datetime.date(year, month, day)
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    end_date = datetime.date(year, month, day)
    
    time_difference = end_date - start_date
    age = time_difference.days
    print("Total days: " + str(age))

Inserting a string into a list without getting split into characters

>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']

JQuery Ajax Post results in 500 Internal Server Error

As an addition to the "malformed JSON" answer, if the query you are running returns an object or anything that prevents the data to be serialised, you will get this error. You should always be sure you have JSON and only JSON at the end of your action method or whatever it is you are getting the data from.

Initialize class fields in constructor or at declaration?

There are many and various situations.

I just need an empty list

The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.

public class CsvFile
{
    private List<CsvRow> lines = new List<CsvRow>();

    public CsvFile()
    {
    }
}

I know the values

I exactly know what values I want to have by default or I need to use some other logic.

public class AdminTeam
{
    private List<string> usernames;

    public AdminTeam()
    {
         usernames = new List<string>() {"usernameA", "usernameB"};
    }
}

or

public class AdminTeam
{
    private List<string> usernames;

    public AdminTeam()
    {
         usernames = GetDefaultUsers(2);
    }
}

Empty list with possible values

Sometimes I expect an empty list by default with a possibility of adding values through another constructor.

public class AdminTeam
{
    private List<string> usernames = new List<string>();

    public AdminTeam()
    {
    }

    public AdminTeam(List<string> admins)
    {
         admins.ForEach(x => usernames.Add(x));
    }
}

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

how to set JAVA_OPTS for Tomcat in Windows?

It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:

You can set the minimum and maximum memory heap size with the

JVM -Xms and -Xmx parameters.

The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use

JAVA_OPTS=-Xms128m -Xmx1024m        

You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter

    -XX:MaxPermSize=256m

For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.

The following is an example of a setenv.bat file:

set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"

Tkinter module not found on Ubuntu

Since you mention synaptic I think you're on Ubuntu. You probably need to run update-python-modules to update your Tkinter module for Python 3.

EDIT: Running update-python-modules

First, make sure you have python-support installed:

sudo apt-get install python-support

Then, run update-python-modules with the -a option to rebuild all the modules:

sudo update-python-modules -a

I cannot guarantee all your modules will build though, since there are some API changes between Python 2 and Python 3.

Convert between UIImage and Base64 string

Swift 3.0 and Xcode 8.0

let imageData = UIImageJPEGRepresentation(imageView.image!, 1)

    let base64String = (imageData! as Data).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    print(base64String)

How can I check if character in a string is a letter? (Python)

This works:

word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
    if not char.isalpha():
        notChar += 1
    else:
        isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")

Install Windows Service created in Visual Studio

Yet another catch I ran into: ensure your Installer derived class (typically ProjectInstaller) is at the top of the namespace hierarchy, I tried to use a public class within another public class, but this results in the same old error:

No public installers with the RunInstallerAttribute.Yes attribute could be found

Wildcard string comparison in Javascript

var searchArray = function(arr, str){
    // If there are no items in the array, return an empty array
    if(typeof arr === 'undefined' || arr.length === 0) return [];
    // If the string is empty return all items in the array
    if(typeof str === 'undefined' || str.length === 0) return arr;

    // Create a new array to hold the results.
    var res = [];

    // Check where the start (*) is in the string
    var starIndex = str.indexOf('*');

    // If the star is the first character...
    if(starIndex === 0) {

        // Get the string without the star.
        str = str.substr(1);
        for(var i = 0; i < arr.length; i++) {

            // Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
            // It doesn't necessarily mean it IS a string either.
            if(!arr[i].indexOf) continue;

            // Check if the string is at the end of each item.
            if(arr[i].indexOf(str) === arr[i].length - str.length) {                    
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // Otherwise, if the star is the last character
    else if(starIndex === str.length - 1) {
        // Get the string without the star.
        str = str.substr(0, str.length - 1);
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function                
            if(!arr[i].indexOf) continue;
            // Check if the string is at the beginning of each item
            if(arr[i].indexOf(str) === 0) {
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // In any other case...
    else {            
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function
            if(!arr[i].indexOf) continue;
            // Check if the string is anywhere in each item
            if(arr[i].indexOf(str) !== -1) {
                // If it is, add the item to the results
                res.push(arr[i]);
            }
        }
    }

    // Return the results as a new array.
    return res;
}

var birds = ['bird1','somebird','bird5','bird-big','abird-song'];

var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song

There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.

Fiddle

What is Shelving in TFS?

I come across this all the time, so supplemental information regarding branches:

If you're working with multiple branches, shelvesets are tied to the specific branch in which you created them. So, if you let a changeset rust on the shelf for too long and have to unshelve to a different branch, then you have to do that with the July release of the power tools.

tfpt unshelve /migrate

submitting a GET form with query string params and hidden params disappear

In HTML5, this is per-spec behaviour.

See http://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#form-submission-algorithm

Look at "4.10.22.3 Form submission algorithm", step 17. In the case of a GET form to an http/s URI with a query string:

Let destination be a new URL that is equal to the action except that its <query> component is replaced by query (adding a U+003F QUESTION MARK character (?) if appropriate).

So, your browser will trash the existing "?..." part of your URI and replace it with a new one based on your form.

In HTML 4.01, the spec produces invalid URIs - most browsers didn't actually do this though..

See http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3, step four - the URI will have a ? appended, even if it already contains one.

How to change the application launcher icon on Flutter?

The one marked as correct answer, is not enough, you need one more step, type this command in the terminal in order to create the icons:

flutter pub run flutter_launcher_icons:main

No @XmlRootElement generated by JAXB

The topic is quite old but still relevant in enterprise business contexts. I tried to avoid to touch the xsds in order to easily update them in the future. Here are my solutions..

1. Mostly xjc:simple is sufficient

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jxb:extensionBindingPrefixes="xjc">

    <jxb:globalBindings>
        <xjc:simple/> <!-- adds @XmlRootElement annotations -->
    </jxb:globalBindings>

</jxb:bindings>

It will mostly create XmlRootElements for importing xsd definitions.

2. Divide your jaxb2-maven-plugin executions

I have encountered that it makes a huge difference if you try to generate classes from multiple xsd definitions instead of a execution definition per xsd.

So if you have a definition with multiple <source>'s, than just try to split them:

          <execution>
            <id>xjc-schema-1</id>
            <goals>
              <goal>xjc</goal>
            </goals>
            <configuration>
              <xjbSources>
                <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
              </xjbSources>
              <sources>
                <source>src/main/resources/xsd/definition1/</source>
              </sources>
              <clearOutputDir>false</clearOutputDir>
            </configuration>
          </execution>

          <execution>
            <id>xjc-schema-2</id>
            <goals>
              <goal>xjc</goal>
            </goals>
            <configuration>
              <xjbSources>
                <xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
              </xjbSources>
              <sources>
                <source>src/main/resources/xsd/definition2/</source>
              </sources>
              <clearOutputDir>false</clearOutputDir>
            </configuration>
          </execution>

The generator will not catch the fact that one class might be sufficient and therefore create custom classes per execution. And thats exactly what I need ;).

Java: Check if enum contains a given string?

Java Streams provides elegant way to do that

Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))

Returns: true if any elements of the stream match the provided value, otherwise false

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

What does !important mean in CSS?

It changes the rules for override priority of css cascades. See the CSS2 spec.

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

Differences between Octave and MATLAB?

Rather than provide you with a complete list of differences, I'll give you my view on the matter.

If you read carefully the wiki page you provide, you'll often see sentences like "Octave supports both, while MATLAB requires the first" etc. This shows that Octave's developers try to make Octave syntax "superior" to MATLAB's.

This attitude makes Octave lose its purpose completely. The idea behind Octave is (or has become, I should say, see comments below) to have an open source alternative to run m-code. If it tries to be "better", it thus tries to be different, which is not in line with the reasons most people use it for. In my experience, running stuff developed in MATLAB doesn't ever work in one go, except for the really simple, really short stuff -- For any sizable function, I always have to translate a lot of stuff before it works in Octave, if not re-write it from scratch. How this is better, I really don't see...

Also, if you learn Octave, there's a lot of syntax allowed in Octave that's not allowed in MATLAB. Meaning -- code written in Octave often does not work in MATLAB without numerous conversions. It's also not compatible the other way around!

I could go on: The MathWorks has many toolboxes for MATLAB, there's Simulink and its related products for which there really is no equivalent in Octave (yes, you'd have to pay for all that. But often your employer/school does that anyway, and well, it at least exists), proven compliance with several industry standards, testing tools, validation tools, requirement management systems, report generation, a much larger community & user base, etc. etc. etc. MATLAB is only a small part of something much larger. Octave is...just Octave.

So, my advice:

  • Find out if your school will pay for MATLAB. Often they will.
  • If they don't, and if you can scrape together the money, buy MATLAB and learn to use it properly. In the long run it's the better decision.
  • If you really can't get the money -- use Octave, but learn MATLAB's syntax and stay away from Octave-only syntax. (see note)

Why this last point? Because in the sciences, there are often large code bases entirely written in MATLAB. There are professors, engineers, students, professional coders, lots and lots of people who know all the intricate gory details of MATLAB, and not so much of Octave.

If you get a new job, and everyone in your new office speaks Spanish, it's kind of cocky to demand of everyone that they start speaking English from then on, simply because you don't speak/like Spanish. Same with MATLAB and Octave.

NB -- if all downvoters could just leave a comment with their arguments and reasons for disagreeing with me, that'd be great :)

Note: Octave can be run in "traditional mode" (by including the --traditional flag when starting Octave) which makes it give an error when certain Octave-only syntax is used.

How to check Oracle database for long running queries

select sq.PARSING_SCHEMA_NAME, sq.LAST_LOAD_TIME, sq.ELAPSED_TIME, sq.ROWS_PROCESSED, ltrim(sq.sql_text), sq.SQL_FULLTEXT
  from v$sql sq, v$session se
 order by sq.ELAPSED_TIME desc, sq.LAST_LOAD_TIME desc;

How to set commands output as a variable in a batch file

To read a file...

set /P Variable=<File.txt

To Write a file

@echo %DataToWrite%>File.txt

note; having spaces before the <> character causes a space to be added at the end of the variable, also

To add to a file,like a logger program, First make a file with a single enter key in it called e.txt

set /P Data=<log0.log
set /P Ekey=<e.txt
@echo %Data%%Ekey%%NewData%>log0.txt

your log will look like this

Entry1
Entry2 

and so on

Anyways a couple useful things

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

Getting started with Haskell

Graham Hutton's Programming in Haskell is concise, reasonably thorough, and his years of teaching Haskell really show. It's almost always what I recommend people start with, regardless of where you go from there.

In particular, Chapter 8 ("Functional Parsers") provides the real groundwork you need to start dealing with monads, and I think is by far the best place to start, followed by All About Monads. (With regard to that chapter, though, do note the errata from the web site, however: you can't use the do form without some special help. You might want to learn about typeclasses first and solve that problem on your own.)

This is rarely emphasized to Haskell beginners, but it's worth learning fairly early on not just about using monads, but about constructing your own. It's not hard, and customized ones can make a number of tasks rather more simple.

Android button onClickListener

Use OnClicklistener or you can use android:onClick="myMethod" in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod function in class look like this.

public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}

And in that SecondActivity.class set new layout in contentview.

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM : this actually means the byte code interpreter .It is platform dependent. For eg: in Windows platform the 'java.exe' or 'javaw.exe' precess is the jvm process.

JDK : is a toolkit containing necessary libraries and utilities to develop and execute java program/application

JRE: is the execution environment for a java application.ie, it only support runtime dependencies including jvm for compiled program. If we want to compile a java program we need jdk.

Using braces with dynamic variable names in PHP

Overview

In PHP, you can just put an extra $ in front of a variable to make it a dynamic variable :

$$variableName = $value;

While I wouldn't recommend it, you could even chain this behavior :

$$$$$$$$DoNotTryThisAtHomeKids = $value;

You can but are not forced to put $variableName between {} :

${$variableName} = $value;

Using {} is only mandatory when the name of your variable is itself a composition of multiple values, like this :

${$variableNamePart1 . $variableNamePart2} = $value;

It is nevertheless recommended to always use {}, because it's more readable.

Differences between PHP5 and PHP7

Another reason to always use {}, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.

In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.

Case 1 : $$foo['bar']['baz']

  • PHP5 interpetation : ${$foo['bar']['baz']}
  • PHP7 interpetation : ${$foo}['bar']['baz']

Case 2 : $foo->$bar['baz']

  • PHP5 interpetation : $foo->{$bar['baz']}
  • PHP7 interpetation : $foo->{$bar}['baz']

Case 3 : $foo->$bar['baz']()

  • PHP5 interpetation : $foo->{$bar['baz']}()
  • PHP7 interpetation : $foo->{$bar}['baz']()

Case 4 : Foo::$bar['baz']()

  • PHP5 interpetation : Foo::{$bar['baz']}()
  • PHP7 interpetation : Foo::{$bar}['baz']()

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Initializing a dictionary in python with a key value and no corresponding values

Based on the clarifying comment by @user2989027, I think a good solution is the following:

definition = ['apple', 'ball']
data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
my_data = {}
for k in definition:
  try:
    my_data[k]=data[k]
  except KeyError:
    pass
print my_data

I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.

good example of Javadoc

How about the JDK source code, but accessed through a 3rd party like docjar? For example, the Collections source.

That way, there's no big download.

Difference between setTimeout with and without quotes and parentheses

Using setInterval or setTimeout

You should pass a reference to a function as the first argument for setTimeout or setInterval. This reference may be in the form of:

  • An anonymous function

    setTimeout(function(){/* Look mah! No name! */},2000);
    
  • A name of an existing function

    function foo(){...}
    
    setTimeout(foo, 2000);
    
  • A variable that points to an existing function

    var foo = function(){...};
    
    setTimeout(foo, 2000);
    

    Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.

Passing arguments

To call a function and pass parameters, you can call the function inside the callback assigned to the timer:

setTimeout(function(){
  foo(arg1, arg2, ...argN);
}, 1000);

There is another method to pass in arguments into the handler, however it's not cross-browser compatible.

setTimeout(foo, 2000, arg1, arg2, ...argN);

Callback context

By default, the context of the callback (the value of this inside the function called by the timer) when executed is the global object window. Should you want to change it, use bind.

setTimeout(function(){
  this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);

Security

Although it's possible, you should not pass a string to setTimeout or setInterval. Passing a string makes setTimeout() or setInterval() use a functionality similar to eval() that executes strings as scripts, making arbitrary and potentially harmful script execution possible.

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

Render HTML in React Native

i uses Js function replace simply.

<Text>{item.excerpt.rendered.replace(/<\/?[^>]+(>|$)/g, "")}</Text>

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

Getting the index of the returned max or min item using max()/min() on a list

After you get the maximum values, try this:

max_val = max(list)
index_max = list.index(max_val)

Much simpler than a lot of options.

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

Is it better in C++ to pass by value or pass by constant reference?

As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.

Using fonts with Rails asset pipeline

If you don't want to keep track of moving your fonts around:

# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(eot|svg|ttf|woff)\z/
    true
  end
}

in_array multiple values

Intersect the targets with the haystack and make sure the intersection is precisely equal to the targets:

$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack is a superset of $target.

To verify that at least one value in $target is also in $haystack, you can do this check:

 if(count(array_intersect($haystack, $target)) > 0){
     // at least one of $target is in $haystack
 }

Python debugging tips

If you don't like spending time in debuggers (and don't appreciate poor usability of pdb command line interface), you can dump execution trace and analyze it later. For example:

python -m trace -t setup.py install > execution.log

This will dump all source line of setup.py install execution to execution.log.

To make it easier to customize trace output and write your own tracers, I put together some pieces of code into xtrace module (public domain).

Firefox 'Cross-Origin Request Blocked' despite headers

I faced similar problem, and I think is valid to be registered how I fixed it:

I have a system built basically over Symfony 3. For self learn and performance purposes I decided to write few scripts using GoLang, also, an API with public access.

My Go API expects Json format params, and also return Json format response

To call those GoApi's I am using, most, $.ajax ( jQuery ) The first test was a deception: the (un)famous "Cross-Origin Request Blocked" pop up ! Then, I tried to set the "Access-Control-Allow-Origin: *" On apache conf, htaccess, php, javascript and anywhere I could find on google !

But, even, same frustrating error !!!

The Solution was simple : I had to make "POST" requests instead "GET" .

To achieve that I had to adjust both, GoLang and JavaScript to use GET ! Once it done, no more Cross-Origin Request Blocked for me !!!

Hope it Helps

PS:

I am using apache and Vhost, on Directory Block I have

  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

Remember : "*" means that you will accept requests from anyone !!! (Which may be a security lack ) In my case it is ok, because it will be an public API

PS2: My Headers

Response headers

Access-Control-Allow-Credentials    true
Access-Control-Allow-Headers    Authorization
Access-Control-Allow-Methods    GET, POST, PUT
Access-Control-Allow-Origin http://localhost
Content-Length  164
Content-Type    application/json; charset=UTF-8
Date    Tue, 07 May 2019 20:33:52 GMT

Request headers (469 B)

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Content-Length  81
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    localhost:9003
Origin  http://localhost
Referer http://localhost/fibootkt/MY_app_dev.php/MyTest/GoAPI
User-Agent  Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/66.0

Android get current Locale, not default

I´ve used this:

String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
   //do something
}

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

In my case error was caused by this line

@BindColor(R.color.colorAccent) var mColor: Int? = 0

Solved By

@JvmField @BindColor(android.R.color.white) @ColorInt internal var mColor: Int = 0

Error in GradleConsole

:app:kaptDebugKotlin e: \app\build\tmp\kapt3\stubs\debug\MainFragment.java:23: error: @BindColor field type must be 'int' or 'ColorStateList'. (com.sample.MainFragment.mColor) e:

e: private java.lang.Integer mColor;

How to check if a value is not null and not empty string in JS

I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.

/**
 * Test if the given value equals null or the empty string.
 * 
 * @param {string} value
**/
const isEmpty = (value) => value === null || value === '';

// Test:
isEmpty('');        // true
isEmpty(null);      // true
isEmpty(1);         // false
isEmpty(0);         // false
isEmpty(undefined); // false

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

HTML5 Form Input Pattern Currency Format

I like to give the users a bit of flexibility and trust, that they will get the format right, but I do want to enforce only digits and two decimals for currency

^[$\-\s]*[\d\,]*?([\.]\d{0,2})?\s*$

Takes care of:

$ 1.
-$ 1.00
$ -1.0
.1
.10
-$ 1,000,000.0

Of course it will also match:

$$--$1,92,9,29.1 => anyway after cleanup => -192,929.10

How to change the data type of a column without dropping the column with query?

ORACLE - Alter table table_name modify(column_name new_DataType);

Uploading images using Node.js, Express, and Mongoose

You can configure the connect body parser middleware in a configuration block in your main application file:

    /** Form Handling */
    app.use(express.bodyParser({
        uploadDir: '/tmp/uploads',
        keepExtensions: true
    }))
    app.use(express.limit('5mb'));

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

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 
do

    if [ ${!i} = "-s" ] 
    then ((i++)) 
        var1=${!i};

    elif [ ${!i} = "-log" ];
    then ((i++)) 
        logFile=${!i};  

    elif [ ${!i} = "-x" ];
    then ((i++)) 
        var2=${!i};    

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 
        var3=${!i};

    elif [ ${!i} = "-b" ];
    then ((i++)) 
        var4=${!i};

    elif [ ${!i} = "-l" ];
    then ((i++)) 
        var5=${!i}; 

    elif [ ${!i} = "-a" ];
    then ((i++)) 
        var6=${!i};
    fi

done;

Rationale: I included a launcher.sh script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

Favicon: .ico or .png / correct tags?

For compatibility with all browsers stick with .ico.

.png is getting more and more support though as it is easier to create using multiple programs.

for .ico

<link rel="shortcut icon" href="http://example.com/myicon.ico" />

for .png, you need to specify the type

<link rel="icon" type="image/png" href="http://example.com/image.png" />

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

How can I debug my JavaScript code?

Visual Studio 2008 has some very good JavaScript debugging tools. You can drop a breakpoint in your client side JavaScript code and step through it using the exact same tools as you would the server side code. There is no need to attach to a process or do anything tricky to enable it.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

How can I recover the return value of a function passed to multiprocessing.Process?

You can use the exit built-in to set the exit code of a process. It can be obtained from the exitcode attribute of the process:

import multiprocessing

def worker(procnum):
    print str(procnum) + ' represent!'
    exit(procnum)

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    result = []
    for proc in jobs:
        proc.join()
        result.append(proc.exitcode)
    print result

Output:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]

Timeout a command in bash without unnecessary delay

My problem was maybe a bit different : I start a command via ssh on a remote machine and want to kill the shell and childs if the command hangs.

I now use the following :

ssh server '( sleep 60 && kill -9 0 ) 2>/dev/null & my_command; RC=$? ; sleep 1 ; pkill -P $! ; exit $RC'

This way the command returns 255 when there was a timeout or the returncode of the command in case of success

Please note that killing processes from a ssh session is handled different from an interactive shell. But you can also use the -t option to ssh to allocate a pseudo terminal, so it acts like an interactive shell

How do I render a shadow?

Use elevation to implement shadows on RN Android. Added elevation prop #27

<View elevation={5}> </View>

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Use stopPropagation method, see an example:

$("#clickable a").click(function(e) {
   e.stopPropagation();
});

As said by jQuery Docs:

stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

Most efficient method to groupby on an array of objects

Using ES6 Map object:

_x000D_
_x000D_
/**
 * @description
 * Takes an Array<V>, and a grouping function,
 * and returns a Map of the array grouped by the grouping function.
 *
 * @param list An array of type V.
 * @param keyGetter A Function that takes the the Array type V as an input, and returns a value of type K.
 *                  K is generally intended to be a property key of V.
 *
 * @returns Map of the array grouped by the grouping function.
 */
//export function groupBy<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>> {
//    const map = new Map<K, Array<V>>();
function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
         const key = keyGetter(item);
         const collection = map.get(key);
         if (!collection) {
             map.set(key, [item]);
         } else {
             collection.push(item);
         }
    });
    return map;
}


// example usage

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];
    
const grouped = groupBy(pets, pet => pet.type);
    
console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}]
console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}]

const odd = Symbol();
const even = Symbol();
const numbers = [1,2,3,4,5,6,7];

const oddEven = groupBy(numbers, x => (x % 2 === 1 ? odd : even));
    
console.log(oddEven.get(odd)); // -> [1,3,5,7]
console.log(oddEven.get(even)); // -> [2,4,6]
_x000D_
_x000D_
_x000D_

About Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

jQuery/JavaScript to replace broken images

I solved my problem with these two simple functions:

function imgExists(imgPath) {
    var http = jQuery.ajax({
                   type:"HEAD",
                   url: imgPath,
                   async: false
               });
    return http.status != 404;
}

function handleImageError() {
    var imgPath;

    $('img').each(function() {
        imgPath = $(this).attr('src');
        if (!imgExists(imgPath)) {
            $(this).attr('src', 'images/noimage.jpg');
        }
    });
}

ImportError: No module named apiclient.discovery

Make sure you only have google-api-python-client installed. If you have apiclient installed, it will cause a collision. So, run the following:

sudo pip uninstall apiclient

Writing outputs to log file and console

I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

#####redir.env#####    
export LOG_FILE=log.txt

      exec 2>>${LOG_FILE}

    function log {
     echo "$1">>${LOG_FILE}
    }

    function message {
     echo "$1"
     echo "$1">>${LOG_FILE}
    }

Then in the actual script I have the following codes:

#!/bin/sh 
. redir.env
echo "Echoed to console only"
log "Written to log file only"
message "To console and log"
echo "This is stderr. Written to log file only" 1>&2

Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

After executing the above script file I have following outputs:

In console

In console
Echoed to console only
To console and log

For the Log file

In Log File Written to log file only
This is stderr. Written to log file only
To console and log

Hope this help.

Regex Last occurrence?

A negative look ahead is a correct answer, but it can be written more cleanly like:

(\\)(?!.*\\)

This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Ways to circumvent the same-origin policy

AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.

Code on github.

Professional jQuery based Combobox control?

Why don't you try http://jqueryajax.codeplex.com/. It is a collection of ASP.NET controls that contains multicolumn drop down as well.

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
    callbacks: {
        label: function (tooltipItem) {
            return (new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
            })).format(tooltipItem.value);
        }
    }
}

When is assembly faster than C?

I used to work with somebody who said "if the compiler is to dumb to figure out what you are trying to do and can't optimize it, your compiler is broken and it is time to get a new one". I'm sure there are edge cases when assembly will beat your C code, but if you are often finding yourself using assembler to "win" over your compiler, your compiler is busted.

Same can be said for writing "optimized" SQL that tries to coerce the query planner into doing things. If you find yourself re-arranging queries to get the planner to do what you want, your query planner is busted--get a new one.

Is there a CSS selector for the first direct child only?

Found this question searching on Google. This will return the first child of a element with class container, regardless as to what type the child is.

.container > *:first-child
{
}

How to avoid page refresh after button click event in asp.net

I think I also have this problem, I was trying to make calendar visible after clicking a button but the page keeps refreshing after clicking the button

MaintainScrollPositionOnPostBack="true"

This actually answered my problem.

I cant vote or comment, I just joined SO today

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How to create an exit message

I got here searching for a way to execute some code whenever the program ends.
Found this:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Quoting MSDN:

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing.

In practice this means that some of the statements might fail, leaving the transaction 'partially completed', and there might be no sign of this failure for a caller.

A simple example:

INSERT INTO t1 VALUES (1/0)    
INSERT INTO t2 VALUES (1/1)    
SELECT 'Everything is fine'

This code would execute 'successfully' with XACT_ABORT OFF, and will terminate with an error with XACT_ABORT ON ('INSERT INTO t2' will not be executed, and a client application will raise an exception).

As a more flexible approach, you could check @@ERROR after each statement (old school), or use TRY...CATCH blocks (MSSQL2005+). Personally I prefer to set XACT_ABORT ON whenever there is no reason for some advanced error handling.

Attach the Source in Eclipse of a jar

Go back in to where you added the jar. I believe its the libraries tab, I don't have Eclipse open but that sounds right. to the left of the jar file you added there should be an arrow pointing right, click that and 3 or 4 options expand, one of them being the source file of the library. Click on that and click edit(I think you can also double click it) then locate the file or folder on your hard disk, you probably have to click apply or okay and you're good to go, same with javadoc and i think the last one is native libraries. I don't pay much attention when I'm in there anymore if you couldn't tell. That's what you were asking, right?

Remove row lines in twitter bootstrap

Got the same question from a friend. My suggestion which does not require !Important looks like this: I add a custom class "no-border" which can be added to the bootstrap table.

.table.no-border tr td, .table.no-border tr th {
  border-width: 0;
}

You can see my go at a solution here

When use getOne and findOne methods Spring Data JPA

TL;DR

T findOne(ID id) (name in the old API) / Optional<T> findById(ID id) (name in the new API) relies on EntityManager.find() that performs an entity eager loading.

T getOne(ID id) relies on EntityManager.getReference() that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.

findOne()/findById() is really more clear and simple to use than getOne().
So in the very most of cases, favor findOne()/findById() over getOne().


API Change

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Previously, it was defined in the CrudRepository interface as :

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is which one defined in the QueryByExampleExecutor interface as :

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want to that as replacement.

In fact, the method with the same behavior is still there in the new API but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional. Which is not so bad to prevent NullPointerException.

So, the actual choice is now between Optional<T> findById(ID id) and T getOne(ID id).


Two distinct methods that rely on two distinct JPA EntityManager retrieval methods

1) The Optional<T> findById(ID id) javadoc states that it :

Retrieves an entity by its id.

As we look into the implementation, we can see that it relies on EntityManager.find() to do the retrieval :

public Optional<T> findById(ID id) {

    Assert.notNull(id, ID_MUST_NOT_BE_NULL);

    Class<T> domainType = getDomainClass();

    if (metadata == null) {
        return Optional.ofNullable(em.find(domainType, id));
    }

    LockModeType type = metadata.getLockModeType();

    Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();

    return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}

And here em.find() is an EntityManager method declared as :

public <T> T find(Class<T> entityClass, Object primaryKey,
                  Map<String, Object> properties);

Its javadoc states :

Find by primary key, using the specified properties

So, retrieving a loaded entity seems expected.

2) While the T getOne(ID id) javadoc states (emphasis is mine) :

Returns a reference to the entity with the given identifier.

In fact, the reference terminology is really board and JPA API doesn't specify any getOne() method.
So the best thing to do to understand what the Spring wrapper does is looking into the implementation :

@Override
public T getOne(ID id) {
    Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    return em.getReference(getDomainClass(), id);
}

Here em.getReference() is an EntityManager method declared as :

public <T> T getReference(Class<T> entityClass,
                              Object primaryKey);

And fortunately, the EntityManager javadoc defined better its intention (emphasis is mine) :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

So, invoking getOne() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.

It means that if we invoke getOne() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable.
For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.
So in this kind of situation, the throw of EntityNotFoundException that is the main reason to use getOne() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

In any case, to ensure its loading you have to manipulate the entity while the session is opened. You can do it by invoking any method on the entity.
Or a better alternative use findById(ID id) instead of.


Why a so unclear API ?

To finish, two questions for Spring-Data-JPA developers:

  • why not having a clearer documentation for getOne() ? Entity lazy loading is really not a detail.

  • why do you need to introduce getOne() to wrap EM.getReference() ?
    Why not simply stick to the wrapped method :getReference() ? This EM method is really very particular while getOne() conveys a so simple processing.

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

How to get correct timestamp in C#

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

angular.service vs angular.factory

  angular.service('myService', myServiceFunction);
  angular.factory('myFactory', myFactoryFunction);

I had trouble wrapping my head around this concept until I put it to myself this way:

Service: the function that you write will be new-ed:

  myInjectedService  <----  new myServiceFunction()

Factory: the function (constructor) that you write will be invoked:

  myInjectedFactory  <---  myFactoryFunction()

What you do with that is up to you, but there are some useful patterns...

Such as writing a service function to expose a public API:

function myServiceFunction() {
  this.awesomeApi = function(optional) {
    // calculate some stuff
    return awesomeListOfValues;
  }
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.awesome = myInjectedService.awesomeApi();

Or using a factory function to expose a public API:

function myFactoryFunction() {
  var aPrivateVariable = "yay";

  function hello() {
    return "hello mars " + aPrivateVariable;
  }
  
  // expose a public API
  return {
    hello: hello
  };
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.hello = myInjectedFactory.hello();

Or using a factory function to return a constructor:

function myFactoryFunction() {
    return function() {
        var a = 2;
        this.a2 = function() {
            return a*2;
        };
    };
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();

Which one to use?...

You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:

var myShinyNewObject = new myInjectedService.myFunction()

which is arguably less desirable than this:

var myShinyNewObject = new myInjectedFactory();

(But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.)


One more thing, they are all Singletons...

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

Error message Strict standards: Non-static method should not be called statically in php

I think this may answer your question.

Non-static method ..... should not be called statically

If the method is not static you need to initialize it like so:

$var = new ClassName();
$var->method();

Or, in PHP 5.4+, you can use this syntax:

(new ClassName)->method();

Difference between System.DateTime.Now and System.DateTime.Today

I thought of Adding these links -

Coming back to original question , Using Reflector i have explained the difference in code

 public static DateTime Today
    {
      get
      {
        return DateTime.Now.Date;   // It returns the date part of Now

        //Date Property
       // returns same date as this instance, and the time value set to 12:00:00 midnight (00:00:00) 
      }
    }


    private const long TicksPerMillisecond = 10000L;
    private const long TicksPerDay = 864000000000L;
    private const int MillisPerDay = 86400000;

    public DateTime Date
    {
       get
      {
        long internalTicks = this.InternalTicks; // Date this instance is converted to Ticks 
        return new DateTime((ulong) (internalTicks - internalTicks % 864000000000L) | this.InternalKind);  
// Modulo of TicksPerDay is subtracted - which brings the time to Midnight time 
      }
    }


     public static DateTime Now
        {
          get
          {
           /* this is why I guess Jon Skeet is recommending to use  UtcNow as you can see in one of the above comment*/
            DateTime utcNow = DateTime.UtcNow;


            /* After this i guess it is Timezone conversion */
            bool isAmbiguousLocalDst = false;
            long ticks1 = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
            long ticks2 = utcNow.Ticks + ticks1;
            if (ticks2 > 3155378975999999999L)
              return new DateTime(3155378975999999999L, DateTimeKind.Local);
            if (ticks2 < 0L)
              return new DateTime(0L, DateTimeKind.Local);
            else
              return new DateTime(ticks2, DateTimeKind.Local, isAmbiguousLocalDst);
          }
        }

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

About "*.d.ts" in TypeScript

Worked example for a specific case:

Let's say you have my-module that you're sharing via npm.

You install it with npm install my-module

You use it thus:

import * as lol from 'my-module';

const a = lol('abc', 'def');

The module's logic is all in index.js:

module.exports = function(firstString, secondString) {

  // your code

  return result
}

To add typings, create a file index.d.ts:

declare module 'my-module' {
  export default function anyName(arg1: string, arg2: string): MyResponse;
}

interface MyResponse {
  something: number;
  anything: number;
}

calling server side event from html button control

just use this at the end of your button click event

protected void btnAddButton_Click(object sender, EventArgs e)
{
   ... save data routin 
     Response.Redirect(Request.Url.AbsoluteUri);
}

Code coverage for Jest built on top of Jasmine

Try Chutzpah. I have just used it. And I blogged about it on how to integrate in Visual Studio.

This is how I did code coverage with Chutzpah: Code Coverage with Chutzpah

Set order of columns in pandas dataframe

I find this to be the most straightforward and working:

df = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

df = df[['one thing','second thing', 'other thing']]

What is makeinfo, and how do I get it?

For Centos , I solve it by installing these packages.

yum install texi2html texinfo 

Dont worry if there is no entry for makeinfo. Just run

make all

You can do it similarly for ubuntu using sudo.

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

Visual Studio Code pylint: Unable to import 'protorpc'

For your case, add the following code to vscode's settings.json.

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]

For the other who got troubles with pip packages, you can go with

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]

You should replace python3.7 above with your python version.

Get the height and width of the browser viewport without scrollbars using jquery?

Description

The following will give you the size of the browsers viewport.

Sample

$(window).height();   // returns height of browser viewport
$(window).width();   // returns width of browser viewport

More Information

IDEA: javac: source release 1.7 requires target release 1.7

check .idea/misc.xml sometimes you need to change languageLevel="JDK_1_X" attribute manually

jQuery - find child with a specific class

$(this).find(".bgHeaderH2").html();

or

$(this).find(".bgHeaderH2").text();

How to move a marker in Google Maps API

You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.

How to format numbers as currency string?

A quiker way with regexp ?

Number.prototype.toMonetaryString=function(){var n=this.toFixed(2),m;
// var=this.toFixed(2).replace(/\./,','); for comma separator
// with a space for thousands separator
  while ((m=n.replace(/(\d)(\d\d\d)\b/g,'$1 $2'))!=n) n=m; 
  return m;
}
String.prototype.fromMonetaryToNumber=function(s){
  return this.replace(/[^\d-]+/g,'')/100;
}   

How can I create an editable dropdownlist in HTML?

A combobox is unfortunately something that was left out of the HTML specifications.

The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.

How to convert a single char into an int

#define toDigit(c) (c-'0')

OpenCV in Android Studio

The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this(1) SO answer.

  1. Download latest OpenCV sdk for Android from OpenCV.org and decompress the zip file.
  2. Import OpenCV to Android Studio, From File -> New -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and d) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom, choose Module Dependency and select the imported OpenCV module.
    • For Android Studio v1.2.2, to access to Module Settings : in the project view, right-click the dependent module -> Open Module Settings
  5. Copy libs folder under sdk/native to Android Studio under app/src/main.
  6. In Android Studio, rename the copied libs directory to jniLibs and we are done.

Step (6) is since Android studio expects native libs in app/src/main/jniLibs instead of older libs folder. For those new to Android OpenCV, don't miss below steps

  • include static{ System.loadLibrary("opencv_java"); } (Note: for OpenCV version 3 at this step you should instead load the library opencv_java3.)
  • For step(5), if you ignore any platform libs like x86, make sure your device/emulator is not on that platform.

OpenCV written is in C/C++. Java wrappers are

  1. Android OpenCV SDK - OpenCV.org maintained Android Java wrapper. I suggest this one.
  2. OpenCV Java - OpenCV.org maintained auto generated desktop Java wrapper.
  3. JavaCV - Popular Java wrapper maintained by independent developer(s). Not Android specific. This library might get out of sync with OpenCV newer versions.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Reloading submodules in IPython

In IPython 0.12 (and possibly earlier), you can use this:

%load_ext autoreload
%autoreload 2

This is essentially the same as the answer by pv., except that the extension has been renamed and is now loaded using %load_ext.

Python: Best way to add to sys.path relative to the current running script

If you don't want to change the script content in any ways, prepend the current working directory . to $PYTHONPATH (see example below)

PYTHONPATH=.:$PYTHONPATH alembic revision --autogenerate -m "First revision"

And call it a day!

"Eliminate render-blocking CSS in above-the-fold content"

Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Delete all rows in a table based on another table

delete
    table1
from 
    t2
where
    table1.ID=t2.ID

Works on mssql

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Making the main scrollbar always visible

body { height:101%; } will "crop" larger pages.

Instead, I use:

body { min-height:101%; }

How to get the name of the current method from code

I think the best way to get the full name is:

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

or try this

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

How many socket connections can a web server handle?

To add my two cents to the conversation a process can have simultaneously open a number of sockets connected equal to this number (in Linux type sytems) /proc/sys/net/core/somaxconn

cat /proc/sys/net/core/somaxconn

This number can be modified on the fly (only by root user of course)

echo 1024 > /proc/sys/net/core/somaxconn

But entirely depends on the server process, the hardware of the machine and the network, the real number of sockets that can be connected before crashing the system

Getting the screen resolution using PHP

I don't think you can detect the screen size purely with PHP but you can detect the user-agent..

<?php
    if ( stristr($ua, "Mobile" )) {
        $DEVICE_TYPE="MOBILE";
    }

    if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
        echo '<link rel="stylesheet" href="/css/mobile.css" />'
    }
?>

Here's a link to a more detailed script: PHP Mobile Detect

Polynomial time and exponential time

O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.

Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

The current accepted answer by crack is deprecated in Symfony 2.3 and will be removed by 3.0. It should be moved to the constructor:

public function __construct($environment, $debug) {
    date_default_timezone_set('Europe/Warsaw');
    parent::__construct($environment, $debug);
}

How to count the number of set bits in a 32-bit integer?

What do you means with "Best algorithm"? The shorted code or the fasted code? Your code look very elegant and it has a constant execution time. The code is also very short.

But if the speed is the major factor and not the code size then I think the follow can be faster:

       static final int[] BIT_COUNT = { 0, 1, 1, ... 256 values with a bitsize of a byte ... };
        static int bitCountOfByte( int value ){
            return BIT_COUNT[ value & 0xFF ];
        }

        static int bitCountOfInt( int value ){
            return bitCountOfByte( value ) 
                 + bitCountOfByte( value >> 8 ) 
                 + bitCountOfByte( value >> 16 ) 
                 + bitCountOfByte( value >> 24 );
        }

I think that this will not more faster for a 64 bit value but a 32 bit value can be faster.

How to redirect back to form with input - Laravel 5

write old function on your fields value for example

<input type="text" name="username" value="{{ old('username') }}">

How set background drawable programmatically in Android

try this.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

Unlink of file Failed. Should I try again?

In my case there are no processes touching the file or directory. Maybe it happens if the path is very long, because an operating system restriction (windows). Try enabling the longpath support flag in the global git configuration as indicated below:

git config --global core.longpaths true

or try to setting the yes/no answer flag if it is not conflictive for you

set GIT_ASK_YESNO=false

If the path is too long, I've not found a successful solution.

SQL "IF", "BEGIN", "END", "END IF"?

If this is MS Sql Server then what you have should work fine... In fact, technically, you don;t need the Begin & End at all, snce there's only one statement in the begin-End Block... (I assume @Classes is a table variable ?)

If @Term = 3
   INSERT INTO @Classes
    SELECT                  XXXXXX  
     FROM XXXX blah blah blah
-- -----------------------------

 -- This next should always run, if the first code did not throw an exception... 
 INSERT INTO @Classes    
 SELECT XXXXXXXX        
 FROM XXXXXX (more code)

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>

</body>
</html>

Where 'div' is your animated object.

I hope you find this useful.

Thanks.

How to get multiple selected values of select box in php?

I fix my problem with javascript + HTML. First i check selected options and save its in a hidden field of my form:

for(i=0; i < form.select.options.length; i++)
   if (form.select.options[i].selected)
    form.hidden.value += form.select.options[i].value;

Next, i get by post that field and get all the string ;-) I hope it'll be work for somebody more. Thanks to all.

Suppress output of a function

invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1:  " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2:  " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3:  " ,bin3interval, fill = TRUE))

produces output without NULL at the end of the line or on the next line

Dataset:  17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width:  15.33333

Bin1:   17 32.33333
Bin2:   32.33333 47.66667
Bin3:   47.66667 63

Working with a List of Lists in Java

Something like this would work for reading:

String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try 
{
    input =  new BufferedReader(new FileReader(filename));
    String line = null;
    while (( line = input.readLine()) != null)
    {
        String[] data = line.split(",");
        csvData.add(Arrays.toList(data));
    }
}
catch (Exception ex)
{
      ex.printStackTrace();
}
finally 
{
    if(input != null)
    {
        input.close();
    }
}

How to unzip files programmatically in Android?

I'm working with zip files which Java's ZipFile class isn't able to handle. Java 8 apparently can't handle compression method 12 (bzip2 I believe). After trying a number of methods including zip4j (which also fails with these particular files due to another issue), I had success with Apache's commons-compress which supports additional compression methods as mentioned here.

Note that the ZipFile class below is not the one from java.util.zip.

It's actually org.apache.commons.compress.archivers.zip.ZipFile so be careful with the imports.

try (ZipFile zipFile = new ZipFile(archiveFile)) {
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        File entryDestination = new File(destination, entry.getName());
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
            }
        }
    }
} catch (IOException ex) {
    log.debug("Error unzipping archive file: " + archiveFile, ex);
}

For Gradle:

compile 'org.apache.commons:commons-compress:1.18'

Is this the proper way to do boolean test in SQL?

In SQL Server you would generally use. I don't know about other database engines.

select * from users where active = 0

Html helper for <input type="file" />

This also works:

Model:

public class ViewModel
{         
    public HttpPostedFileBase File{ get; set; }
}

View:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })       
}

Controller action:

[HttpPost]
public ActionResult Action(ViewModel model)
{
    if (ModelState.IsValid)
    {
        var postedFile = Request.Files["File"];

       // now you can get and validate the file type:
        var isFileSupported= IsFileSupported(postedFile);

    }
}

public bool IsFileSupported(HttpPostedFileBase file)
            {
                var isSupported = false;

                switch (file.ContentType)
                {

                    case ("image/gif"):
                        isSupported = true;
                        break;

                    case ("image/jpeg"):
                        isSupported = true;
                        break;

                    case ("image/png"):
                        isSupported = true;
                        break;


                    case ("audio/mp3"):  
                        isSupported = true;
                        break;

                    case ("audio/wav"):  
                        isSupported = true;
                        break;                                 
                }

                return isSupported;
            }

List of contentTypes

How to align an indented line in a span that wraps into multiple lines?

<span> elements are inline elements, as such layout properties such as width or margin don't work. You can fix that by either changing the <span> to a block element (such as <div>), or by using padding instead.

Note that making a span element a block element by adding display: block; is redundant, as a span is by definition a otherwise style-less inline element whereas div is an otherwise style-less block element. So the correct solution is to use a div instead of a block-span.

How to catch a click event on a button?

The absolutely best way: Just let your activity implement View.OnClickListener, and write your onClick method like this:

public void onClick(View v) {
    final int id = v.getId();
    switch (id) {
    case R.id.button1:
        // your code for button1 here
        break;
    case R.id.button2:
        // your code for button2 here
        break;
    // even more buttons here
    }
}

Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick:

<Button
    android:id="@+id/button1"
    android:onClick="onClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1" />

That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.

How can jQuery deferred be used?

The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases. jQuery.when() handles a non-Promise/Deferred as a Completed one, immediately executing any .done() or .then() on the chain.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Another real world example using the $.when helper:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});

SQL Server Configuration Manager not found

If you don't have any version of SQLServerManagerXX.msc, then you simply do not have it installed. I noticed it does not come with SQL server management studio 2019.

It's available (client-connectivity tools) in the SQL Server Express edition or SQL Server Developer edition which is good for dev/test (non-production) usage.

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

React - Preventing Form Submission

function onTestClick(evt) {
  evt.stopPropagation();
}

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

Include another JSP file

For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %> in my index.jsp then in the other jsp files like register.jsp I had to use <%@ include file="footer.jsp"%>. As you see there was no more need to use full path, STS had store my initial path.

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

Android failed to load JS bundle

The initial question was about reloading the application in a phyisical device.

When you're debugging the application in a physical device (ie via adb), you can reload the JS bundle by clicking on the top left "action" button of your device. This will open the option menu (Reload, Debug JS remotely...).

Hope this helps.

Parsing date string in Go

For those of you out there that are encountering this, use the time.RFC3339 versus the string constant of "2006-01-02T15:04:05.000Z". And here is the reason why:

regDate := "2007-10-09T22:50:01.23Z"

layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)

if err != nil {
    fmt.Println("Static format doesn't work")
} else {
    fmt.Println(t1)
}

layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)

if err != nil {
    fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
    fmt.Println(t2)
}

This will produce the following result:

Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC

Here is the Playground Link

Remove excess whitespace from within a string

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.

function secureRip(string $str): string { /* Rips all whitespace securely. */
  $arr = str_split($str, 1);
  $retStr = '';
  foreach ($arr as $char) {
    $retStr .= trim($char);
  }
  return $retStr;
}

Split an integer into digits to compute an ISBN checksum

(number/10**x)%10

You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.

Getting the text that follows after the regex match

You need to use the group(int) of your matcher - group(0) is the entire match, and group(1) is the first group you marked. In the example you specify, group(1) is what comes after "sentence".

The openssl extension is required for SSL/TLS protection

After trying everything, I finally managed to get this sorted. None of the above suggested solutions worked for me. My system is A PC Windows 10. In order to get this sorted I had to change the config.json file located here C:\Users\[Your User]\AppData\Roaming\Composer\. In there, you will find:

{
    "config": {
        "disable-tls": true},
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "http://repo.packagist.org" // this needs to change to 'https'
        }
    }
}

where you need to update the packagist repo url to point to the 'https' url version.

I am aware that the above selected solution will work for 95% of the cases, but as I said, that did not work for me. Hope this helps someone.

Happy coding!

fatal error LNK1169: one or more multiply defined symbols found in game programming

just add /FORCE as linker flag and you're all set.

for instance, if you're working on CMakeLists.txt. Then add following line:

SET(CMAKE_EXE_LINKER_FLAGS  "/FORCE")

Visual Studio loading symbols

For me, it seems related to breakpoints, as indicated in the accepted answer. However, I found two workarounds that did not involve deleting all the breakpoints:

  • Restarting Visual Studio seemed to fix it temporarily.
  • Clicking the "X" button to close Visual Studio while debugging causes the "Do you want to stop debugging?" message box to pop up; while this message box is up, the symbols load at ordinary speeds. Once all the symbols are loaded, you can click "No" to cancel the close.

How to force a script reload and re-execute?

Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.

<script>
    function reload_js(src) {
        $('script[src="' + src + '"]').remove();
        $('<script>').attr('src', src).appendTo('head');
    }
    reload_js('source_file.js');
</script>

Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

Another option is using command line:

code -d left.txt right.txt

Note: You may need to add code to your path first. See: How to call VS Code Editor from command line

How do I discard unstaged changes in Git?

Tried all the solutions above but still couldn't get rid of new, unstaged files.

Use git clean -f to remove those new files - with caution though! Note the force option.

How do I get the picture size with PIL?

Followings gives dimensions as well as channels:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <span class="sr-only">Toggle navigation</span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

What exactly does the .join() method do?

To append a string, just concatenate it with the + sign.

E.g.

>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world

join connects strings together with a separator. The separator is what you place right before the join. E.g.

>>> "-".join([a,b])
'Hello, -world'

Join takes a list of strings as a parameter.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Is a good idea named the functions with commun alias on the first words for filtre the name with LIKE Example with public schema in Postgresql 9.4, be sure to replace with his scheme

SELECT routine_name 
FROM information_schema.routines 
WHERE routine_type='FUNCTION' 
  AND specific_schema='public'
  AND routine_name LIKE 'aliasmyfunctions%';

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

Bootstrap 3 scrollable div for table

A scrolling comes from a box with class pre-scrollable

<div class="pre-scrollable"></div>

There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.

Just get column names from hive table

use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

$cd ~
$ls

Returning a C string from a function

Well, in your code you are trying to return a String (in C which is nothing but a null-terminated array of characters), but the return type of your function is char which is causing all the trouble for you. Instead you should write it this way:

const char* myFunction()
{

    return "My String";

}

And it's always good to qualify your type with const while assigning literals in C to pointers as literals in C aren't modifiable.

Eventviewer eventid for lock and unlock

The event IDs to look for in pre-Vista Windows are 528, 538, and 680. 528 usually stands for successful unlock of workstation.

The codes for newer Windows versions differ, see below answers for more infos.

How do I get a list of all the duplicate items using pandas in python?

Method #1: print all rows where the ID is one of the IDs in duplicated:

>>> import pandas as pd
>>> df = pd.read_csv("dup.csv")
>>> ids = df["ID"]
>>> df[ids.isin(ids[ids.duplicated()])].sort("ID")
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

but I couldn't think of a nice way to prevent repeating ids so many times. I prefer method #2: groupby on the ID.

>>> pd.concat(g for _, g in df.groupby("ID") if len(g) > 1)
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

Python error "ImportError: No module named"

Based on your comments to orip's post, I guess this is what happened:

  1. You edited __init__.py on windows.
  2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
  3. You used WinSCP to copy the file to your unix box.
  4. WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data."
  5. The missing __init__.py (now called __init__.py.bin) means python doesn't understand toolkit as a package.
  6. You create __init__.py in the appropriate directory and everything works... ?

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

How to properly compare two Integers in Java?

this method compares two Integer with null check, see tests

public static boolean compare(Integer int1, Integer int2) {
    if(int1!=null) {
        return int1.equals(int2);
    } else {
        return int2==null;
    }
    //inline version:
    //return (int1!=null) ? int1.equals(int2) : int2==null;
}

//results:
System.out.println(compare(1,1));           //true
System.out.println(compare(0,1));           //false
System.out.println(compare(1,0));           //false
System.out.println(compare(null,0));        //false
System.out.println(compare(0,null));        //false
System.out.println(compare(null,null));     //true

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Convert pem key to ssh-rsa format

No need for scripts or other 'tricks': openssl and ssh-keygen are enough. I'm assuming no password for the keys (which is bad).

Generate an RSA pair

All the following methods give an RSA key pair in the same format

  1. With openssl (man genrsa)

    openssl genrsa -out dummy-genrsa.pem 2048
    

    In OpenSSL v1.0.1 genrsa is superseded by genpkey so this is the new way to do it (man genpkey):

    openssl genpkey -algorithm RSA -out dummy-genpkey.pem -pkeyopt rsa_keygen_bits:2048
    
  2. With ssh-keygen

    ssh-keygen -t rsa -b 2048 -f dummy-ssh-keygen.pem -N '' -C "Test Key"
    

Converting DER to PEM

If you have an RSA key pair in DER format, you may want to convert it to PEM to allow the format conversion below:

Generation:

openssl genpkey -algorithm RSA -out genpkey-dummy.cer -outform DER -pkeyopt rsa_keygen_bits:2048

Conversion:

openssl rsa -inform DER -outform PEM -in genpkey-dummy.cer -out dummy-der2pem.pem

Extract the public key from the PEM formatted RSA pair

  1. in PEM format:

    openssl rsa -in dummy-xxx.pem -pubout
    
  2. in OpenSSH v2 format see:

    ssh-keygen -y -f dummy-xxx.pem
    

Notes

OS and software version:

[user@test1 ~]# cat /etc/redhat-release ; uname -a ; openssl version
CentOS release 6.5 (Final)
Linux test1.example.local 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
OpenSSL 1.0.1e-fips 11 Feb 2013

References:

How can I call controller/view helper methods from the console in Ruby on Rails?

The earlier answers are calling helpers, but the following will help for calling controller methods. I have used this on Ruby on Rails 2.3.2.

First add the following code to your .irbrc file (which can be in your home directory)

class Object
   def request(options = {})
     url=app.url_for(options)
     app.get(url)
     puts app.html_document.root.to_s
  end
end

Then in the Ruby on Rails console you can type something like...

request(:controller => :show, :action => :show_frontpage)

...and the HTML will be dumped to the console.

VBA - Select columns using numbers?

Try using the following, where n is your variable and x is your offset (4 in this case):

LEFT(ADDRESS(1,n+x,4),1)

This will return the letter of that column (so for n=1 and x=4, it'll return A+4 = E). You can then use INDIRECT() to reference this, as so:

COLUMNS(INDIRECT(LEFT(ADDRESS(1,n,4),1)&":"&LEFT(ADDRESS(1,n+x,4),1)))

which with n=1, x=4 becomes:

COLUMNS(INDIRECT("A"&":"&"E"))

and so:

COLUMNS(A:E)

Self Join to get employee manager name

CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName, 
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM   tblEmployeeDetails e1
       JOIN tblEmployeeDetails e2
       ON e1.emp_mgr_id = e2.emp_id

EDIT: Left Join will work if emp_mgr_id is null.

CREATE VIEW AS 
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,  
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName 
FROM   tblEmployeeDetails e1 
       LEFT JOIN tblEmployeeDetails e2 
       ON e1.emp_mgr_id = e2.emp_id

How to show current user name in a cell?

This displays the name of the current user:

Function Username() As String
    Username = Application.Username
End Function

The property Application.Username holds the name entered with the installation of MS Office.

Enter this formula in a cell:

=Username()

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

How do I change the figure size for a seaborn plot?

Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.

sns.catplot(data=df, x='xvar', y='yvar', 
    hue='hue_bar', height=8.27, aspect=11.7/8.27)

See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.

Determine Whether Two Date Ranges Overlap

the simplest

The simplest way is to use a well-engineered dedicated library for date-time work.

someInterval.overlaps( anotherInterval )

java.time & ThreeTen-Extra

The best in the business is the java.time framework built into Java 8 and later. Add to that the ThreeTen-Extra project that supplements java.time with additional classes, specifically the Interval class we need here.

As for the language-agnostic tag on this Question, the source code for both projects is available for use in other languages (mind their licenses).

Interval

The org.threeten.extra.Interval class is handy, but requires date-time moments (java.time.Instant objects) rather than date-only values. So we proceed by using the first moment of the day in UTC to represent the date.

Instant start = Instant.parse( "2016-01-01T00:00:00Z" );
Instant stop = Instant.parse( "2016-02-01T00:00:00Z" );

Create an Interval to represent that span of time.

Interval interval_A = Interval.of( start , stop );

We can also define an Interval with a starting moment plus a Duration.

Instant start_B = Instant.parse( "2016-01-03T00:00:00Z" );
Interval interval_B = Interval.of( start_B , Duration.of( 3 , ChronoUnit.DAYS ) );

Comparing to test for overlaps is easy.

Boolean overlaps = interval_A.overlaps( interval_B );

You can compare an Interval against another Interval or Instant:

All of these use the Half-Open approach to defining a span of time where the beginning is inclusive and the ending is exclusive.

How to save CSS changes of Styles panel of Chrome Developer Tools?

To answer the last part of your question about any extensions that can save changes, there is hotfix

It allows you to save changes from Chrome Dev Tools directly to GitHub. From there you can set up a post-receive hook on GitHub to automatically update your website.

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the other encode method in URLEncoder:

URLEncoder.encode(String, String)

The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8). For example:

System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);