Programs & Examples On #Jmenu

0

Java: Local variable mi defined in an enclosing scope must be final or effectively final

What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.

Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).

I would suggest two workarounds : Either you make your own class that implements actionlistenner and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.

Or (and this is probably the best solution) just qualify a copy of the variable final to access it in the inner scope as the error suggests to make it a constant:

This would suit your case since you are not modifying the value of the variable.

How to make FileFilter in java?

... What about using Apache's FileFilters from: org.apache.commons.io?

just like:

 import org.apache.commons.io.filefilter.FileFileFilter;
 import org.apache.commons.io.filefilter.WildcardFileFilter;

 ...

 File dir = new File(".");

 String[] filters = { "*.txt"};
 IOFileFilter wildCardFilter = new WildcardFileFilter(filters, IOCase.INSENSITIVE);

 String[] files = dir.list( wildCardFilter );
 for ( int i = 0; i < files.length; i++ ) {
     System.out.println(files[i]);
 }

How do I create a right click context menu in Java Swing?

The following code implements a default context menu known from Windows with copy, cut, paste, select all, undo and redo functions. It also works on Linux and Mac OS X:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DefaultContextMenu extends JPopupMenu
{
    private Clipboard clipboard;

    private UndoManager undoManager;

    private JMenuItem undo;
    private JMenuItem redo;
    private JMenuItem cut;
    private JMenuItem copy;
    private JMenuItem paste;
    private JMenuItem delete;
    private JMenuItem selectAll;

    private JTextComponent textComponent;

    public DefaultContextMenu()
    {
        undoManager = new UndoManager();
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        addPopupMenuItems();
    }

    private void addPopupMenuItems()
    {
        undo = new JMenuItem("Undo");
        undo.setEnabled(false);
        undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        undo.addActionListener(event -> undoManager.undo());
        add(undo);

        redo = new JMenuItem("Redo");
        redo.setEnabled(false);
        redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        redo.addActionListener(event -> undoManager.redo());
        add(redo);

        add(new JSeparator());

        cut = new JMenuItem("Cut");
        cut.setEnabled(false);
        cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        cut.addActionListener(event -> textComponent.cut());
        add(cut);

        copy = new JMenuItem("Copy");
        copy.setEnabled(false);
        copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        copy.addActionListener(event -> textComponent.copy());
        add(copy);

        paste = new JMenuItem("Paste");
        paste.setEnabled(false);
        paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        paste.addActionListener(event -> textComponent.paste());
        add(paste);

        delete = new JMenuItem("Delete");
        delete.setEnabled(false);
        delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        delete.addActionListener(event -> textComponent.replaceSelection(""));
        add(delete);

        add(new JSeparator());

        selectAll = new JMenuItem("Select All");
        selectAll.setEnabled(false);
        selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        selectAll.addActionListener(event -> textComponent.selectAll());
        add(selectAll);
    }

    private void addTo(JTextComponent textComponent)
    {
        textComponent.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent pressedEvent)
            {
                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canUndo())
                    {
                        undoManager.undo();
                    }
                }

                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canRedo())
                    {
                        undoManager.redo();
                    }
                }
            }
        });

        textComponent.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }

            @Override
            public void mouseReleased(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }
        });

        textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
    }

    private void handleContextMenu(MouseEvent releasedEvent)
    {
        if (releasedEvent.getButton() == MouseEvent.BUTTON3)
        {
            processClick(releasedEvent);
        }
    }

    private void processClick(MouseEvent event)
    {
        textComponent = (JTextComponent) event.getSource();
        textComponent.requestFocus();

        boolean enableUndo = undoManager.canUndo();
        boolean enableRedo = undoManager.canRedo();
        boolean enableCut = false;
        boolean enableCopy = false;
        boolean enablePaste = false;
        boolean enableDelete = false;
        boolean enableSelectAll = false;

        String selectedText = textComponent.getSelectedText();
        String text = textComponent.getText();

        if (text != null)
        {
            if (text.length() > 0)
            {
                enableSelectAll = true;
            }
        }

        if (selectedText != null)
        {
            if (selectedText.length() > 0)
            {
                enableCut = true;
                enableCopy = true;
                enableDelete = true;
            }
        }

        if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
        {
            enablePaste = true;
        }

        undo.setEnabled(enableUndo);
        redo.setEnabled(enableRedo);
        cut.setEnabled(enableCut);
        copy.setEnabled(enableCopy);
        paste.setEnabled(enablePaste);
        delete.setEnabled(enableDelete);
        selectAll.setEnabled(enableSelectAll);

        // Shows the popup menu
        show(textComponent, event.getX(), event.getY());
    }

    public static void addDefaultContextMenu(JTextComponent component)
    {
        DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
        defaultContextMenu.addTo(component);
    }
}

Usage:

JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);

Now the textArea will have a context menu when it is right-clicked on.

Find a file by name in Visual Studio Code

I believe the action name is "workbench.action.quickOpen".

How to remove all debug logging calls before building the release version of an Android app?

I like to use Log.d(TAG, some string, often a String.format ()).

TAG is always the class name

Transform Log.d(TAG, --> Logd( in the text of your class

private void Logd(String str){
    if (MainClass.debug) Log.d(className, str);
}

In this way when you are ready to make a release version, set MainClass.debug to false!

How to use the read command in Bash?

I really only use read with "while" and a do loop:

echo "This is NOT a test." | while read -r a b c theRest; do  
echo "$a" "$b" "$theRest"; done  

This is a test.
For what it's worth, I have seen the recommendation to always use -r with the read command in bash.

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Sub CopyValueWithFormatting()
    Sheet1.Range("A1").Copy
    With Sheet2.Range("B1")
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteValues
    End With
End Sub

How to invoke function from external .c file in C?

make a file classAusiliaria.h and in there provide your method signatures.

Now instead of including the .c file include this .h file.

How to find NSDocumentDirectory in Swift?

Usually i prefer like below in swift 3, because i can add file name and create a file easily

let fileManager = FileManager.default
if let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    let databasePath = documentsURL.appendingPathComponent("db.sqlite3").path
    print("directory path:", documentsURL.path)
    print("database path:", databasePath)
    if !fileManager.fileExists(atPath: databasePath) {
        fileManager.createFile(atPath: databasePath, contents: nil, attributes: nil)
    }
}

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

How can I verify if one list is a subset of another?

Most of the solutions consider that the lists do not have duplicates. In case your lists do have duplicates you can try this:

def isSubList(subList,mlist):
    uniqueElements=set(subList)
    for e in uniqueElements:
        if subList.count(e) > mlist.count(e):
            return False     
    # It is sublist
    return True

It ensures the sublist never has different elements than list or a greater amount of a common element.

lst=[1,2,2,3,4]
sl1=[2,2,3]
sl2=[2,2,2]
sl3=[2,5]

print(isSubList(sl1,lst)) # True
print(isSubList(sl2,lst)) # False
print(isSubList(sl3,lst)) # False

Regex replace uppercase with lowercase letters

Try this

  • Find: ([A-Z])([A-Z]+)\b
  • Replace: $1\L$2

Make sure case sensitivity is on (Alt + C)

What is logits, softmax and softmax_cross_entropy_with_logits?

Above answers have enough description for the asked question.

Adding to that, Tensorflow has optimised the operation of applying the activation function then calculating cost using its own activation followed by cost functions. Hence it is a good practice to use: tf.nn.softmax_cross_entropy() over tf.nn.softmax(); tf.nn.cross_entropy()

You can find prominent difference between them in a resource intensive model.

How to use ng-repeat for dictionaries in AngularJs?

You can use

<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>

See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/

Open firewall port on CentOS 7

The answer by ganeshragav is correct, but it is also useful to know that you can use:

firewall-cmd --permanent --zone=public --add-port=2888/tcp 

but if is a known service, you can use:

firewall-cmd --permanent --zone=public --add-service=http 

and then reload the firewall

firewall-cmd --reload

[ Answer modified to reflect Martin Peter's comment, original answer had --permanent at end of command line ]

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

How do I validate a date in rails?

Using the chronic gem:

class MyModel < ActiveRecord::Base
  validate :valid_date?

  def valid_date?
    unless Chronic.parse(from_date)
      errors.add(:from_date, "is missing or invalid")
    end
  end

end

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

PHP check if date between two dates

The above methods are useful but they are not full-proof because it will give error if time is between 12:00 AM/PM and 01:00 AM/PM . It will return the "No Go" in-spite of being in between the timing . Here is the code for the same:

$time = '2019-03-27 12:00 PM';

$date_one = $time; 
$date_one = strtotime($date_one);
$date_one = strtotime("+60 minutes", $date_one);
$date_one =  date('Y-m-d h:i A', $date_one);

$date_ten = strtotime($time); 
$date_ten = strtotime("-12 minutes", $date_ten); 
$date_ten = date('Y-m-d h:i A', $date_ten);

$paymentDate='2019-03-27 12:45 AM';

$contractDateBegin = date('Y-m-d h:i A', strtotime($date_ten)); 
$contractDateEnd = date('Y-m-d h:i A', strtotime($date_one));

echo $paymentDate; 
echo "---------------"; 
echo $contractDateBegin; 
echo "---------------"; 
echo $contractDateEnd; 
echo "---------------";

$contractDateEnd='2019-03-27 01:45 AM';

if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd)  
{  
 echo "is between";
} 
else
{  
  echo "NO GO!";  
}

Here you will get output "NO Go" because 12:45 > 01:45.

To get proper output date in between, make sure that for "AM" values from 01:00 AM to 12:00 AM will get converted to the 24-hour format. This little trick helped me.

How to remove a key from HashMap while iterating over it?

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

How to remove rows with any zero value

There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)

##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

This error also occurs if you are trying to write a unit test case in angular using jasmine.

The basic concept of this error is to import FormsModule. Thus, in the file for unit tests, we add imports Section and place FormsModule in that file under

    TestBed.configureTestingModule
    For eg: 
    TestBed.configureTestingModule({
        declarations: [ XYZComponent ],
        **imports: [FormsModule]**,
    }).compileComponents();

Javascript objects: get parent

A nested object (child) inside another object (parent) cannot get data directly from its parent.

Have a look on this:

var main = {
    name : "main object",
    child : {
        name : "child object"
    }
};

If you ask the main object what its child name is (main.child.name) you will get it.
Instead you cannot do it vice versa because the child doesn't know who its parent is.
(You can get main.name but you won't get main.child.parent.name).

By the way, a function could be useful to solve this clue.
Let's extend the code above:

var main = {
    name : "main object",
    child : {
        name : "child object"
    },
    init : function() {
        this.child.parent = this;
        delete this.init;
        return this;
    }
}.init();

Inside the init function you can get the parent object simply calling this.
So we define the parent property directly inside the child object.
Then (optionally) we can remove the init method.
Finally we give the main object back as output from the init function.

If you try to get main.child.parent.name now you will get it right.
It is a little bit tricky but it works fine.

load jquery after the page is fully loaded

It is advised to load your scripts at the bottom of your <body> block to speed up the page load, like this:

<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>

Finding index of character in Swift String

Swift 3

extension String {
        func substring(from:String) -> String
        {
            let searchingString = from
            let rangeOfSearchingString = self.range(of: searchingString)!
            let indexOfSearchingString: Int = self.distance(from: self.startIndex, to: rangeOfSearchingString.upperBound )
            let trimmedString = self.substring(start: indexOfSearchingString , end: self.count)
            
            return trimmedString
        }
        
    }

What does the "yield" keyword do?

Yet another TL;DR

Iterator on list: next() returns the next element of the list

Iterator generator: next() will compute the next element on the fly (execute code)

You can see the yield/generator as a way to manually run the control flow from outside (like continue loop one step), by calling next, however complex the flow.

Note: The generator is NOT a normal function. It remembers the previous state like local variables (stack). See other answers or articles for detailed explanation. The generator can only be iterated on once. You could do without yield, but it would not be as nice, so it can be considered 'very nice' language sugar.

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Is there a way to collapse all code blocks in Eclipse?

In addition to the hotkey, if you right click in the gutter where you see the +/-, there is a context menu item 'Folding.' Opening the submenu associated with this, you can see a 'Collapse All' item. this will also do what you wish.

JavaScript: Class.method vs. Class.prototype.method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

Consider this example:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

Configure apache to listen on port other than 80

It was a firewall issue. There was a hardware firewall that was blocking access to almost all ports. (Turning off software firewall / SELinux bla bla had no effect)

Then I scanned the open ports and used the port that was open.

If you are facing the same problem, Run the following command

sudo nmap -T Aggressive -A -v 127.0.0.1 -p 1-65000

It will scan for all the open ports on your system. Any port that is open can be accessed from outside.

Ref.: http://www.go2linux.org/which_service_or_program_is_listening_on_port

data.frame Group By column

require(reshape2)

T <- melt(df, id = c("A"))

T <- dcast(T, A ~ variable, sum)

I am not certain the exact advantages over aggregate.

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

What are the ascii values of up down left right?

The ascii values of the:

  1. Up key - 224 72

  2. Down key - 224 80

  3. Left key - 224 75

  4. Right key - 224 77

Each of these has two integer values for ascii value, because they are special keys, as opposed to the code for $, which is simply 36. These 2 byte special keys usually have the first digit as either 224, or 0. this can be found with the F# in windows, or the delete key.

EDIT : This may actually be unicode looking back, but they do work.

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

How can I group data with an Angular filter?

First do a loop using a filter that will return only unique teams, and then a nested loop that returns all players per current team:

http://jsfiddle.net/plantface/L6cQN/

html:

<div ng-app ng-controller="Main">
    <div ng-repeat="playerPerTeam in playersToFilter() | filter:filterTeams">
        <b>{{playerPerTeam.team}}</b>
        <li ng-repeat="player in players | filter:{team: playerPerTeam.team}">{{player.name}}</li>        
    </div>
</div>

script:

function Main($scope) {
    $scope.players = [{name: 'Gene', team: 'team alpha'},
                    {name: 'George', team: 'team beta'},
                    {name: 'Steve', team: 'team gamma'},
                    {name: 'Paula', team: 'team beta'},
                    {name: 'Scruath of the 5th sector', team: 'team gamma'}];

    var indexedTeams = [];

    // this will reset the list of indexed teams each time the list is rendered again
    $scope.playersToFilter = function() {
        indexedTeams = [];
        return $scope.players;
    }

    $scope.filterTeams = function(player) {
        var teamIsNew = indexedTeams.indexOf(player.team) == -1;
        if (teamIsNew) {
            indexedTeams.push(player.team);
        }
        return teamIsNew;
    }
}

AssertionError: View function mapping is overwriting an existing endpoint function: main

For users that use @app.route it is better to use the key-argument endpoint rather then chaning the value of __name__ like Roei Bahumi stated. Taking his example will be:

@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
    pass

@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
    pass

Sass Variable in CSS calc() function

Interpolate:

body
    height: calc(100% - #{$body_padding})

For this case, border-box would also suffice:

body
    box-sizing: border-box
    height: 100%
    padding-top: $body_padding

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

asp.net mvc3 return raw html to view

Give a try to return bootstrap alert message, this worked for me

return Content("<div class='alert alert-success'><a class='close' data-dismiss='alert'>
&times;</a><strong style='width:12px'>Thanks!</strong> updated successfully</div>");

Note: Don't forget to add bootstrap css and js in your view page

hope helps someone.

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

you can use

style="display:none"

Ex:

<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>

Editing in the Chrome debugger

Pretty easy, go to the 'scripts' tab. And select the source file you want and double-click any line to edit it.

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

Cannot stop or restart a docker container

Worth knowing:

If you are running an ENTRYPOINT script ... the script will work with the shebang

#!/bin/bash -x

But will stop the container from stopping with

#!/bin/bash -xe

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

I had this error occur for a different reason.

I created a template for save/cancel buttons that I wanted to appear at top and bottom of the page. It worked at first when I had my template defined inside of a <script type="text/html"> element.... but then I heard you could optionally create a template out of an ordinary DIV element instead.

(This worked better for me since I was using ASP.NET MVC and none of my @variableName Razor syntax was being executed at runtime from inside of the script element. So by changing to a DIV instead, I could still have the MVC Razor engine generate HTML inside my KnockoutJs template when the page loads.)

After I changed my template to use a DIV instead of a SCRIPT element, my code looked like this.... which worked fine on IE10. However, later when I tested it on IE8, it threw that....

"You cannot apply bindings multiple times to the same element" error.....

HTML

<div id="mainKnockoutDiv" class="measurementsDivContents hourlyMeasurements">

  <div id="saveButtons_template" style="display: none;">
    ... my template content here ...
  </div>

  <!--ko template: { name: 'saveButtons_template' } -->
  <!--/ko-->

  Some_HTML_content_here....

  <!--ko template: { name: 'saveButtons_template' } -->
  <!--/ko-->

</div>

JavaScript

ko.applyBindings(viewModel, document.getElementById('mainKnockoutDiv'));

THE SOLUTION:

All I had to do was move my saveButtons_template DIV down to the bottom, so that it was outside of the mainKnockoutDiv. This solved the problem for me.

I suppose KnockoutJs was trying to bind my template DIV multiple times since it was located inside the applyBindings target area... and was not using the SCRIPT element.... and was being referenced as a template.

Capturing Groups From a Grep RegEx

I realize that an answer was already accepted for this, but from a "strictly *nix purist angle" it seems like the right tool for the job is pcregrep, which doesn't seem to have been mentioned yet. Try changing the lines:

    echo $f | grep -oEi '[0-9]+_([a-z]+)_[0-9a-z]*'
    name=$?

to the following:

    name=$(echo $f | pcregrep -o1 -Ei '[0-9]+_([a-z]+)_[0-9a-z]*')

to get only the contents of the capturing group 1.

The pcregrep tool utilizes all of the same syntax you've already used with grep, but implements the functionality that you need.

The parameter -o works just like the grep version if it is bare, but it also accepts a numeric parameter in pcregrep, which indicates which capturing group you want to show.

With this solution there is a bare minimum of change required in the script. You simply replace one modular utility with another and tweak the parameters.

Interesting Note: You can use multiple -o arguments to return multiple capture groups in the order in which they appear on the line.

Check if SQL Connection is Open or Closed

The .NET documentation says: State Property: A bitwise combination of the ConnectionState values

So I think you should check

!myConnection.State.HasFlag(ConnectionState.Open)

instead of

myConnection.State != ConnectionState.Open

because State can have multiple flags.

Is SQL syntax case sensitive?

SQL keywords are case insensitive themselves.

Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).

Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.

Benefits of EBS vs. instance-store (and vice-versa)

We like instance-store. It forces us to make our instances completely recyclable, and we can easily automate the process of building a server from scratch on a given AMI. This also means we can easily swap out AMIs. Also, EBS still has performance problems from time to time.

Initialize a string variable in Python: "" or None?

None is used to indicate "not set", whereas any other value is used to indicate a "default" value.

Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.

Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.

Download a file with Android, and showing the progress in a ProgressDialog

I found this blog post very helpful, Its using loopJ to download file, it has only one Simple function, will be helpful to some new android guys.

Python OpenCV2 (cv2) wrapper to get image size?

import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])

Ouput :- enter image description here

My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg

MySQL Sum() multiple columns

SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
 FROM your_table
 GROUP BY student

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

How to reformat JSON in Notepad++?

You require a plugin to format JSON. To install the plugin do the following steps:

  1. Open notepad++ -> ALT+P -> Plugin Manager -> Selcet JSON Viewer -> Click Install
  2. Restart notepad++
  3. Now you can use shortcut to format json as CTRL + ALT +SHIFT + M or ALT+P -> Plugin Manager -> JSON Viewer -> Format JSON

enter image description here

Could not resolve placeholder in string value

I got the same error in my microservice project.The property itself missed in my yml file.So I added property name and value that resolves my problem

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

When is assembly faster than C?

A use case which might not apply anymore but for your nerd pleasure: On the Amiga, the CPU and the graphics/audio chips would fight for accessing a certain area of RAM (the first 2MB of RAM to be specific). So when you had only 2MB RAM (or less), displaying complex graphics plus playing sound would kill the performance of the CPU.

In assembler, you could interleave your code in such a clever way that the CPU would only try to access the RAM when the graphics/audio chips were busy internally (i.e. when the bus was free). So by reordering your instructions, clever use of the CPU cache, the bus timing, you could achieve some effects which were simply not possible using any higher level language because you had to time every command, even insert NOPs here and there to keep the various chips out of each others radar.

Which is another reason why the NOP (No Operation - do nothing) instruction of the CPU can actually make your whole application run faster.

[EDIT] Of course, the technique depends on a specific hardware setup. Which was the main reason why many Amiga games couldn't cope with faster CPUs: The timing of the instructions was off.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

"fatal: Not a git repository (or any of the parent directories)" from git status

i have the same problem from my office network. i use this command but its not working for me url, so like this: before $ git clone https://gitlab.com/omsharma/Resume.git

After i Use this URL : $ git clone https://[email protected]/omsharma/Resume.git try It.

Retrieve column names from java.sql.ResultSet

When you need the column names, but do not want to grab entries:

PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");

ResultSet set = stmt.executeQuery();

//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }

NOTE: Only works with MySQL

Comparing two arrays & get the values which are not common

Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.

$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)

Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)

How do I call ::CreateProcess in c++ to launch a Windows executable?

On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.

Bytes of a string in Java

The pedantic answer (though not necessarily the most useful one, depending on what you want to do with the result) is:

string.length() * 2

Java strings are physically stored in UTF-16BE encoding, which uses 2 bytes per code unit, and String.length() measures the length in UTF-16 code units, so this is equivalent to:

final byte[] utf16Bytes= string.getBytes("UTF-16BE");
System.out.println(utf16Bytes.length);

And this will tell you the size of the internal char array, in bytes.

Note: "UTF-16" will give a different result from "UTF-16BE" as the former encoding will insert a BOM, adding 2 bytes to the length of the array.

Create two blank lines in Markdown

Try adding multiple spaces (two spaces = one <br>):

mycode(space)(space)(space)(space)

Jenkins, specifying JAVA_HOME

On CentOS 6.x and Redhat 6.x systems, the openjdk-devel package contains the jdk. It's sensible enough if you are familiar with the -devel pattern used in RedHat, but confusing if you're looking for a jdk package that conforms to java naming standards.

Can I apply a CSS style to an element name?

You can use attribute selectors but they won't work in IE6 like meder said, there are javascript workarounds to that tho. Check Selectivizr

More detailed into on attribute selectors: http://www.css3.info/preview/attribute-selectors/

/* turns all input fields that have a name that starts with "go" red */
input[name^="go"] { color: red }

How to downgrade tensorflow, multiple versions possible?

Is it possible to have multiple version of tensorflow on the same OS?

Yes, you can use python virtual environments for this. From the docs:

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

After you have install virtualenv (see the docs), you can create a virtual environment for the tutorial and install the tensorflow version you need in it:

PATH_TO_PYTHON=/usr/bin/python3.5
virtualenv -p $PATH_TO_PYTHON my_tutorial_env 
source my_tutorial_env/bin/activate # this activates your new environment
pip install tensorflow==1.1

PATH_TO_PYTHON should point to where python is installed on your system. When you want to use the other version of tensorflow execute:

deactivate my_tutorial_env

Now you can work again with the tensorflow version that was already installed on your system.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

Locking pattern for proper use of .NET MemoryCache

There is an open source library [disclaimer: that I wrote]: LazyCache that IMO covers your requirement with two lines of code:

IAppCache cache = new CachingService();
var cachedResults = cache.GetOrAdd("CacheKey", 
  () => SomeHeavyAndExpensiveCalculation());

It has built in locking by default so the cacheable method will only execute once per cache miss, and it uses a lambda so you can do "get or add" in one go. It defaults to 20 minutes sliding expiration.

There's even a NuGet package ;)

Can I grep only the first n lines of a file?

An extension to Joachim Isaksson's answer: Quite often I need something from the middle of a long file, e.g. lines 5001 to 5020, in which case you can combine head with tail:

head -5020 file.txt | tail -20 | grep x

This gets the first 5020 lines, then shows only the last 20 of those, then pipes everything to grep.

(Edited: fencepost error in my example numbers, added pipe to grep)

Is there a JavaScript strcmp()?

How about:

String.prototype.strcmp = function(s) {
    if (this < s) return -1;
    if (this > s) return 1;
    return 0;
}

Then, to compare s1 with 2:

s1.strcmp(s2)

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

The EntityManager is closed

This is really old issue, but I just had similar problem. I was doing something like this :

// entity
$entityOne = $this->em->find(Parent::class, 1);

// do something on other entites (SomeEntityClass)
$this->em->persist($entity);
$this->em->flush();
$this->em->clear();

// and at end I was trying to save changes to first one by
$this->em->persist($entityOne);
$this->em->flush();
$this->em->clear();

Problem was that clear detach all entities including the first one and throw error The EntityManager is closed.

In my case solution was to just do clear on distinct type of Entity and leave $entityOne still under EM:

$this->em->clear(SomeEntityClass::class);

byte[] to file in Java

File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Why should text files end with a newline?

This answer is an attempt at a technical answer rather than opinion.

If we want to be POSIX purists, we define a line as:

A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206

An incomplete line as:

A sequence of one or more non- <newline> characters at the end of the file.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195

A text file as:

A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397

A string as:

A contiguous sequence of bytes terminated by and including the first null byte.

Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396

From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).

Case in point: wc -l filename.

From the wc's manual we read:

A line is defined as a string of characters delimited by a <newline> character.

What are the implications to JavaScript, HTML, and CSS files then being that they are text files?

In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).

As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.

At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.

We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.

What are we left with then? System level tooling.

This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc).

Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT.

Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt

Staying on the tooling track, for all practical intents and purposes, let's consider this:

Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.

curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js

$ cat x.js y.js > z.js

-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 x.js
-rw-r--r--  1 milanadamovsky   7905 Aug 14 23:17 y.js
-rw-r--r--  1 milanadamovsky  15810 Aug 14 23:18 z.js

Notice the cat file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.

As someone else mentioned in this thread: what if you want to cat two files whose output becomes just one line instead of two? In other words, cat does what it's supposed to do.

The man of cat only mentions reading input up to EOF, not <newline>. Note that the -n switch of cat will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man.)

-n Number the output lines, starting at 1.

Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.

Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.

For example, instead of using wc -l filename one could do awk '{x++}END{ print x}' filename , and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curld) - unless our intent was truly to count lines in the POSIX compliant sense.

Conclusion

There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.

Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.

Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

This is a right answer. you need to import FormsMoudle

first in app.module.ts

**

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule  } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule,
    ReactiveFormsModule ,
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

** second in app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

Best regards and hope will be helpfull

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

How to find if an array contains a string

Another simple way using JOIN and INSTR

Sub Sample()
    Dim Mainfram(4) As String, strg As String
    Dim cel As Range
    Dim Delim As String

    Delim = "#"

    Mainfram(0) = "apple"
    Mainfram(1) = "pear"
    Mainfram(2) = "orange"
    Mainfram(3) = "fruit"

    strg = Join(Mainfram, Delim)
    strg = Delim & strg

    For Each cel In Selection
        If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
        Rows(cel.Row).Style = "Accent1"
    Next cel
End Sub

How do I use properly CASE..WHEN in MySQL

CASE course_enrollment_settings.base_price is wrong here, it should be just CASE

SELECT 
CASE 
WHEN course_enrollment_settings.base_price = 0      THEN 1 
WHEN course_enrollment_settings.base_price<101      THEN 2 
WHEN course_enrollment_settings.base_price>100 AND    
                  course_enrollment_settings.base_price<201 THEN 3 
    ELSE 6 
END AS 'calc_base_price', 
course_enrollment_settings.base_price 
FROM 
  course_enrollment_settings 
WHERE course_enrollment_settings.base_price = 0 

Some explanations. Your original query will be executed as :

SELECT 
CASE 0
WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
ELSE 6, ...

it's why you always get 3

Getting the absolute path of the executable, using C#?

var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.

For that reason I am posting the answer listed in the comments to give it the exposure it deserves.

How do you stop tracking a remote branch in Git?

To remove the upstream for the current branch do:

$ git branch --unset-upstream

This is available for Git v.1.8.0 or newer. (Sources: 1.7.9 ref, 1.8.0 ref)

source

COUNT / GROUP BY with active record?

This code counts rows with date range:

Controller:

$this->load->model("YourModelName");
$data ['query'] = $this->YourModelName->get_report();

Model:

  public function get_report()
     {   
       $query = $this->db->query("SELECT  *
FROM   reservation WHERE arvdate <= '2016-7-20' AND  dptrdate >= '2016-10-25' ");
       return $query;
     }

where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.

View:

<?php
 echo $query->num_rows();
?>

This code is to return number of rows. To return table data, then use

$query->rows();
return $row->table_column_name;

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Vertically center text in a 100% height div?

have you tried line-height:1em;? I recall that that's the way to get it to center vertically.

How to open a page in a new window or tab from code-behind

Target= "_blank"

This does it in html, give it a try in C#

Blade if(isset) is not working Laravel

Use 3 curly braces if you want to echo

{{{ $usersType or '' }}}

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

The icon will adopt the color from value of the color css property of it's parent.

You can either add this directly to the style:

<span class="glyphicon glyphicon-user" style="color:blue"></span>

Or you can add it as a class to your icon and then set the font color to it in CSS

HTML

<span class="glyphicon glyphicon-search"></span>
<span class="glyphicon glyphicon-user blue"></span>
<span class="glyphicon glyphicon-trash"></span>

CSS

.blue {
    color: blue;
}

This fiddle has an example.

How to Delete node_modules - Deep Nested Folder in Windows

Its too easy.

Just delete all folders inside node_modules and then delete actual node_module folder.

This Works for me. Best luck....

Days between two dates?

Try:

(b-a).days

I tried with b and a of type datetime.date.

Should a function have only one return statement?

The only important question is "How is the code simpler, better readable, easier to understand?" If it is simpler with multiple returns, then use them.

Difference between using "chmod a+x" and "chmod 755"

chmod a+x modifies the argument's mode while chmod 755 sets it. Try both variants on something that has full or no permissions and you will notice the difference.

How do I move focus to next input with jQuery?

why not simply just give the input field where you want to jump to a id and do a simple focus

$("#newListField").focus();

Regular Expression to get all characters before "-"

I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Instead of using lxml use html.parser, you can use this piece of code:

soup = BeautifulSoup(html, 'html.parser')

Query to display all tablespaces in a database and datafiles

In oracle, generally speaking, there are number of facts that I will mention in following section:

  • Each database can have many Schema/User (Logical division).
  • Each database can have many tablespaces (Logical division).
  • A schema is the set of objects (tables, indexes, views, etc) that belong to a user.
  • In Oracle, a user can be considered the same as a schema.
  • A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'

Recommended way to embed PDF in HTML?

To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.

Sleep for milliseconds

nanosleep is a better choice than usleep - it is more resilient against interrupts.

How to automatically convert strongly typed enum into int?

As others have said, you can't have an implicit conversion, and that's by-design.

If you want you can avoid the need to specify the underlying type in the cast.

template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) noexcept {
    return static_cast<typename std::underlying_type<E>::type>(e);
}

std::cout << foo(to_underlying(b::B2)) << std::endl;

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

TL;DR

For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

JAVA_VERSION=11
brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

AJAX Mailchimp signup form integration

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

https://github.com/cgarnier/angular-mailchimp-subscribe

Calculate number of hours between 2 dates in PHP

//Calculate number of hours between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);

Converting XDocument to XmlDocument and vice versa

If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:

using System.Xml; 
using System.Xml.Linq;

namespace www.dimaka.com
{ 
    internal static class LinqHelper 
    { 
        public static XmlDocument ToXmlDocument(this XDocument xDocument) 
        { 
            var xmlDocument = new XmlDocument(); 
            using (var reader = xDocument.CreateReader()) 
            { 
                xmlDocument.Load(reader); 
            }

            var xDeclaration = xDocument.Declaration; 
            if (xDeclaration != null) 
            { 
                var xmlDeclaration = xmlDocument.CreateXmlDeclaration( 
                    xDeclaration.Version, 
                    xDeclaration.Encoding, 
                    xDeclaration.Standalone);

                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild); 
            }

            return xmlDocument; 
        } 
    } 
}

Hope that helps!

C# try catch continue execution

just do this

    try
    {
        //some code
     try
     {
          int idNumber = function2();

     }
     finally
     {
       do stuff here....
     }
    }
    catch(Exception e)
    {//... perhaps something here}

For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.

How to add line break for UILabel?

You have to set the numberOfLines property on the UILabel. The default is 1, if you set it to 0 it will remove all limits.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?

Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.

jQuery Ajax calls and the Html.AntiForgeryToken()

I'm using a ajax post to run a delete method (happens to be from a visjs timeline but that's not relelvant). This is what I sis:

This is my Index.cshtml

@Scripts.Render("~/bundles/schedule")
@Styles.Render("~/bundles/visjs")
@Html.AntiForgeryToken()

<!-- div to attach schedule to -->
<div id='schedule'></div>

<!-- div to attach popups to -->
<div id='dialog-popup'></div>

All I added here was @Html.AntiForgeryToken() to make the token appear in the page

Then in my ajax post I used:

$.ajax(
    {
        type: 'POST',
        url: '/ScheduleWorks/Delete/' + item.id,
        data: {
            '__RequestVerificationToken': 
            $("input[name='__RequestVerificationToken']").val()
              }
     }
);

Which adds the token value, scraped off the page, to the fields posted

Before this I tried putting the value in the headers but I got the same error

Feel free to post improvements. This certainly seems to be a simple approach that I can understand

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

How do I link to Google Maps with a particular longitude and latitude?

It´s out of the scope of the question, but I think it might be also interesting to know how to link to a route. The query would look like this:

https://www.google.es/maps/dir/'52.51758801683297,13.397978515625027'/'52.49083837044266,13.369826049804715'

A variable modified inside a while loop is not remembered

Though this is an old question and asked several times, here's what I'm doing after hours fidgeting with here strings, and the only option that worked for me is to store the value in a file during while loop sub-shells and then retrieve it. Simple.

Use echo statement to store and cat statement to retrieve. And the bash user must chown the directory or have read-write chmod access.

#write to file
echo "1" > foo.txt

while condition; do 
    if (condition); then
        #write again to file
        echo "2" > foo.txt      
    fi
done

#read from file
echo "Value of \$foo in while loop body: $(cat foo.txt)"

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I wrote a quick simple app recent that handle the management of various version of node and npm. It allows you to choose different version of node and npm to download and select which version to use. Check it out and see if it's something that's useful.

https://github.com/nhatkthanh/wnm

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

How can I set the initial value of Select2 when using AJAX?

after spending a few hours searching for a solution, I decided to create my own. He it is:

 function CustomInitSelect2(element, options) {
            if (options.url) {
                $.ajax({
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                    element.select2({
                        data: data
                    });
                    if (options.initialValue) {
                        element.val(options.initialValue).trigger('change');
                    }
                });
            }
        }

And you can initialize the selects using this function:

$('.select2').each(function (index, element) {
            var item = $(element);
            if (item.data('url')) {
                CustomInitSelect2(item, {
                    url: item.data('url'),
                    initialValue: item.data('value')
                });
            }
            else {
                item.select2();
            }
        });

And of course, here is the html:

<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

So, rather return the whole object first, just wrap it to json_encode and then return it. This will return a proper and valid object.

public function id($id){
    $promotion = Promotion::find($id);
    return json_encode($promotion);
}

Or, For DB this will be just like,

public function id($id){
    $promotion = DB::table('promotions')->first();
    return json_encode($promotion);
}

I think it may help someone else.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

I've got this exact error, but in my case I was binding values for the LIMIT clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset; resulted in LIMIT '10' OFFSET '1'; instead of LIMIT 10 OFFSET 1;. What helps to correct that is the following:

$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

Uncaught TypeError: Cannot read property 'appendChild' of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

SELECT FOR UPDATE with SQL Server

Create a fake update to enforce the rowlock.

UPDATE <tablename> (ROWLOCK) SET <somecolumn> = <somecolumn> WHERE id=1

If that's not locking your row, god knows what will.

After this "UPDATE" you can do your SELECT (ROWLOCK) and subsequent updates.

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.

library(ggplot2)
library(ggrepel)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_classic()

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

PHP + MySQL transactions examples

<?php

// trans.php
function begin(){
    mysql_query("BEGIN");
}

function commit(){
    mysql_query("COMMIT");
}

function rollback(){
    mysql_query("ROLLBACK");
}

mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());

mysql_select_db("bedrock") or die(mysql_error());

$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";

begin(); // transaction begins

$result = mysql_query($query);

if(!$result){
    rollback(); // transaction rolls back
    echo "transaction rolled back";
    exit;
}else{
    commit(); // transaction is committed
    echo "Database transaction was successful";
}

?>

How does System.out.print() work?

Its all about Method Overloading.

There are individual methods for each data type in println() method

If you pass object :

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

If you pass Primitive type:

corresponding primitive type method calls

if you pass String :

corresponding println(String x) method calls

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.

Actually the problem was in ApplesDO Class:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }
}

There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:

public class ApplesDO {

    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public ApplesDO(CustomType custom) {
        //constructor Code
    }

    //Introducing the dummy constructor
    public ApplesDO() {
    }

}

Simple insecure two-way data "obfuscation"?

I combined what I found the best from several answers and comments.

  • Random initialization vector prepended to crypto text (@jbtule)
  • Use TransformFinalBlock() instead of MemoryStream (@RenniePet)
  • No pre-filled keys to avoid anyone copy & pasting a disaster
  • Proper dispose and using patterns

Code:

/// <summary>
/// Simple encryption/decryption using a random initialization vector
/// and prepending it to the crypto text.
/// </summary>
/// <remarks>Based on multiple answers in http://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>
public class SimpleAes : IDisposable
{
    /// <summary>
    ///     Initialization vector length in bytes.
    /// </summary>
    private const int IvBytes = 16;

    /// <summary>
    ///     Must be exactly 16, 24 or 32 bytes long.
    /// </summary>
    private static readonly byte[] Key = Convert.FromBase64String("FILL ME WITH 24 (2 pad chars), 32 OR 44 (1 pad char) RANDOM CHARS"); // Base64 has a blowup of four-thirds (33%)

    private readonly UTF8Encoding _encoder;
    private readonly ICryptoTransform _encryptor;
    private readonly RijndaelManaged _rijndael;

    public SimpleAes()
    {
        _rijndael = new RijndaelManaged {Key = Key};
        _rijndael.GenerateIV();
        _encryptor = _rijndael.CreateEncryptor();
        _encoder = new UTF8Encoding();
    }

    public string Decrypt(string encrypted)
    {
        return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
    }

    public void Dispose()
    {
        _rijndael.Dispose();
        _encryptor.Dispose();
    }

    public string Encrypt(string unencrypted)
    {
        return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));
    }

    private byte[] Decrypt(byte[] buffer)
    {
        // IV is prepended to cryptotext
        byte[] iv = buffer.Take(IvBytes).ToArray();
        using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))
        {
            return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);
        }
    }

    private byte[] Encrypt(byte[] buffer)
    {
        // Prepend cryptotext with IV
        byte [] inputBuffer = _encryptor.TransformFinalBlock(buffer, 0, buffer.Length); 
        return _rijndael.IV.Concat(inputBuffer).ToArray();
    }
}

Update 2015-07-18: Fixed mistake in private Encrypt() method by comments of @bpsilver and @Evereq. IV was accidentally encrypted, is now prepended in clear text as expected by Decrypt().

Int to Char in C#

(char)myint;

for example:

Console.WriteLine("(char)122 is {0}", (char)122);

yields:

(char)122 is z

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

checked = "checked" vs checked = true

The original checked attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.

This, however is not valid for XHTML that followed HTML 4.

The standard proposed to use checked="checked" as a condition for true - so both ways you posted end up doing the same thing.

It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).

How to apply CSS to iframe?

I found another solution to put the style in the main html like this

<style id="iframestyle">
    html {
        color: white;
        background: black;
    }
</style>
<style>
    html {
        color: initial;
        background: initial;
    }
    iframe {
        border: none;
    }
</style>

and then in iframe do this (see the js onload)

<iframe  onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>

and in js

<script>
    ifstyle = document.getElementById('iframestyle')
    iframe = top.frames["log"];
</script>

It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a "style" tag in parent window

HTTP POST and GET using cURL in Linux

I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:

GET approach with JSON result

curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 

POST approach with JSON result

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here

SQL: Two select statements in one query

select name, games, goals
from tblMadrid where name = 'ronaldo'
union
select name, games, goals
from tblBarcelona where name = 'messi'
ORDER  BY goals 

PHP calculate age

The following works great for me and seems to be a lot simpler than the examples that have already been given.

$dob_date = "01";
$dob_month = "01";
$dob_year = "1970";
$year = gmdate("Y");
$month = gmdate("m");
$day = gmdate("d");
$age = $year-$dob_year; // $age calculates the user's age determined by only the year
if($month < $dob_month) { // this checks if the current month is before the user's month of birth
  $age = $age-1;
} else if($month == $dob_month && $day >= $dob_date) { // this checks if the current month is the same as the user's month of birth and then checks if it is the user's birthday or if it is after it
  $age = $age;
} else if($month == $dob_month && $day < $dob_date) { //this checks if the current month is the user's month of birth and checks if it before the user's birthday
  $age = $age-1;
} else {
  $age = $age;
}

I've tested and actively use this code, it might seem a little cumbersome but it is very simple to use and edit and is quite accurate.

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.

How to ping an IP address

Here is a method for pinging an IP address in Java that should work on Windows and Unix systems:

import org.apache.commons.lang3.SystemUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CommandLine
{
    /**
     * @param ipAddress The internet protocol address to ping
     * @return True if the address is responsive, false otherwise
     */
    public static boolean isReachable(String ipAddress) throws IOException
    {
        List<String> command = buildCommand(ipAddress);
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        try (BufferedReader standardOutput = new BufferedReader(new InputStreamReader(process.getInputStream())))
        {
            String outputLine;

            while ((outputLine = standardOutput.readLine()) != null)
            {
                // Picks up Windows and Unix unreachable hosts
                if (outputLine.toLowerCase().contains("destination host unreachable"))
                {
                    return false;
                }
            }
        }

        return true;
    }

    private static List<String> buildCommand(String ipAddress)
    {
        List<String> command = new ArrayList<>();
        command.add("ping");

        if (SystemUtils.IS_OS_WINDOWS)
        {
            command.add("-n");
        } else if (SystemUtils.IS_OS_UNIX)
        {
            command.add("-c");
        } else
        {
            throw new UnsupportedOperationException("Unsupported operating system");
        }

        command.add("1");
        command.add(ipAddress);

        return command;
    }
}

Make sure to add Apache Commons Lang to your dependencies.

How to update/refresh specific item in RecyclerView

Update single item

  1. Update the data item
  2. Notify the adapter of the change with notifyItemChanged(updateIndex)

Example

Change the "Sheep" item so that it says "I like sheep."

Update single item

String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

My full answer with more examples is here.

How can I increase a scrollbar's width using CSS?

This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:

::-webkit-scrollbar {
    width: 2em;
    height: 2em
}
::-webkit-scrollbar-button {
    background: #ccc
}
::-webkit-scrollbar-track-piece {
    background: #888
}
::-webkit-scrollbar-thumb {
    background: #eee
}?

JSFiddle Demo


References:

Reading in from System.in - Java

Use System.in, it is an InputStream which just serves this purpose

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Yes there is one and it is inside the SQLServer management studio. Unlike the previous versions I think. Follow these simple steps.

1)Right click on a database in the Object explorer 2)Selected New Query from the popup menu 3)Query Analyzer will be opened.

Enjoy work.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Another solution:

private void Foo()
{
   l_ExcelApp = new Excel.ApplicationClass();
   l_ExcelApp.ReferenceStyle = Excel.XlReferenceStyle.xlR1C1;
   // ... now reference by R[row]C[column], Ex. A1 <==> R1C1, C6 <==> R3C6, ...
}

see more here - Cell referencing in Excel for everyone! by Dr Nitin Paranjape

How do I get multiple subplots in matplotlib?

Go with the following if you really want to use a loop. Nobody has actually answered how to feed data in a loop:

def plot(data):
    fig = plt.figure(figsize=(100, 100))
    for idx, k in enumerate(data.keys(), 1):
        x, y = data[k].keys(), data[k].values
        plt.subplot(63, 10, idx)
        plt.bar(x, y)  
    plt.show()

"Parameter not valid" exception loading System.Drawing.Image

I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:

using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
    try
    {
        using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
        {
            try
            {
                bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                GC.Collect();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    catch (ArgumentException aex)
    {
        throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
    }
}

The following line was causing an error:

Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)

The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it. The fix was to control/ validate the image for a valid jpeg image.

Hope it helps!

How to read fetch(PDO::FETCH_ASSOC);

PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.

The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:

Array
(
    [email] => '[email protected]'
    [password] => 'yourpassword'
)

To read data from the 'email' column, do:

$user['email'];

and for 'password':

$user['password'];

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

If you've just killed a big query, it will take time to rollback. If you issue another query before the killed query is done rolling back, you might get a lock timeout error. That's what happened to me. The solution was just to wait a bit.

Details:

I had issued a DELETE query to remove about 900,000 out of about 1 million rows.

I ran this by mistake (removes only 10% of the rows): DELETE FROM table WHERE MOD(id,10) = 0

Instead of this (removes 90% of the rows): DELETE FROM table WHERE MOD(id,10) != 0

I wanted to remove 90% of the rows, not 10%. So I killed the process in the MySQL command line, knowing that it would roll back all the rows it had deleted so far.

Then I ran the correct command immediately, and got a lock timeout exceeded error soon after. I realized that the lock might actually be the rollback of the killed query still happening in the background. So I waited a few seconds and re-ran the query.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

filtering NSArray into a new NSArray in Objective-C

Another category method you could use:

- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {
    NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                                       return block(obj);
                                   }];

    return [self objectsAtIndexes:filteredIndexes];
}

How to convert a structure to a byte array in C#?

If you really want it to be FAST on Windows, you can do it using unsafe code with CopyMemory. CopyMemory is about 5x faster (e.g. 800MB of data takes 3s to copy via marshalling, while only taking .6s to copy via CopyMemory). This method does limit you to using only data which is actually stored in the struct blob itself, e.g. numbers, or fixed length byte arrays.

    [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
    private static unsafe extern void CopyMemory(void *dest, void *src, int count);

    private static unsafe byte[] Serialize(TestStruct[] index)
    {
        var buffer = new byte[Marshal.SizeOf(typeof(TestStruct)) * index.Length];
        fixed (void* d = &buffer[0])
        {
            fixed (void* s = &index[0])
            {
                CopyMemory(d, s, buffer.Length);
            }
        }

        return buffer;
    }

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

this configuration in app.js worked fine for me :

    //production mode
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
  app.get("*", (req, res) => {
    res.sendFile(path.join((__dirname + "/client/build/index.html")));

  });
}

//build mode
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname + "/client/public/index.html"));

});

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

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

Apply these two things.

  1. You need to set the character set of your database to be utf8.

  2. You need to call the mysql_set_charset('utf8') in the file where you made the connection with the database and right after the selection of database like mysql_select_db use the mysql_set_charset. That will allow you to add and retrieve data properly in whatever the language.

How to check programmatically if an application is installed or not in Android?

This code checks to make sure the app is installed, but also checks to make sure it's enabled.

private boolean isAppInstalled(String packageName) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        return pm.getApplicationInfo(packageName, 0).enabled;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

Sizing elements to percentage of screen width/height

Code :

MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

How to Use Order By for Multiple Columns in Laravel 4?

Simply invoke orderBy() as many times as you need it. For instance:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

Produces the following query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Building on @Prasath's answer. This is how you do it in Swift:

if application.respondsToSelector("isRegisteredForRemoteNotifications")
{
    // iOS 8 Notifications
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
    application.registerForRemoteNotifications()
}
else
{
    // iOS < 8 Notifications
    application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
}

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

Get File Path (ends with folder)

Use Application.GetSaveAsFilename() in the same way that you used Application.GetOpenFilename()

mingw-w64 threads: posix vs win32

Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.

Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:

As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the CreateThread function will not setup the stack correctly for the C runtime library. You should use _beginthreadex instead, which is (almost) completely compatible with CreateThread.

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

Anaconda vs. miniconda

Anaconda or Miniconda?

Choose Anaconda if you:

  1. Are new to conda or Python.

  2. Like the convenience of having Python and over 1,500 scientific packages automatically installed at once.

  3. Have the time and disk space---a few minutes and 3 GB.

  4. Do not want to individually install each of the packages you want to use.

Choose Miniconda if you:

  1. Do not mind installing each of the packages you want to use individually.

  2. Do not have time or disk space to install over 1,500 packages at once.

  3. Want fast access to Python and the conda commands and you wish to sort out the other programs later.

Source

Can we pass parameters to a view in SQL?

Simply use this view into stored procedure with required parameter/s (eg. in SQL Server) and parameter values in querying view.

Create stored procedure with View/ table: _spCallViewWithParameters

enter image description here

Execute procedure:

enter image description here

combining two data frames of different lengths

Just my 2 cents. This code combines two matrices or data.frames into one. If one data structure have lower number of rows then missing rows will be added with NA values.

combine.df <- function(x, y) {
    rows.x <- nrow(x)
    rows.y <- nrow(y)
    if (rows.x > rows.y) {
        diff <- rows.x - rows.y
        df.na <- matrix(NA, diff, ncol(y))
        colnames(df.na) <- colnames(y)
        cbind(x, rbind(y, df.na))
    } else {
        diff <- rows.y - rows.x
        df.na <- matrix(NA, diff, ncol(x))
        colnames(df.na) <- colnames(x)
        cbind(rbind(x, df.na), y)
    }
}

df1 <- data.frame(1:10, row.names = 1:10)
df2 <- data.frame(1:5, row.names = 10:14)
combine.df(df1, df2)

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

Call to a member function fetch_assoc() on boolean in <path>

OK, i just fixed this error.

This happens when there is an error in query or table doesn't exist.

Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How to Code Double Quotes via HTML Codes

Google recommend that you don't use any of them, source.

There is no need to use entity references like &mdash, &rdquo, or &#x263a, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

Is there a reason you can't simply use "?

Search for an item in a Lua list

Sort of solution using metatable...

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end

Java: how to convert HashMap<String, Object> to array

HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

try this

open the build.gradle file

  android {
        dexOptions {
           javaMaxHeapSize = "4g"
        }
   }

Create WordPress Page that redirects to another URL

There are 3 ways of doing this:

  1. By changing your 404.php code.
  2. By using wordpress plugins.
  3. By editing your .htaccess file.

Complete tutorial given at http://bornvirtual.com/wordpress/redirect-404-error-in-wordpress/906/

What is a NullReferenceException, and how do I fix it?

Update C#8.0, 2019: Nullable reference types

C#8.0 introduces nullable reference types and non-nullable reference types. So only nullable reference types must be checked to avoid a NullReferenceException.


If you have not initialized a reference type, and you want to set or read one of its properties, it will throw a NullReferenceException.

Example:

Person p = null;
p.Name = "Harry"; // NullReferenceException occurs here.

You can simply avoid this by checking if the variable is not null:

Person p = null;
if (p!=null)
{
    p.Name = "Harry"; // Not going to run to this point
}

To fully understand why a NullReferenceException is thrown, it is important to know the difference between value types and [reference types][3].

So, if you're dealing with value types, NullReferenceExceptions can not occur. Though you need to keep alert when dealing with reference types!

Only reference types, as the name is suggesting, can hold references or point literally to nothing (or 'null'). Whereas value types always contain a value.

Reference types (these ones must be checked):

  • dynamic
  • object
  • string

Value types (you can simply ignore these ones):

  • Numeric types
  • Integral types
  • Floating-point types
  • decimal
  • bool
  • User defined structs

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

Edit Crystal report file without Crystal Report software

This may be a long shot, but Crystal Reports for Eclipse is free. I'm not sure if it will work, but if all you need is to edit some static text, you could get that version of CR and get the job done.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

Just correct Google play services dependencies:

You are including all play services in your project. Only add those you want.

For example , if you are using only maps and g+ signin, than change

 compile 'com.google.android.gms:play-services:8.1.0'

to

compile 'com.google.android.gms:play-services-maps:8.1.0'
compile 'com.google.android.gms:play-services-plus:8.1.0'

From the doc :

In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.

From version 6.5, you can instead selectively compile Google Play service APIs into your app. For example, to include only the Google Fit and Android Wear APIs, replace the following line in your build.gradle file:
compile 'com.google.android.gms:play-services:8.3.0'
with these lines:

compile 'com.google.android.gms:play-services-fitness:8.3.0'
compile 'com.google.android.gms:play-services-wearable:8.3.0'

Whole list can be found here.

Is there a way to get rid of accents and convert a whole string to regular letters?

@David Conrad solution is the fastest I tried using the Normalizer, but it does have a bug. It basically strips characters which are not accents, for example Chinese characters and other letters like æ, are all stripped. The characters that we want to strip are non spacing marks, characters which don't take up extra width in the final string. These zero width characters basically end up combined in some other character. If you can see them isolated as a character, for example like this `, my guess is that it's combined with the space character.

public static String flattenToAscii(String string) {
    char[] out = new char[string.length()];
    String norm = Normalizer.normalize(string, Normalizer.Form.NFD);

    int j = 0;
    for (int i = 0, n = norm.length(); i < n; ++i) {
        char c = norm.charAt(i);
        int type = Character.getType(c);

        //Log.d(TAG,""+c);
        //by Ricardo, modified the character check for accents, ref: http://stackoverflow.com/a/5697575/689223
        if (type != Character.NON_SPACING_MARK){
            out[j] = c;
            j++;
        }
    }
    //Log.d(TAG,"normalized string:"+norm+"/"+new String(out));
    return new String(out);
}

How to change Screen buffer size in Windows Command Prompt from batch script

As a workaround, you may use...

Windows Powershell ISE

As the Powershell script editor does not seems to have a buffer limitation in its read-eval-print-loop part (the "blue" part). And with Powershell you may execute DOS commands as well.

PS. I understand this answer is a bit aside the original question, however I believe it is good to mention as it is a good workaround.

How to escape double quotes in JSON

if you want to escape double quote in JSON use \\ to escape it.

example if you want to create json of following javascript object

{time: '7 "o" clock'}

then you must write in following way

'{"time":"7 \\"o\\" clock"}'

if we parse it using JSON.parse()

JSON.parse('{"time":"7 \\"o\\" clock"}')

result will be

{time: "7 "o" clock"}

How to ensure that there is a delay before a service is started in systemd?

You can run the sleep command before your ExecStart with ExecStartPre :

[Service]
ExecStartPre=/bin/sleep 30

Get type of all variables

> mtcars %>% 
+     summarise_all(typeof) %>% 
+     gather
    key  value
1   mpg double
2   cyl double
3  disp double
4    hp double
5  drat double
6    wt double
7  qsec double
8    vs double
9    am double
10 gear double
11 carb double

I try class and typeof functions, but all fails.

Google Maps API v2: How to make markers clickable?

I added a mMap.setOnMarkerClickListener(this); in the onMapReady(GoogleMap googleMap) method. So every time you click a marker it displays the text name in the toast method.

public class DemoMapActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    double lat=0.34924212701428;
    double lng=32.616554024713;
    String venue = "Capital Shoppers City";
    LatLng location = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(location).title(venue)).setTag(0);
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(location);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
    mMap.moveCamera(cameraUpdate);
    mMap.animateCamera(zoom);
    mMap.setOnMarkerClickListener(this);
}

@Override
public boolean onMarkerClick(final Marker marker) {
    // Retrieve the data from the marker.
    Integer clickCount = (Integer) marker.getTag();

    // Check if a click count was set, then display the click count.
    if (clickCount != null) {
        clickCount = clickCount + 1;
        marker.setTag(clickCount);
        Toast.makeText(this,
                       marker.getTitle() +
                       " has been clicked ",
                       Toast.LENGTH_SHORT).show();
    }
    // Return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

}

You can check this link for reference Markers

How do I delete an entity from symfony2

DELETE FROM ... WHERE id=...;

protected function templateRemove($id){
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));

            if ($entity != null){
                $em->remove($entity);
                $em->flush();
            }
        }

How to remove empty lines with or without whitespace in Python

I use this solution to delete empty lines and join everything together as one line:

match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above

Android : Capturing HTTP Requests with non-rooted android device

I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above

https://play.google.com/store/apps/details?id=org.sandroproxy.drony

It intercepts the requests and are shown on a LOG

How to set a variable to be "Today's" date in Python/Pandas

pd.datetime.now().strftime("%d/%m/%Y")

this will give output as '11/02/2019'

you can use add time if you want

pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")

this will give output as '11/02/2019 11:08:26'

strftime formats

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I have just faced with similar issue building LLVM 3.7 version. first check whether you have installed the required library on your system:

$locate libstdc++.so.6.*

Then add the found location to your $LD_LIBRARY_PATH environment variable.

Easy way to print Perl array? (with a little formatting)

Map can also be used, but sometimes hard to read when you have lots of things going on.

map{ print "element $_\n" }   @array; 

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.

Creating a BAT file for python script

c:\python27\python.exe c:\somescript.py %*

How to convert from Hex to ASCII in JavaScript?

** for Hexa to String**

let input  = '32343630';

Note : let output = new Buffer(input, 'hex'); // this is deprecated

let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");