Programs & Examples On #Lts

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Completely Remove MySQL Ubuntu 14.04 LTS

remove mysql :

sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

Restart instance :

sudo shutdown -r now

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Use Pre-request script tab to write javascript to get and save the date into a variable:

const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());

and then use it in the request body as follows:

"currentDate": "{{currentDate}}"

How to read XML using XPath in Java

Getting started example:

xml file:

<inventory>
    <book year="2000">
        <title>Snow Crash</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553380958</isbn>
        <price>14.95</price>
    </book>

    <book year="2005">
        <title>Burning Tower</title>
        <author>Larry Niven</author>
        <author>Jerry Pournelle</author>
        <publisher>Pocket</publisher>
        <isbn>0743416910</isbn>
        <price>5.99</price>
    </book>

    <book year="1995">
        <title>Zodiac</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553573862</isbn>
        <price>7.50</price>
    </book>

    <!-- more books... -->

</inventory>

Java code:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));

    // normalize text representation
    doc.getDocumentElement().normalize();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

    NodeList listOfBooks = doc.getElementsByTagName("book");
    int totalBooks = listOfBooks.getLength();
    System.out.println("Total no of books : " + totalBooks);

    for(int i=0; i<listOfBooks.getLength() ; i++) {

        Node firstBookNode = listOfBooks.item(i);
        if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {

            Element firstElement = (Element)firstBookNode;                              
            System.out.println("Year :"+firstElement.getAttribute("year"));

            //-------
            NodeList firstNameList = firstElement.getElementsByTagName("title");
            Element firstNameElement = (Element)firstNameList.item(0);

            NodeList textFNList = firstNameElement.getChildNodes();
            System.out.println("title : " + ((Node)textFNList.item(0)).getNodeValue().trim());
        }
    }//end of for loop with s var
} catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
} catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
} catch (Throwable t) {
    t.printStackTrace ();
}                

Multiple submit buttons in an HTML form

Another simple option would be to put the back button after the submit button in the HTML code, but float it to the left, so it appears on the page before the submit button.

Changing the tab order should be all it takes to accomplish this. Keep it simple.

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

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

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

How to initialize private static members in C++?

Since C++17, static members may be defined in the header with the inline keyword.

http://en.cppreference.com/w/cpp/language/static

"A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify a default member initializer. It does not need an out-of-class definition:"

struct X
{
    inline static int n = 1;
};

How do I make an auto increment integer field in Django?

In Django

1 : we have default field with name "id" which is auto increment.
2 : You can define a auto increment field using AutoField field.

class Order(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    #you use primary_key = True if you do not want to use default field "id" given by django to your model

db design

+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`auto_increment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

If you want to use django's default id as increment field .

class Order(models.Model):
    dd_date = models.DateTimeField(auto_now_add=True)

db design

+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dd_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

How do I increase the capacity of the Eclipse output console?

Under Window > Preferences, go to the Run/Debug > Console section, then you should see an option "Limit console output." You can uncheck this or change the number in the "Console buffer size (characters)" text box below.

(This is in Galileo, Helios CDT, Kepler, Juno, Luna, Mars, Neon, Oxygen and 2018-09)

Make Div overlay ENTIRE page (not just viewport)?

I had quite a bit of trouble as I didn't want to FIX the overlay in place as I wanted the info inside the overlay to be scrollable over the text. I used:

<html style="height=100%">
   <body style="position:relative">
      <div id="my-awesome-overlay" 
           style="position:absolute; 
                  height:100%; 
                  width:100%; 
                  display: block">
           [epic content here]
      </div>
   </body>
</html>

Of course the div in the middle needs some content and probably a transparent grey background but I'm sure you get the gist!

How to do this using jQuery - document.getElementById("selectlist").value

"Equivalent" is the word here

While...

$('#selectlist').val();

...is equivalent to...

document.getElementById("selectlist").value

...it's worth noting that...

$('#selectlist')

...although 'equivalent' is not the same as...

document.getElementById("selectlist")

...as the former returns a jQuery object, not a DOM object.

To get the DOM object(s) from the jQuery one, use the following:

$('#selectlist').get(); //get all DOM objects in the jQuery collection
$('#selectlist').get(0); //get the DOM object in the jQuery collection at index 0
$('#selectlist')[0]; //get the DOM objects in the jQuery collection at index 0

How create a new deep copy (clone) of a List<T>?

Well,

If you mark all involved classes as serializable you can :

public static List<T> CloneList<T>(List<T> oldList)  
{  
BinaryFormatter formatter = new BinaryFormatter();  
MemoryStream stream = new MemoryStream();  
formatter.Serialize(stream, oldList);  
stream.Position = 0;  
return (List<T>)formatter.Deserialize(stream);      
} 

Source:

https://social.msdn.microsoft.com/Forums/en-US/5c9b4c31-850d-41c4-8ea3-fae734b348c4/copy-listsomeobject-to-clone-list?forum=csharpgeneral

Display Bootstrap Modal using javascript onClick

I had the same problem, after researching a lot, I finally built a js function to create modals dynamically based on my requirements. Using this function, you can create popups in one line such as:

puyModal({title:'Test Title',heading:'Heading',message:'This is sample message.'})

Or you can use other complex functionality such as iframes, video popups, etc.

Find it on https://github.com/aybhalala/puymodals For demo, go to http://pateladitya.com/puymodals/

Check play state of AVPlayer

In iOS10, there's a built in property for this now: timeControlStatus

For example, this function plays or pauses the avPlayer based on it's status and updates the play/pause button appropriately.

@IBAction func btnPlayPauseTap(_ sender: Any) {
    if aPlayer.timeControlStatus == .playing {
        aPlayer.pause()
        btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
    } else if aPlayer.timeControlStatus == .paused {
        aPlayer.play()
        btnPlay.setImage(UIImage(named: "control-pause"), for: .normal)
    }
}

As for your second question, to know if the avPlayer reached the end, the easiest thing to do would be to set up a notification.

NotificationCenter.default.addObserver(self, selector: #selector(self.didPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)

When it gets to the end, for example, you can have it rewind to the beginning of the video and reset the Pause button to Play.

@objc func didPlayToEnd() {
    aPlayer.seek(to: CMTimeMakeWithSeconds(0, 1))
    btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
}

These examples are useful if you're creating your own controls, but if you use a AVPlayerViewController, then the controls come built in.

mongod command not recognized when trying to connect to a mongodb server

Seems like, The environmental variable is not correctly set up.

Go to the mongodb installation folder and get the executable files (mongo.exe, mongod.exe etc) location. (In my case) Something like :

C:\Program Files\MongoDB\Server\3.2\bin

Then go to :

Panel > System & Security > System > Advanced System Settings > Environment Variables 

Find the PATH variable and edit its value. Then add C:\Program Files\MongoDB\Server\3.2\bin and don't forget to separate each values with ;. Now confirm and exit.

Question mark characters displaying within text, why is this?

Unicode or other character set characters falling through?

I have seen similar "strange" characters show up on sites I have worked on often when the text is copied from an email or some other document format (e.g. word) into a text editor. The editor can display the non ASCII characters but the browser can't. For the website, I would suggest looking up the HTML entity code for the character and inserting that instead ... or switch to more standard ones.

How to make a owl carousel with arrows instead of next previous

The following code works for me on owl carousel .

https://github.com/OwlFonk/OwlCarousel

$(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    navigation: true,
    navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

For OwlCarousel2

https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

 $(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    nav: true,
    navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

Regular Expressions: Is there an AND operator?

You need to use lookahead as some of the other responders have said, but the lookahead has to account for other characters between its target word and the current match position. For example:

(?=.*word1)(?=.*word2)(?=.*word3)

The .* in the first lookahead lets it match however many characters it needs to before it gets to "word1". Then the match position is reset and the second lookahead seeks out "word2". Reset again, and the final part matches "word3"; since it's the last word you're checking for, it isn't necessary that it be in a lookahead, but it doesn't hurt.

In order to match a whole paragraph, you need to anchor the regex at both ends and add a final .* to consume the remaining characters. Using Perl-style notation, that would be:

/^(?=.*word1)(?=.*word2)(?=.*word3).*$/m

The 'm' modifier is for multline mode; it lets the ^ and $ match at paragraph boundaries ("line boundaries" in regex-speak). It's essential in this case that you not use the 's' modifier, which lets the dot metacharacter match newlines as well as all other characters.

Finally, you want to make sure you're matching whole words and not just fragments of longer words, so you need to add word boundaries:

/^(?=.*\bword1\b)(?=.*\bword2\b)(?=.*\bword3\b).*$/m

mysqldump exports only one table

In case you encounter an error like this

mysqldump: 1044 Access denied when using LOCK TABLES

A quick workaround is to pass the –-single-transaction option to mysqldump.

So your command will be like this.

mysqldump --single-transaction -u user -p DBNAME > backup.sql

Assign a login to a user created without login (SQL Server)

I found that this question was still relevant but not clearly answered in my case.

Using SQL Server 2012 with an orphaned SQL_USER this was the fix;

USE databasename                      -- The database I had recently attached
EXEC sp_change_users_login 'Report'   -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

How to create a file name with the current date & time in Python?

import datetime

def print_time():
    parser = datetime.datetime.now() 
    return parser.strftime("%d-%m-%Y %H:%M:%S")

print(print_time())

# Output>
# 03-02-2021 22:39:28

What does on_delete do on Django models?

Reorient your mental model of the functionality of "CASCADE" by thinking of adding a FK to an already existing cascade (i.e. a waterfall). The source of this waterfall is a primary key (PK). Deletes flow down.

So if you define a FK's on_delete as "CASCADE," you're adding this FK's record to a cascade of deletes originating from the PK. The FK's record may participate in this cascade or not ("SET_NULL"). In fact, a record with a FK may even prevent the flow of the deletes! Build a dam with "PROTECT."

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.

Use the subplots_adjust() function to move the bottom of the subplot up:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

Then play with the offset in the legend bbox_to_anchor part of the legend command, to get the legend box where you want it. Some combination of setting the figsize and using the subplots_adjust(bottom=...) should produce a quality plot for you.

Alternative: I simply changed the line:

fig = plt.figure(1)

to:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

and changed

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

to

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

and it shows up fine on my screen (a 24-inch CRT monitor).

Here figsize=(M,N) sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport option when including graphics.

Adding a newline into a string in C#

The previous answers come close, but to meet the actual requirement that the @ symbol stay close, you'd want that to be str.Replace("@", "@" + System.Environment.NewLine). That will keep the @ symbol and add the appropriate newline character(s) for the current platform.

how to set radio option checked onload with jQuery

Don't need all that. With simple and old HTML you can achieve what you want. If you let the radio you want checked by default like this:
<input type='radio' name='gender' checked='true' value='Male'>
When page loads, it'll come checked.

Process to convert simple Python script into Windows executable

i would recommend going to http://sourceforge.net/projects/py2exe/files/latest/download?source=files to download py2exe. Then make a python file named setup.py. Inside it, type

from distutils.core import setup
import py2exe
setup(console=['nameoffile.py'])

Save in your user folder Also save the file you want converted in that same folder

Run window's command prompt type in setup.py install py2exe

It should print many lines of code...

Next, open the dist folder.

Run the exe file.

If there are needed files for the program to work, move them to the folder

Copy/Send the dist folder to person.

Optional: Change the name of the dist folder

Hope it works!:)

Could not find a version that satisfies the requirement <package>

Try installing flask through the powershell using the following command.

pip install --isolated Flask

This will allow installation to avoide environment variables and user configuration.

Java double comparison epsilon

If you are dealing with money I suggest checking the Money design pattern (originally from Martin Fowler's book on enterprise architectural design).

I suggest reading this link for the motivation: http://wiki.moredesignpatterns.com/space/Value+Object+Motivation+v2

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

On Windows (msys) using Docker Toolbox/Machine, I had to add an extra / before /bin/bash to indicate that it was a *nix filepath.

So, docker run --rm -it <image>:latest //bin/bash

jQuery Scroll to bottom of page/iframe

scrollTop() returns the number of pixels that are hidden from view from the scrollable area, so giving it:

$(document).height()

will actually overshoot the bottom of the page. For the scroll to actually 'stop' at the bottom of the page, the current height of the browser window needs subtracting. This will allow the use of easing if required, so it becomes:

$('html, body').animate({ 
   scrollTop: $(document).height()-$(window).height()}, 
   1400, 
   "easeOutQuint"
);

How to check if user input is not an int value

Simply throw Exception if input is invalid

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

How to Toggle a div's visibility by using a button click

jQuery would be the easiest way if you want to use it, but this should work.

function showHide(){
    var e = document.getElementById('e');

    if ( e.style.display !== 'none' ) {
        e.style.display = 'none';
    } else {
        e.style.display = '';
    }
}

Debugging in Maven?

I found an easy way to do this -

Just enter a command like this -

>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test

It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.

Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to check whether java is installed on the computer

Using Apache Commons-Lang's SystemUtils.isJavaVersionAtLeast(JavaVersion)

import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;

if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)
    System.out.println("Java version was 8 or greater!");

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

How do I check to see if a value is an integer in MySQL?

This also works:

CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.

for example

SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

Get and set position with jQuery .offset()

Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You code should be:

   <section id="right">
      <label for="form_msg">Message</label>
      <textarea name="form_msg" id="#msg_text"></textarea>
      <input id="submit" class="button" name="submit" type="submit" value="Send">
   </section>

Js

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

The PHP:

<?php
if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]","My Subject:",$email,$message);
}
?>

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    }
    return self;
}

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];

}

- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

Code shamelessly borrowed from: saving class in nsuserdefaults

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

how to empty recyclebin through command prompt?

You can use a powershell script (this works for users with folder redirection as well to not have their recycle bins take up server storage space)

$Shell = New-Object -ComObject Shell.Application
$RecBin = $Shell.Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}

The above script is taken from here.

If you have windows 10 and powershell 5 there is the Clear-RecycleBin commandlet.

To use Clear-RecycleBin inside PowerShell without confirmation, you can use Clear-RecycleBin -Force. Official documentation can be found here

Run a batch file with Windows task scheduler

Try run the task with high privileges.

put a \ at the end of path in "start in folder" such as c:\temp\

I do not know why , but this works for me sometimes.

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

How to sort an array of objects with jquery or javascript

Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->

var array = [ [id,name,value], [id,name,value] ]

Hopefully that helps!

Table is marked as crashed and should be repaired

Connect to your server via SSH

then connect to your mysql console

and

USE user_base
REPAIR TABLE TABLE;

-OR-

If there are a lot of broken tables in current database:

mysqlcheck -uUSER -pPASSWORD  --repair --extended user_base

If there are a lot of broken tables in a lot of databases:

mysqlcheck -uUSER -pPASSWORD  --repair --extended -A

How do you get the index of the current iteration of a foreach loop?

I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.

string[] names = { "one", "two", "three" };
var oddOrEvenByName = names
    .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.

Close Android Application

If you close the main Activity using Activity.finish(), I think it will close all the activities. MAybe you can override the default function, and implement it in a static way, I'm not sure

Android: Clear the back stack

Either add this to your Activity B and Activity C

android:noHistory="true"

or Override onBackPressed function to avoid back pressing with a return.

@Override
public void onBackPressed() {
   return;
}

No module named serial

You do not have serial package installed.

Try pip install serial to install the module.

Alternatively, install it in binary form from here:

Install Pyserial for Windows

Note that you always install precompiled binaries at your own risk.

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
    
  2. By whitespace:

     s.split_whitespace()
    
  3. By newlines:

     s.lines()
    
  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")
    

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

Round up to Second Decimal Place in Python

Updated answer:
The problem with my original answer, as pointed out in the comments by @jpm, is the behavior at the boundaries. Python 3 makes this even more difficult since it uses "bankers" rounding instead of "old school" rounding. However, in looking into this issue I discovered an even better solution using the decimal library.

import decimal

def round_up(x, place=0):
    context = decimal.getcontext()
    # get the original setting so we can put it back when we're done
    original_rounding = context.rounding
    # change context to act like ceil()
    context.rounding = decimal.ROUND_CEILING

    rounded = round(decimal.Decimal(str(x)), place)
    context.rounding = original_rounding
    return float(rounded)

Or if you really just want a one-liner:

import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING

# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12

# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11

Here are some examples:

round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112

round_up(3.4)
>> 4.0

# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1

# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04

We can use it to round to the left of the decimal as well:

round_up(11, -1)
>> 20

We don't multiply by 10, thereby avoiding the overflow mentioned in this answer.

round_up(1.01e308, -307)
>> 1.1e+308

Original Answer (Not recommended):
This depends on the behavior you want when considering positive and negative numbers, but if you want something that always rounds to a larger value (e.g. 2.0449 -> 2.05, -2.0449 -> -2.04) then you can do:

round(x + 0.005, 2)

or a little fancier:

def round_up(x, place):
    return round(x + 5 * 10**(-1 * (place + 1)), place)

This also seems to work as follows:

round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308

Format numbers in thousands (K) in Excel

I've found the following combination that works fine for positive and negative numbers (43787200020 is transformed to 43.787.200,02 K)

[>=1000] #.##0,#0. "K";#.##0,#0. "K"

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Sharing the solution which worked for me, which may help someone

Issue when compiling for simulator:

building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

XCODE 12.1, POD 1.9.1

My Project structure

  • Main Target
  • Share Extension
  • Notifiction service extension
  • Submodule, Custom Framework
  • Podfile
  1. Add arm64 to Build settings -> Exclude Architecture in all the targets.

enter image description here

  1. Removed arm64 from VALID_ARCHS and added x86_64 in all the targets.

enter image description here

  1. Add following code in podfile

    post_install do |installer|
        installer.pods_project.build_configurations.each do |config|
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
     end
    end
    
  2. Did pod update, deleted podfile.lock, and did pod install

  3. Do clean build.

Force file download with php using header()

The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.

I used this other Stackoverflow Q&A material instead, it worked great for me:

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

How to start up spring-boot application via command line?

You will need to build the jar file first. Here is the syntax to run the main class from a jar file.

java -jar path/to/your/jarfile.jar fully.qualified.package.Application 

css h1 - only as wide as the text

.h1 {
  width: -moz-fit-content;
  width: fit-content;

  // workaround for IE11
  display: table;
}

All modern browsers support width: fit-content for that.

For IE11 we could emulate this behavior with display: table which doesn't break margin collapse like display: inline-block or float: left.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Show a child form in the centre of Parent form in C#

If you want to calculate your own location, then first set StartPosition to FormStartPosition.Manual:

Form Child = new Form();
Child.StartPosition = FormStartPosition.Manual;
Child.Location = new Point(Location.X + (Width - Child.Width) / 2, Location.Y + (Height - Child.Height) / 2);
Child.Show(this);

Where this is the main/parent form, just like Location.X.

Default value for StartPosition is FormStartPosition.CenterParent and therefore it changes the child's location after showing.

Database corruption with MariaDB : Table doesn't exist in engine

I've just had this problem with MariaDB/InnoDB and was able to fix it by

  • create the required table in the correct database in another MySQL/MariaDB instance
  • stop both servers
  • copy .ibd, .frm files to original server
  • start both servers
  • drop problem table on both servers

Git: How to remove remote origin from Git repo

You can rename (changing URL of a remote repository) using :

git remote set-url origin new_URL

new_URL can be like https://github.com/abcdefgh/abcd.git

Too permanently delete the remote repository use :

git remote remove origin

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

using if else with eval in aspx page

 <%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
                        &nbsp;[<%=System.Environment.MachineName%>]
                        <%}%>

How can I hide an HTML table row <tr> so that it takes up no space?

Thought I'd add to this a potential other solution:

<tr style='visibility:collapse'><td>stuff</td></tr>

I've only tested it on Chrome but putting this on the <tr> hides the row PLUS all the cells inside the row still contribute to the widths of the columns. I will sometimes make an extra row at the bottom of a table with just some spacers that make it so certain columns can't be less than a certain width, then hide the row using this method. (I know you're supposed to be able to do this with other css but I've never gotten that to work)

Again, I'm in a purely chrome environment so I have no idea how this functions in other browsers.

Why does JSHint throw a warning if I am using const?

I got this same warning when using an export statement. I'm using VS Code and used a similar approach to Wenlong Jiang's solution.

  1. User Settings

  2. JSHint config

  3. "jshint.config": {} (Edit)

  4. Use double quotes when specifying "esversion"

    Or copy this snippet into User Settings:

    "jshint.options": {
      "esversion": 6,
    }
    

Creating a .jshintrc file isn't necessary if you want to configure the global jshint settings for your editor

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

Reading file using fscanf() in C

scanf() and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main(void)
{
    char item[9], status;

    FILE *fp;

    if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        printf("No such file\n");
        exit(1);
    }

    while (true) {
        int ret = fscanf(fp, "%s %c", item, &status);
        if(ret == 2)
            printf("\n%s \t %c", item, status);
        else if(errno != 0) {
            perror("scanf:");
            break;
        } else if(ret == EOF) {
            break;
        } else {
            printf("No match.\n");
        }
    }
    printf("\n");
    if(feof(fp)) {
        puts("EOF");
    }
    return 0;
}

Jinja2 template variable if None Object set a default value

Use the none test (not to be confused with Python's None object!):

{% if p is not none %}   
    {{ p.User['first_name'] }}
{% else %}
    NONE
{% endif %}

or:

{{ p.User['first_name'] if p is not none else 'NONE' }}

or if you need an empty string:

{{ p.User['first_name'] if p is not none }}

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

Auto Generate Database Diagram MySQL

I believe DB Designer does something like that. And I think they even have a free version.

edit Never mind. Michael's link is much better.

Using switch statement with a range of value in each case?

other alternative is using math operation by dividing it, for example:

switch ((int) num/10) {
    case 1:
        System.out.println("10-19");
        break;
    case 2:
        System.out.println("20-29");
        break;
    case 3:
        System.out.println("30-39");
        break;
    case 4:
        System.out.println("40-49");
        break;
    default:
        break;
}

But, as you can see this can only be used when the range is fixed in each case.

How to keep a VMWare VM's clock in sync?

VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.

The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues

ReactJS lifecycle method inside a function Component

Solution One: You can use new react HOOKS API. Currently in React v16.8.0

Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.

A Note from the Author of recompose (acdlite, Oct 25 2018):

Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.

Solution Two:

If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.

Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).

// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

function RenderlessComponent() {
  return null; 
}

export default lifecycle({

  componentDidMount() {
    const { checkIfAuthed } = this.props;
    // Do they have an active session? ("Remember me")
    checkIfAuthed();
  },

  componentWillReceiveProps(nextProps) {
    const {
      loadUser,
    } = this.props;

    // Various 'indicators'..
    const becameAuthed = (!(this.props.auth) && nextProps.auth);
    const isCurrentUser = (this.props.currentUser !== null);

    if (becameAuthed) {
      loadUser(nextProps.auth.uid);
    }

    const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
    if (shouldSetCurrentUser) {
      const currentUser = nextProps.users[nextProps.auth.uid];
      if (currentUser) {
        this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
        });
      }
    }
  }
})(RenderlessComponent);

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

How to implement onBackPressed() in Fragments?

I just use findFragmentById and cast to the fragment and call a method that handles onBackpressed. This sample shows checking if this is the first step in order process if it is pop up a dialog fragment to confirm exit order.

@Override
    public void onBackPressed() {
        //check if first fragment in wizard is loaded, if true get abandon confirmation before going back
        OrderFragment frag =(OrderFragment)getSupportFragmentManager().findFragmentById(R.id.fragContainer);
        if (frag==null || (frag!=null && frag.getOrderStage()<1)){
            AlertDialogFragment.show(getSupportFragmentManager(), R.string.dialog_cancel_order,R.string.dialog_cancel_order_msg, R.string.dialog_cancel_order_pos,R.string.dialog_order_quiz_neg, DIALOG_ID_CANCEL);
        }else {
            super.onBackPressed();
        }
    }

useState set method not reflecting change immediately

// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;

Now you should see, that your code actually does work. What does not work is the console.log(movies). This is because movies points to the old state. If you move your console.log(movies) outside of useEffect, right above the return, you will see the updated movies object.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Try writing the following batch file and executing it:

Echo one
cmd
Echo two
cmd
Echo three
cmd

Only the first two lines get executed. But if you type "exit" at the command prompt, the next two lines are processed. It's a shell loading another.

To be sure that this is not what is happening in your script, just type "exit" when the first command ends.

HTH!

How to initialize const member variable in a class?

This is the right way to do. You can try this code.

#include <iostream>

using namespace std;

class T1 {
    const int t;

    public:
        T1():t(100) {
            cout << "T1 constructor: " << t << endl;
        }
};

int main() {
    T1 obj;
    return 0;
}

if you are using C++10 Compiler or below then you can not initialize the cons member at the time of declaration. So here it is must to make constructor to initialise the const data member. It is also must to use initialiser list T1():t(100) to get memory at instant.

Default value to a parameter while passing by reference in C++

In case of OO... To say that a Given Class has and "Default" means that this Default (value) must declared acondingly an then may be usd as an Default Parameter ex:

class Pagination {
public:
    int currentPage;
    //...
    Pagination() {
        currentPage = 1;
        //...
    }
    // your Default Pagination
    static Pagination& Default() {
        static Pagination pag;
        return pag;
    }
};

On your Method ...

 shared_ptr<vector<Auditoria> > 
 findByFilter(Auditoria& audit, Pagination& pagination = Pagination::Default() ) {

This solutions is quite suitable since in this case, "Global default Pagination" is a single "reference" value. You will also have the power to change default values at runtime like an "gobal-level" configuration ex: user pagination navigation preferences and etc..

How to get the root dir of the Symfony2 application?

Since Symfony 3.3 you can use binding, like

services:
_defaults:
    autowire: true      
    autoconfigure: true
    bind:
        $kernelProjectDir: '%kernel.project_dir%'

After that you can use parameter $kernelProjectDir in any controller OR service. Just like

class SomeControllerOrService
{
    public function someAction(...., $kernelProjectDir)
    {
          .....

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

To be consistent with what is probably the most likely source of generating a time span (computing the difference of 2 times or date-times), you may want to store a .NET TimeSpan as a SQL Server DateTime Type.

This is because in SQL Server, the difference of 2 DateTime's (Cast to Float's and then Cast back to a DateTime) is simply a DateTime relative to Jan. 1, 1900. Ex. A difference of +0.1 second would be January 1, 1900 00:00:00.100 and -0.1 second would be Dec. 31, 1899 23:59:59.900.

To convert a .NET TimeSpan to a SQL Server DateTime Type, you would first convert it to a .NET DateTime Type by adding it to a DateTime of Jan. 1, 1900. Of course, when you read it into .NET from SQL Server, you would first read it into a .NET DateTime and then subtract Jan. 1, 1900 from it to convert it to a .NET TimeSpan.

For use cases where the time spans are being generated from SQL Server DateTime's and within SQL Server (i.e. via T-SQL) and SQL Server is prior to 2016, depending on your range and precision needs, it may not be practical to store them as milliseconds (not to mention Ticks) because the Int Type returned by DateDiff (vs. the BigInt from SS 2016+'s DateDiff_Big) overflows after ~24 days worth of milliseconds and ~67 yrs. of seconds. Whereas, this solution will handle time spans with precision down to 0.1 seconds and from -147 to +8,099 yrs..

WARNINGS:

  1. This would only work if the difference relative to Jan. 1, 1900 would result in a value within the range of a SQL Server DateTime Type (Jan. 1, 1753 to Dec. 31, 9999 aka -147 to +8,099 yrs.). We don't have to worry near as much on the .NET TimeSpan side, since it can hold ~29 k to +29 k yrs. I didn't mention the SQL Server DateTime2 Type (whose range, on the negative side, is much greater than SQL Server DateTime's), because: a) it cannot be converted to a numeric via a simple Cast and b) DateTime's range should suffice for the vast majority of use cases.

  2. SQL Server DateTime differences computed via the Cast - to - Float - and - back method does not appear to be accurate beyond 0.1 seconds.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

In my case the sub domain name causes the problem. Here are details

I used app_development.something.com, here underscore(_) sub domain is creating CORS error. After changing app_development to app-development it works fine.

Update Angular model after setting input value with jQuery

add .change() after setting the value.

example:('id').val.('value').change();

also don't forget to add onchange or ng-change tag in html

Express.js: how to get remote client address

This worked for me better than the rest. My sites are behind CloudFlare and it seemed to require cf-connecting-ip.

req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress

Didn't test Express behind proxies as it didn't say anything about this cf-connecting-ip header.

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

Floating point comparison functions for C#

Further to Andrew Wang's answer: if the BitConverter method is too slow but you cannot use unsafe code in your project, this struct is ~6x quicker than BitConverter:

[StructLayout(LayoutKind.Explicit)]
public struct FloatToIntSafeBitConverter
{
    public static int Convert(float value)
    {
        return new FloatToIntSafeBitConverter(value).IntValue;
    }

    public FloatToIntSafeBitConverter(float floatValue): this()
    {
        FloatValue = floatValue;
    }

    [FieldOffset(0)]
    public readonly int IntValue;

    [FieldOffset(0)]
    public readonly float FloatValue;
}

(Incidentally, I tried using the accepted solution but it (well my conversion at least) failed some of the unit tests also mentioned in the answer. e.g. assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); )

How to output only captured groups with sed?

Try

sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

I got this under cygwin:

$ (echo "asdf"; \
   echo "1234"; \
   echo "asdf1234adsf1234asdf"; \
   echo "1m2m3m4m5m6m7m8m9m0m1m2m3m4m5m6m7m8m9") | \
  sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

1234
1234 1234
1 2 3 4 5 6 7 8 9
$

Remove spacing between table cells and rows

You have cellspacing="0" twice, try replacing the second one with cellpadding="0" instead.

Multiple line code example in Javadoc comment

/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/
  • <pre/> is required for preserving lines.
  • {@code must has its own line
  • <blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}


UPDATE with JDK8

The minimum requirements for proper codes are <pre/> and {@code}.

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

yields

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding <blockquote/> inserts an indentation.

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

yields

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting <p> or surrounding with <p> and </p> yields warnings.

Python SQLite: database is locked

Turned out the problem happened because the path to the db file was actually a samba mounted dir. I moved it and that started working.

Changing the page title with Jquery

using

$('title').html("new title");

How to start/stop/restart a thread in Java?

Review java.lang.Thread.

To start or restart (once a thread is stopped, you can't restart that same thread, but it doesn't matter; just create a new Thread instance):

// Create your Runnable instance
Task task = new Task(...);

// Start a thread and run your Runnable
Thread t = new Thread(task);

To stop it, have a method on your Task instance that sets a flag to tell the run method to exit; returning from run exits the thread. If your calling code needs to know the thread really has stopped before it returns, you can use join:

// Tell Task to stop
task.setStopFlag(true);

// Wait for it to do so
t.join();

Regarding restarting: Even though a Thread can't be restarted, you can reuse your Runnable instance with a new thread if it has state and such you want to keep; that comes to the same thing. Just make sure your Runnable is designed to allow multiple calls to run.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

How do I display an alert dialog on Android?

you can try this....

    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Dialog on Android");
dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //Action for "Delete".
    }
})
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //Action for "Cancel".
            }
        });

final AlertDialog alert = dialog.create();
alert.show();

For more info,check this link...

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

Auto start node.js server on boot

Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.

Elasticsearch query to return all records

http://localhost:9200/foo/_search/?size=1000&pretty=1

you will need to specify size query parameter as the default is 10

Maven package/install without test (skip tests)

Tests should always[1] run before package. If you need to turn off the tests, you're doing something wrong. In other words, you're trying to solve the wrong problem. Figure out what your problem really is, and ask that question. It sounds like it's database-related.

[1] You might skip tests when you need to quickly generate an artifact for local, development use, but in general, creating an artifact should always follow a successful test run.

how to make negative numbers into positive

floor a;
floor b;
a = -0.340515;

so what to do?

b = 65565 +a;
a = 65565 -b;

or

if(a < 0){
a = 65565-(65565+a);}

Is there a CSS selector for elements containing certain text?

I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:

td.male { color: blue; }
td.female { color: pink; }

can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:

<td class="{{person.gender}}">

Just make sure that the content is only one word! Or you could even map to different CSS class names with:

<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">

For completeness, here's the data attribute approach:

<td data-gender="{{person.gender}}">

Use of 'const' for function parameters

There's really no reason to make a value-parameter "const" as the function can only modify a copy of the variable anyway.

The reason to use "const" is if you're passing something bigger (e.g. a struct with lots of members) by reference, in which case it ensures that the function can't modify it; or rather, the compiler will complain if you try to modify it in the conventional way. It prevents it from being accidentally modified.

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Java abstract interface

Be aware that in Spring it has non academic meaning. The abstract interface is a warning to the developer not to use it for @Autowired. I hope that spring/eclipse @Autowired will look at this attribute and warn/fail about usages of such.

A real example: @Service proxy under @Transnational to a @Repository need to use same basic methods however they should use different interfaces that extends this abstract interface due to @Autowired. (I call this XXXSpec interface)

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Find and replace entire mysql database

sqldump to a text file, find/replace, re-import the sqldump.

Dump the database to a text file
mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

Restore the database after you have made changes to it.
mysql -u root -p[root_password] [database_name] < dumpfilename.sql

HTTP requests and JSON parsing in Python

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

Iterating over every two elements in a list

In case you're interested in the performance, I did a small benchmark (using my library simple_benchmark) to compare the performance of the solutions and I included a function from one of my packages: iteration_utilities.grouper

from iteration_utilities import grouper
import matplotlib as mpl
from simple_benchmark import BenchmarkBuilder

bench = BenchmarkBuilder()

@bench.add_function()
def Johnsyweb(l):
    def pairwise(iterable):
        "s -> (s0, s1), (s2, s3), (s4, s5), ..."
        a = iter(iterable)
        return zip(a, a)

    for x, y in pairwise(l):
        pass

@bench.add_function()
def Margus(data):
    for i, k in zip(data[0::2], data[1::2]):
        pass

@bench.add_function()
def pyanon(l):
    list(zip(l,l[1:]))[::2]

@bench.add_function()
def taskinoor(l):
    for i in range(0, len(l), 2):
        l[i], l[i+1]

@bench.add_function()
def mic_e(it):
    def pairwise(it):
        it = iter(it)
        while True:
            try:
                yield next(it), next(it)
            except StopIteration:
                return

    for a, b in pairwise(it):
        pass

@bench.add_function()
def MSeifert(it):
    for item1, item2 in grouper(it, 2):
        pass

bench.use_random_lists_as_arguments(sizes=[2**i for i in range(1, 20)])
benchmark_result = bench.run()
mpl.rcParams['figure.figsize'] = (8, 10)
benchmark_result.plot_both(relative_to=MSeifert)

enter image description here

So if you want the fastest solution without external dependencies you probably should just use the approach given by Johnysweb (at the time of writing it's the most upvoted and accepted answer).

If you don't mind the additional dependency then the grouper from iteration_utilities will probably be a bit faster.

Additional thoughts

Some of the approaches have some restrictions, that haven't been discussed here.

For example a few solutions only work for sequences (that is lists, strings, etc.), for example Margus/pyanon/taskinoor solutions which uses indexing while other solutions work on any iterable (that is sequences and generators, iterators) like Johnysweb/mic_e/my solutions.

Then Johnysweb also provided a solution that works for other sizes than 2 while the other answers don't (okay, the iteration_utilities.grouper also allows setting the number of elements to "group").

Then there is also the question about what should happen if there is an odd number of elements in the list. Should the remaining item be dismissed? Should the list be padded to make it even sized? Should the remaining item be returned as single? The other answer don't address this point directly, however if I haven't overlooked anything they all follow the approach that the remaining item should be dismissed (except for taskinoors answer - that will actually raise an Exception).

With grouper you can decide what you want to do:

>>> from iteration_utilities import grouper

>>> list(grouper([1, 2, 3], 2))  # as single
[(1, 2), (3,)]

>>> list(grouper([1, 2, 3], 2, truncate=True))  # ignored
[(1, 2)]

>>> list(grouper([1, 2, 3], 2, fillvalue=None))  # padded
[(1, 2), (3, None)]

How can I get a precise time, for example in milliseconds in Objective-C?

I would NOT use mach_absolute_time() because it queries a combination of the kernel and the processor for an absolute time using ticks (probably an uptime).

What I would use:

CFAbsoluteTimeGetCurrent();

This function is optimized to correct the difference in the iOS and OSX software and hardware.

Something Geekier

The quotient of a difference in mach_absolute_time() and AFAbsoluteTimeGetCurrent() is always around 24000011.154871

Here is a log of my app:

Please note that final result time is a difference in CFAbsoluteTimeGetCurrent()'s

 2012-03-19 21:46:35.609 Rest Counter[3776:707] First Time: 353900795.609040
 2012-03-19 21:46:36.360 Rest Counter[3776:707] Second Time: 353900796.360177
 2012-03-19 21:46:36.361 Rest Counter[3776:707] Final Result Time (difference): 0.751137
 2012-03-19 21:46:36.363 Rest Counter[3776:707] Mach absolute time: 18027372
 2012-03-19 21:46:36.365 Rest Counter[3776:707] Mach absolute time/final time: 24000113.153295
 2012-03-19 21:46:36.367 Rest Counter[3776:707] -----------------------------------------------------
 2012-03-19 21:46:43.074 Rest Counter[3776:707] First Time: 353900803.074637
 2012-03-19 21:46:43.170 Rest Counter[3776:707] Second Time: 353900803.170256
 2012-03-19 21:46:43.172 Rest Counter[3776:707] Final Result Time (difference): 0.095619
 2012-03-19 21:46:43.173 Rest Counter[3776:707] Mach absolute time: 2294833
 2012-03-19 21:46:43.175 Rest Counter[3776:707] Mach absolute time/final time: 23999753.727777
 2012-03-19 21:46:43.177 Rest Counter[3776:707] -----------------------------------------------------
 2012-03-19 21:46:46.499 Rest Counter[3776:707] First Time: 353900806.499199
 2012-03-19 21:46:55.017 Rest Counter[3776:707] Second Time: 353900815.016985
 2012-03-19 21:46:55.018 Rest Counter[3776:707] Final Result Time (difference): 8.517786
 2012-03-19 21:46:55.020 Rest Counter[3776:707] Mach absolute time: 204426836
 2012-03-19 21:46:55.022 Rest Counter[3776:707] Mach absolute time/final time: 23999996.639500
 2012-03-19 21:46:55.024 Rest Counter[3776:707] -----------------------------------------------------

Need to perform Wildcard (*,?, etc) search on a string using Regex

You must escape special Regex symbols in input wildcard pattern (for example pattern *.txt will equivalent to ^.*\.txt$) So slashes, braces and many special symbols must be replaced with @"\" + s, where s - special Regex symbol.

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

ng serve not detecting file changes automatically

for window -

c:\>ng serve --open

For Linux -

$sudo ng serve --open

How to ignore the first line of data when processing CSV data?

I would convert csvreader to list, then pop the first element

import csv        

with open(fileName, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        data = list(csvreader)               # Convert to list
        data.pop(0)                          # Removes the first row

        for row in data:
            print(row)

How to use wait and notify in Java without IllegalMonitorStateException?

Do you need to thread this at all ? I'm wondering how big your matrices are, and whether there's any benefit in having one thread print whilst the other does the multiplication.

Perhaps it would be worth measuring this time before doing the relatively complex threading work ?

If you do need to thread it, I would create 'n' threads to perform the multiplication of the cells (perhaps 'n' is the number of cores available to you), and then use the ExecutorService and Future mechanism to dispatch multiple multiplications simultaneously.

That way you can optimise the work based on the number of cores, and you're using the higher level Java threading tools (which should make life easier). Write the results back into a receiving matrix, and then simply print this once all your Future tasks have completed.

List all files and directories in a directory + subdirectories

using System.IO;
using System.Text;
string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories);

Can't install laravel installer via composer

It says that it requires zip extension

laravel/installer v1.4.0 requires ext-zip...

Install using (to install the default version):

sudo apt install php-zip

Or, if you're running a specific version of PHP:

# For php v7.0
sudo apt-get install php7.0-zip

# For php v7.1
sudo apt-get install php7.1-zip

# For php v7.2
sudo apt-get install php7.2-zip

# For php v7.3
sudo apt-get install php7.3-zip

# For php v7.4
sudo apt-get install php7.4-zip

How can a file be copied?

Similar to the accepted answer, the following code block might come in handy if you also want to make sure to create any (non-existent) folders in the path to the destination.

from os import path, makedirs
from shutil import copyfile
makedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)
copyfile(source_path, destination_path)

As the accepted answers notes, these lines will overwrite any file which exists at the destination path, so sometimes it might be useful to also add: if not path.exists(destination_path): before this code block.

How to add a progress bar to a shell script?

This is only applicable using gnome zenity. Zenity provides a great native interface to bash scripts: https://help.gnome.org/users/zenity/stable/

From Zenity Progress Bar Example:

#!/bin/sh
(
echo "10" ; sleep 1
echo "# Updating mail logs" ; sleep 1
echo "20" ; sleep 1
echo "# Resetting cron jobs" ; sleep 1
echo "50" ; sleep 1
echo "This line will just be ignored" ; sleep 1
echo "75" ; sleep 1
echo "# Rebooting system" ; sleep 1
echo "100" ; sleep 1
) |
zenity --progress \
  --title="Update System Logs" \
  --text="Scanning mail logs..." \
  --percentage=0

if [ "$?" = -1 ] ; then
        zenity --error \
          --text="Update canceled."
fi

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

Find a private field with Reflection?

Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).

The binding flag you will need is: System.Reflection.BindingFlags.NonPublic

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Cannot catch toolbar home button click event

    mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
    mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // event when click home button
        }
    });

in mycase this code work perfect

Map.Entry: How to use it?

Map.Entry is a key and its value combined into one class. This allows you to iterate over Map.entrySet() instead of having to iterate over Map.keySet(), then getting the value for each key. A better way to write what you have is:

for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
  String key = entry.getKey();
  JButton value = entry.getValue();

  this.add(value);
}

If this wasn't clear let me know and I'll amend my answer.

How to wrap async function calls into a sync function in Node.js or Javascript?

deasync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. As a result, deasync only blocks subsequent code from running without blocking entire thread, nor incuring busy wait. With this module, here is the answer to the jsFiddle challenge:

function AnticipatedSyncFunction(){
  var ret;
  setTimeout(function(){
      ret = "hello";
  },3000);
  while(ret === undefined) {
    require('deasync').runLoopOnce();
  }
  return ret;    
}


var output = AnticipatedSyncFunction();
//expected: output=hello (after waiting for 3 sec)
console.log("output="+output);
//actual: output=hello (after waiting for 3 sec)

(disclaimer: I am the co-author of deasync. The module was created after posting this question and found no workable proposal.)

How to escape the % (percent) sign in C's printf?

As others have said, %% will escape the %.

Note, however, that you should never do this:

char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);

Whenever you have to print a string, always, always, always print it using

printf("%s", c)

to prevent an embedded % from causing problems [memory violations, segfault, etc]

Ruby Hash to array of values

Also, a bit simpler....

>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]

Ruby doc here

Convert named list to vector with values only

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

How can I disable a tab inside a TabControl?

The TabPage class hides the Enabled property. That was intentional as there is an awkward UI design problem with it. The basic issue is that disabling the page does not also disable the tab. And if try to work around that by disabling the tab with the Selecting event then it does not work when the TabControl has only one page.

If these usability problems do not concern you then keep in mind that the property still works, it is merely hidden from IntelliSense. If the FUD is uncomfortable then you can simply do this:

public static void EnableTab(TabPage page, bool enable) {
    foreach (Control ctl in page.Controls) ctl.Enabled = enable;
}

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

EDIT: This applies to older versions of Visual Studio / MSBuild (specifically MSVC2015?). With more modern versions, MSBuild is included in Visual Studio Build Tools 2019, and compilers are located in different places and detected in different ways.

This is due to a mismatch of installed MSBuild toolsets and registry settings. It can happen if you did one or more of the following:

  • Install multiple Visual Studio versions in the wrong order
  • Uninstall one or more versions of Visual Studio
  • Manually make registry changes or modifications to the Visual Studio installation

The only safe and reliable solution I know of is to reinstall your OS. If your project needs multiple versions of Visual Studio to build, install the oldest version first. Then fix your code so you can use one single tool to build it, or you or your colleagues will be in the same mess again soon.

If this is not an option for you, first read https://stackoverflow.com/a/41786593/2279059 for a better understanding of the problem and what the various "solutions" actually do. Then, depending on your Visual Studio version and setup, one of the other answers or variations of them may eventually help.

Some more hints:

Equivalent of explode() to work with strings in MySQL

I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my very similar problem. I know some of the other solutions look shorter but they seem to use SUBSTRING_INDEX() way more than necessary. Here I try to just use LOCATE() just once per delimiter.

-- *****************************************************************************
-- test_PVreplace

DROP FUNCTION IF EXISTS test_PVreplace;

delimiter //
CREATE FUNCTION test_PVreplace (
   str TEXT,   -- String to do search'n'replace on
   pv TEXT     -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
   )
   RETURNS TEXT

-- Replace specific tags with specific values.

sproc:BEGIN
   DECLARE idx INT;
   DECLARE idx0 INT DEFAULT 1;   -- 1-origined, not 0-origined
   DECLARE len INT;
   DECLARE sPV TEXT;
   DECLARE iPV INT;
   DECLARE sP TEXT;
   DECLARE sV TEXT;

   -- P/V string *must* end with a delimiter.

   IF (RIGHT (pv, 1) <> '|') THEN
      SET pv = CONCAT (pv, '|');
      END IF;

   -- Find all the P/V pairs.

   SELECT LOCATE ('|', pv, idx0) INTO idx;
   WHILE (idx > 0) DO
      SET len = idx - idx0;
      SELECT SUBSTRING(pv, idx0, len) INTO sPV;

      -- Found a P/V pair.  Break it up.

      SELECT LOCATE ('=', sPV) INTO iPV;
      IF (iPV = 0) THEN
         SET sP = sPV;
         SET sV = '';
      ELSE
         SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
         SELECT SUBSTRING(sPV, iPV+1) INTO sV;
         END IF;

      -- Do the substitution(s).

      SELECT REPLACE (str, sP, sV) INTO str;

      -- Do next P/V pair.

      SET idx0 = idx + 1;
      SELECT LOCATE ('|', pv, idx0) INTO idx;
      END WHILE;
   RETURN (str);
END//
delimiter ;

SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');

Codeigniter $this->db->get(), how do I return values for a specific row?

Accessing a single row

//Result as an Object
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
echo $result->age;

//Result as an Array
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
echo $result['age'];

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Disable ONLY_FULL_GROUP_BY

To whom is running a VPS/Server with cPanel/WHM, you can do the following to permanently disable ONLY_FULL_GROUP_BY

You need root access (either on a VPS or a dedicated server)

  1. Enter WHM as root and run phpMyAdmin

  2. Click on Variables, look for sql_mode, click on 'Edit' and copy the entire line inside that textbox

e.g. copy this:

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  1. Connect to you server via SFTP - SSH (root) and download the file /etc/my.cnf

  2. Open with a text editor my.cnf file on your local PC and paste into it (under [mysqld] section) the entire line you copied at step (2) but remove ONLY_FULL_GROUP_BY,

e.g. paste this:

# disabling ONLY_FULL_GROUP_BY
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  1. Save the my.cnf file and upload it back into /etc/

  2. Enter WHM and go to "WHM > Restart Services > SQL Server (MySQL)" and restart the service

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Here's a modification of CMS's solution that can be called in multiple places in your code:

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});

CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.

With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.

SQL query to select dates between two dates

SELECT Date, TotalAllowance  
FROM Calculation  
WHERE EmployeeId = 1 
  AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd') 
               AND to_date ('2011/02/27','yyyy-mm-dd');

Why does the order in which libraries are linked sometimes cause errors in GCC?

I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.

Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.

For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.

Once you hit upon a solution document it so the next developer does not have to work it out again.

My old lecturer used to say, "high cohesion & low coupling", it’s still true today.

Python json.loads shows ValueError: Extra data

You can just read from a file, jsonifying each line as you go:

tweets = []
for line in open('tweets.json', 'r'):
    tweets.append(json.loads(line))

This avoids storing intermediate python objects. As long as your write one full tweet per append() call, this should work.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Problem: (Sql server 2014) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 12.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=42295 and download:

  • ENU\x64\SharedManagementObjects.msi for X64 OS or
  • ENU\x86\SharedManagementObjects.msi for X86 OS,

then install it, and restart visual studio.

PS: You may need install DB2OLEDBV5_x64.msi or DB2OLEDBV5_x86.msi too.


Problem: (Sql server 2012) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=35580 and download:

  • ENU\x64\SharedManagementObjects.msi for X64 OS or
  • ENU\x86\SharedManagementObjects.msi for X86 OS,

then install it, and restart visual studio.


Problem: (Sql server 2008) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 10.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=26728 and download:

  • 1033\x64\SharedManagementObjects.msi for X64 OS or
  • 1033\x86\SharedManagementObjects.msi for X86 OS,

(In most cases downloading this is better http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0x409)

then install it, and restart visual studio.


Problem: I recently got similar problem after installing SharedManagementObjects. assembly Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0 not found by visual studio. The problem was Visual C++ Redistributable Packages for Visual Studio was not installed yet.

Solution: for Visual Studio 2013 just go to http://www.microsoft.com/en-us/download/details.aspx?id=40784 and download:

  • vcredist_x64.exe for X64 OS or
  • vcredist_x86.exe for X86 OS,

then install it, and restart visual studio.

PS: You can find Visual C++ Redistributable Packages for Visual Studio 20XX for other versions of Visual Studio easily by googling it.

What is an AssertionError? In which case should I throw it from my own code?

Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw AssertionErrors everywhere, and that is obviously not what happens.

The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private and not calling it from within Example's code). And so if a call occurs, that assertion has been violated, and so AssertionError is appropriate.

Can I hide/show asp:Menu items based on role?

You can remove unwanted menu items in Page_Load, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.

Find the unique values in a column and then sort them

I would suggest using numpy's sort, as it is anyway what pandas is doing in background:

import numpy as np
np.sort(df.A.unique())

But doing all in pandas is valid as well.

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

Plot two graphs in same plot in R

Rather than keeping the values to be plotted in an array, store them in a matrix. By default the entire matrix will be treated as one data set. However if you add the same number of modifiers to the plot, e.g. the col(), as you have rows in the matrix, R will figure out that each row should be treated independently. For example:

x = matrix( c(21,50,80,41), nrow=2 )
y = matrix( c(1,2,1,2), nrow=2 )
plot(x, y, col("red","blue")

This should work unless your data sets are of differing sizes.

What is the difference between 'E', 'T', and '?' for Java generics?

It's more convention than anything else.

  • T is meant to be a Type
  • E is meant to be an Element (List<E>: a list of Elements)
  • K is Key (in a Map<K,V>)
  • V is Value (as a return value or mapped value)

They are fully interchangeable (conflicts in the same declaration notwithstanding).

Generating random integer from a range

assume min and max are int values, [ and ] means include this value, ( and ) means not include this value, using above to get the right value using c++ rand()

reference: for ()[] define, visit:

https://en.wikipedia.org/wiki/Interval_(mathematics)

for rand and srand function or RAND_MAX define, visit:

http://en.cppreference.com/w/cpp/numeric/random/rand

[min, max]

int randNum = rand() % (max - min + 1) + min

(min, max]

int randNum = rand() % (max - min) + min + 1

[min, max)

int randNum = rand() % (max - min) + min

(min, max)

int randNum = rand() % (max - min - 1) + min + 1

Best algorithm for detecting cycles in a directed graph

Given that this is a schedule of jobs, I suspect that at some point you are going to sort them into a proposed order of execution.

If that's the case, then a topological sort implementation may in any case detect cycles. UNIX tsort certainly does. I think it is likely that it is therefore more efficient to detect cycles at the same time as tsorting, rather than in a separate step.

So the question might become, "how do I most efficiently tsort", rather than "how do I most efficiently detect loops". To which the answer is probably "use a library", but failing that the following Wikipedia article:

http://en.wikipedia.org/wiki/Topological_sorting

has the pseudo-code for one algorithm, and a brief description of another from Tarjan. Both have O(|V| + |E|) time complexity.

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
   // do something...
   return null;
}

What do "branch", "tag" and "trunk" mean in Subversion repositories?

The trunk directory is the directory that you're probably most familiar with, because it is used to hold the most recent changes. Your main codebase should be in trunk.

The branches directory is for holding your branches, whatever they may be.

The tags directory is basically for tagging a certain set of files. You do this for things like releases, where you want "1.0" to be these files at these revisions and "1.1" to be these files at these revisions. You usually don't modify tags once they're made. For more information on tags, see Chapter 4. Branching and Merging (in Version Control with Subversion).

How to checkout a specific Subversion revision from the command line?

It seems that you can use the repository browser. Click the revision button at top-right and change it to the revision you want. Then right-click your file in the browser and use 'Copy to working copy...' but change the filename it will check out, to avoid a clash.

Could not find or load main class

First, put your file *.class (e.g Hello.class) into 1 folder (e.g C:\java). Then you try command and type cd /d C:\java. Now you can type "java Hello" !

PHP json_decode() returns NULL with valid JSON?

If you are getting json from database, put

mysqli_set_charset($con, "utf8");

after defining connection link $con

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

Fitting a histogram with python

I was a bit puzzled that norm.fit apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...

# histogram is [(val,count)]
from math import sqrt

def normfit(hist):
    n,s,ss = univar(hist)
    mu = s/n
    var = ss/n-mu*mu
    return (mu, sqrt(var))

def univar(hist):
    n = 0
    s = 0
    ss = 0
    for v,c in hist:
        n += c
        s += c*v
        ss += c*v*v
    return n, s, ss

I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)

RestClientException: Could not extract response. no suitable HttpMessageConverter found

I was having a very similar problem, and it turned out to be quite simple; my client wasn't including a Jackson dependency, even though the code all compiled correctly, the auto-magic converters for JSON weren't being included. See this RestTemplate-related solution.

In short, I added a Jackson dependency to my pom.xml and it just worked:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.1</version>
</dependency>

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

Add System.IO.Compression.ZipFile as nuget reference it is working

Show dialog from fragment?

I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.

I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.

How can I compile LaTeX in UTF8?

Save your file in UTF8 format.

Verify the file format using the following (UNIX) command:

file -bi filename.tex 

You should see:

text/x-tex; charset=utf-8

Convert the file using iconv if it is not UTF8:

iconv --from-code=ISO-8859-1 --to-code=UTF-8 filename.txt > filename-utf.txt

How to round double to nearest whole number and then convert to a float?

For what is worth:

the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer

+-------+--------+
| input | output |
+-------+--------+
|     1 |      0 |
|     2 |      0 |
|     3 |      5 |
|     4 |      5 |
|     5 |      5 |
|     6 |      5 |
|     7 |      5 |
|     8 |     10 |
|     9 |     10 |
+-------+--------+

private int roundClosest(final int i, final int k) {
    int deic = (i % k);
    if (deic <= (k / 2.0)) {
        return (int) (Math.floor(i / (double) k) * k);
    } else {
        return (int) (Math.ceil(i / (double) k) * k);
    }
}

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

ImageMagick security policy 'PDF' blocking conversion

For me on my archlinux system the line was already uncommented. I had to replace "none" by "read | write " to make it work.

How to display default text "--Select Team --" in combo box on pageload in WPF?

Not tried it with combo boxes but this has worked for me with other controls...

ageektrapped blogpost

He uses the adorner layer here to display a watermark.

If Browser is Internet Explorer: run an alternative script instead

Try this: The systemLanguage and the userLanguage is undefined in all browser.

if(navigator.userLanguage !== "undefined" && navigator.systemLanguage !== "undefined" && navigator.userAgent.match(/trident/i)) {
    alert("hello explorer i catch U :D")
  }

Tracking Google Analytics Page Views with AngularJS

Just a quick addition. If you're using the new analytics.js, then:

var track = function() {     
 ga('send', 'pageview', {'page': $location.path()});                
};

Additionally one tip is that google analytics will not fire on localhost. So if you are testing on localhost, use the following instead of the default create (full documentation)

ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});

How can I parse a YAML file from a Linux shell script?

Given that Python3 and PyYAML are quite easy dependencies to meet nowadays, the following may help:

yaml() {
    python3 -c "import yaml;print(yaml.safe_load(open('$1'))$2)"
}

VALUE=$(yaml ~/my_yaml_file.yaml "['a_key']")

How to import module when module name has a '-' dash or hyphen in it?

Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path

For example if your structure is like this:

foo-bar
+-- barfoo.py
+-- __init__.py

import sys
sys.path.append('foo-bar')

import barfoo

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

first of all: as far as i know placing dialog inside a tabview is a bad practice... you better take it out...

and now to your question:

sorry, took me some time to get what exactly you wanted to implement,

did at my web app myself just now, and it works

as I sayed before place the p:dialog out side the `p:tabView ,

leave the p:dialog as you initially suggested :

<p:dialog modal="true" widgetVar="dlg">
    <h:panelGrid id="display">
        <h:outputText value="Name:" />
        <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
    </h:panelGrid>
</p:dialog>   

and the p:commandlink should look like this (all i did is to change the update attribute)

<p:commandLink update="display" oncomplete="dlg.show()">
    <f:setPropertyActionListener value="#{lndInstrument}" 
        target="#{instrumentBean.selectedInstrument}" />
    <h:outputText value="#{lndInstrument.name}" />
</p:commandLink>  

the same works in my web app, and if it does not work for you , then i guess there is something wrong in your java bean code...

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

How to echo in PHP, HTML tags

<?php

echo '<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>';

?>

Just put it in single quotes.

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

How do you decompile a swf file

erlswf is an opensource project written in erlang for decompiling .swf files.

Here's the site: https://github.com/bef/erlswf

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

Excel VBA date formats

It's important to distinguish between the content of cells, their display format, the data type read from cells by VBA, and the data type written to cells from VBA and how Excel automatically interprets this. (See e.g. this previous answer.) The relationship between these can be a bit complicated, because Excel will do things like interpret values of one type (e.g. string) as being a certain other data type (e.g. date) and then automatically change the display format based on this. Your safest bet it do everything explicitly and not to rely on this automatic stuff.

I ran your experiment and I don't get the same results as you do. My cell A1 stays a Date the whole time, and B1 stays 41575. So I can't answer your question #1. Results probably depend on how your Excel version/settings choose to automatically detect/change a cell's number format based on its content.

Question #2, "How can I ensure that a cell will return a date value": well, not sure what you mean by "return" a date value, but if you want it to contain a numerical value that is displayed as a date, based on what you write to it from VBA, then you can either:

  • Write to the cell a string value that you hope Excel will automatically interpret as a date and format as such. Cross fingers. Obviously this is not very robust. Or,

  • Write a numerical value to the cell from VBA (obviously a Date type is the intended type, but an Integer, Long, Single, or Double could do as well) and explicitly set the cells' number format to your desired date format using the .NumberFormat property (or manually in Excel). This is much more robust.

If you want to check that existing cell contents can be displayed as a date, then here's a function that will help:

Function CellContentCanBeInterpretedAsADate(cell As Range) As Boolean
    Dim d As Date
    On Error Resume Next
    d = CDate(cell.Value)
    If Err.Number <> 0 Then
        CellContentCanBeInterpretedAsADate = False
    Else
        CellContentCanBeInterpretedAsADate = True
    End If
    On Error GoTo 0
End Function

Example usage:

Dim cell As Range
Set cell = Range("A1")

If CellContentCanBeInterpretedAsADate(cell) Then
    cell.NumberFormat = "mm/dd/yyyy hh:mm"
Else
    cell.NumberFormat = "General"
End If

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

What are the differences between delegates and events?

Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.

How do I kill all the processes in Mysql "show processlist"?

I'd combine bash and mysql:

for i in $(mysql -Ne "select id from information_schema.processlist where user like 'foo%user' and time > 300;"); do
  mysql -e "kill ${i}"
done

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

Best practice to validate null and empty collection in Java

If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

  • null might mean something more specific;
  • your API (contract) might force you to return null.

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

List files with certain extensions with ls and grep

Here is one example that worked for me.

find <mainfolder path> -name '*myfiles.java' | xargs -n 1 basename

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

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

Scato wrotes:

anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).

the console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648

Hex-Decimals are unsigned positive values, so 0x80000000 = 2147483648 - thats mathematically correct. If you want to make it a signed value you have to right shift: 0x80000000 >> 0 = -2147483648. You can write 1 << 31 instead, too.

Find objects between two dates MongoDB

To clarify. What is important to know is that:

  • Yes, you have to pass a Javascript Date object.
  • Yes, it has to be ISODate friendly
  • Yes, from my experience getting this to work, you need to manipulate the date to ISO
  • Yes, working with dates is generally always a tedious process, and mongo is no exception

Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:

var inputDate = new Date(myDate.toISOString());
MyModel.find({
    'date': { $lte: inputDate }
})

Print a list in reverse order with range()?

Use the 'range' built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding stop.

>>> range(9,-1,-1)   
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
    [-2, 0, 2, 4]

In Python 3, this produces a non-list range object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).