Programs & Examples On #Javolution

Javolution is a hard-real-time collections library.

Iterating through a range of dates in Python

for i in range(16):
    print datetime.date.today() + datetime.timedelta(days=i)

What's the difference between OpenID and OAuth?

OAuth

Used for delegated authorization only -- meaning you are authorizing a third-party service access to use personal data, without giving out a password. Also OAuth "sessions" generally live longer than user sessions. Meaning that OAuth is designed to allow authorization

i.e. Flickr uses OAuth to allow third-party services to post and edit a persons picture on their behalf, without them having to give out their flicker username and password.

OpenID

Used to authenticate single sign-on identity. All OpenID is supposed to do is allow an OpenID provider to prove that you say you are. However many sites use identity authentication to provide authorization (however the two can be separated out)

i.e. One shows their passport at the airport to authenticate (or prove) the person's who's name is on the ticket they are using is them.

How can I get the source directory of a Bash script from within the script itself?

I don't think this is as easy as others have made it out to be. pwd doesn't work, as the current directory is not necessarily the directory with the script. $0 doesn't always have the information either. Consider the following three ways to invoke a script:

./script

/usr/bin/script

script

In the first and third ways $0 doesn't have the full path information. In the second and third, pwd does not work. The only way to get the directory in the third way would be to run through the path and find the file with the correct match. Basically the code would have to redo what the OS does.

One way to do what you are asking would be to just hardcode the data in the /usr/share directory, and reference it by its full path. Data shoudn't be in the /usr/bin directory anyway, so this is probably the thing to do.

Validation to check if password and confirm password are same is not working

if((pswd.length<6 || pswd.length>12) || pswd == ""){
        document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;

} 

else {  
    if(pswd != pswdcnf) {
        document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
    } else {
        document.getElementById("passwordconfirm").innerHTML="password  matche";
        document.getElementById("passwordloc").innerHTML = '';
    }

}

Update ViewPager dynamically?

I had been trying so many different approaches, none really sove my problem. Below are how I solve it with a mix of solutions provided by you all. Thanks everyone.

class PagerAdapter extends FragmentPagerAdapter {

    public boolean flag_refresh=false;

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int page) {
        FragmentsMain f;
        f=new FragmentsMain();
        f.page=page;
        return f;
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public int getItemPosition(Object item) {
        int page= ((FragmentsMain)item).page;

        if (page == 0 && flag_refresh) {
            flag_refresh=false;
            return POSITION_NONE;
        } else {
            return super.getItemPosition(item);
        }
    }

    @Override
    public void destroyItem(View container, int position, Object object) {

        ((ViewPager) container).removeView((View) object);
    }
}

I only want to refresh page 0 after onResume().

 adapter=new PagerAdapter(getSupportFragmentManager());
 pager.setAdapter(adapter);

@Override
protected void onResume() {
    super.onResume();

    if (adapter!=null) {
        adapter.flag_refresh=true;
        adapter.notifyDataSetChanged();
    }
}

In my FragmentsMain, there is public integer "page", which can tell me whether it is the page I want to refresh.

public class FragmentsMain extends Fragment {

private Cursor cursor;
private static Context context;
public int page=-1;

Printing without newline (print 'a',) prints a space, how to remove?

Either what Ant says, or accumulate into a string, then print once:

s = '';
for i in xrange(20):
    s += 'a'
print s

How to change a particular element of a C++ STL vector

at and operator[] both return a reference to the indexed element, so you can simply use:

l.at(4) = -1;

or

l[4] = -1;

Returning data from Axios API

    async handleResponse(){
      const result = await this.axiosTest();
    }

    async axiosTest () {
    return await axios.get(url)
    .then(function (response) {
            console.log(response.data);
            return response.data;})
.catch(function (error) {
    console.log(error);
});
}

You can find check https://flaviocopes.com/axios/#post-requests url and find some relevant information in the GET section of this post.

Guid.NewGuid() vs. new Guid()

Guid.NewGuid(), as it creates GUIDs as intended.

Guid.NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

new Guid() merely creates an empty GUID (all zeros, I think).

I guess they had to make the constructor public as Guid is a struct.

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')
>>> plt.show()

enter image description here

constant pointer vs pointer on a constant value

const char * a;

This states pointer to constant character. For eg.

char b='s';
const char *a = &b;

Here a points to a constant char('s',in this case).You can't use a to change that value.But this declaration doesn't mean that value it points to is really a constant,it just means the value is a constant insofar as a is concerned. You can change the value of b directly by changing the value of b,but you can't change the value indirectly via the a pointer.

*a='t'; //INVALID b='t' ; //VALID

char * const a=&b

This states a constant pointer to char. It constraints a to point only to b however it allows you to alter the value of b.

Hope it helps!!! :)

WordPress - Check if user is logged in

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.

if (get_current_user_id()) {
   // display navbar here
}

More details here get_current_user_id().

"Fade" borders in CSS

I know this is old but this seems to work well for me in 2020...

Using the border-image CSS property I was able to quickly manipulate the borders for this fading purpose.

Note: I don't think border-image works well with border-radius... I seen someone saying that somewhere but for this purpose it works well.

1 Liner:

CSS

 .bbdr_rfade_1      { border: 4px solid; border-image: linear-gradient(90deg, rgba(60,74,83,0.90), rgba(60,74,83,.00)) 1; border-left:none; border-top:none; border-right:none;  }

HTML

<div class = 'bbdr_rfade_1'>Oh I am so going to not up-vote this guy...</div>

How do I make a div full screen?

This is the simplest one.

#divid {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

importing pyspark in python shell

Here is a simple method (If you don't bother about how it works!!!)

Use findspark

  1. Go to your python shell

    pip install findspark
    
    import findspark
    findspark.init()
    
  2. import the necessary modules

    from pyspark import SparkContext
    from pyspark import SparkConf
    
  3. Done!!!

How to convert JSON to XML or XML to JSON?

For convert JSON string to XML try this:

    public string JsonToXML(string json)
    {
        XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
        XElement root = new XElement("Root");
        root.Name = "Result";

        var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
        root.Add(
                 from row in dataTable.AsEnumerable()
                 select new XElement("Record",
                                     from column in dataTable.Columns.Cast<DataColumn>()
                                     select new XElement(column.ColumnName, row[column])
                                    )
               );


        xmlDoc.Add(root);
        return xmlDoc.ToString();
    }

For convert XML to JSON try this:

    public string XmlToJson(string xml)
    {
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(xml);

       string jsonText = JsonConvert.SerializeXmlNode(doc);
       return jsonText;
     }

Using Powershell to stop a service remotely without WMI or remoting

You can also do (Get-Service -Name "what ever" - ComputerName RemoteHost).Status = "Stopped"

Better naming in Tuple classes than "Item1", "Item2"

You Can write a class that contains the Tuple.

You need to override the Equals and GetHashCode functions

and the == and != operators.

class Program
{
    public class MyTuple
    {
        private Tuple<int, int> t;

        public MyTuple(int a, int b)
        {
            t = new Tuple<int, int>(a, b);
        }

        public int A
        {
            get
            {
                return t.Item1;
            }
        }

        public int B
        {
            get
            {
                return t.Item2;
            }
        }

        public override bool Equals(object obj)
        {
            return t.Equals(((MyTuple)obj).t);
        }

        public override int GetHashCode()
        {
            return t.GetHashCode();
        }

        public static bool operator ==(MyTuple m1, MyTuple m2)
        {
            return m1.Equals(m2);
        }

        public static bool operator !=(MyTuple m1, MyTuple m2)
        {
            return !m1.Equals(m2);
        }
    }

    static void Main(string[] args)
    {
        var v1 = new MyTuple(1, 2);
        var v2 = new MyTuple(1, 2);

        Console.WriteLine(v1 == v2);

        Dictionary<MyTuple, int> d = new Dictionary<MyTuple, int>();
        d.Add(v1, 1);

        Console.WriteLine(d.ContainsKey(v2));
    }
}

will return:

True

True

How to create an email form that can send email using html

you can use Simple Contact Form in HTML with PHP mailer. It's easy to implement in you website. You can try the demo from following link: Simple Contact/Feedback Form in HTML-PHP mailer

Otherwise you can watch the demo video in following link: Youtube: Simple Contact/Feedback Form in HTML-PHP mailer

When you are running in localhost, you may get following error:

Warning: mail(): Failed to connect to mailserver at "smtp.gmail.com" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in S:\wamp\www\sample\mailTo.php on line 10

You can check in this link for more detailed information: Simple Contact/Feedback Form in HTML with php (HTML-PHP mailer) And this is the screenshot of HTML form: Simple Form

And this is the main PHP coding:

<?php
if($_POST["submit"]) {
    $recipient="[email protected]"; //Enter your mail address
    $subject="Contact from Website"; //Subject 
    $sender=$_POST["name"];
    $senderEmail=$_POST["email"];
    $message=$_POST["comments"];
    $mailBody="Name: $sender\nEmail Address: $senderEmail\n\nMessage: $message";
    mail($recipient, $subject, $mailBody);
    sleep(1);
    header("Location:http://blog.antonyraphel.in/sample/"); // Set here redirect page or destination page
}
?>

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I have polished this missing subclass of QLabel. It is awesome and works well.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>
#include <QResizeEvent>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(QWidget *parent = 0);
    virtual int heightForWidth( int width ) const;
    virtual QSize sizeHint() const;
    QPixmap scaledPixmap() const;
public slots:
    void setPixmap ( const QPixmap & );
    void resizeEvent(QResizeEvent *);
private:
    QPixmap pix;
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"
//#include <QDebug>

AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
    QLabel(parent)
{
    this->setMinimumSize(1,1);
    setScaledContents(false);
}

void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
{
    pix = p;
    QLabel::setPixmap(scaledPixmap());
}

int AspectRatioPixmapLabel::heightForWidth( int width ) const
{
    return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
}

QSize AspectRatioPixmapLabel::sizeHint() const
{
    int w = this->width();
    return QSize( w, heightForWidth(w) );
}

QPixmap AspectRatioPixmapLabel::scaledPixmap() const
{
    return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}

void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
{
    if(!pix.isNull())
        QLabel::setPixmap(scaledPixmap());
}

Hope that helps! (Updated resizeEvent, per @dmzl's answer)

img onclick call to JavaScript function

Put the javascript part and the end right before the closing </body> then it should work.

http://jsfiddle.net/Q3Zy3/1/

  <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
  <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>

  <script type="text/javascript">
      function exportToForm(a,b,c,d,e) {
      alert(a + b);
      window.external.values(a.value, b.value, c.value, d.value, e.value);
  }
</script>

Exception in thread "main" java.util.NoSuchElementException

Everyone explained pretty well on it. Let me answer when should this class be used.

When Should You Use NoSuchElementException?

Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0 and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.

As with most programming languages, the Iterator class includes a hasNext() method that returns a boolean indicating if the iteration has anymore elements. If hasNext() returns true, then the next() method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove() method, which removes the last element that was obtained via next().

While Iterator is generalized for use with all collections in the Java Collections Framework, ListIterator is more specialized and only works with List-based collections, like ArrayList, LinkedList, and so forth. However, ListIterator adds even more functionality by allowing iteration to traverse in both directions via hasPrevious() and previous() methods.

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Android Shared preferences for creating one time activity (example)

Setting values in Preference:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.apply();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.

More info:

Using Shared Preferences

Shared Preferences

Changing SQL Server collation to case insensitive from case sensitive?

You basically need to run the installation again to rebuild the master database with the new collation. You cannot change the entire server's collation any other way.

See:

Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'test2'   -- put your database name here

This will yield a value something like:

Latin1_General_CI_AS

The _CI means "case insensitive" - if you want case-sensitive, use _CS in its place:

Latin1_General_CS_AS

So your T-SQL command would be:

ALTER DATABASE test2 -- put your database name here
   COLLATE Latin1_General_CS_AS   -- replace with whatever collation you need

You can get a list of all available collations on the server using:

SELECT * FROM ::fn_helpcollations()

You can see the server's current collation using:

SELECT SERVERPROPERTY ('Collation')

What should main() return in C and C++?

Returning 0 should tell the programmer that the program has successfully finished the job.

working with negative numbers in python

import time

print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

print ()


while x > 0:
    print (':',z)
    x = x - 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',z)

while x < 0:
    print (':',-(z))
    x = x + 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',-(z))

print ()  

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Using new line(\n) in string and rendering the same in HTML

Use <br /> for new line in html:

display_txt = display_txt.replace(/\n/g, "<br />");

Convert character to Date in R

library(lubridate) if your date format is like this '04/24/2017 05:35:00'then change it like below prods.all$Date2<-gsub("/","-",prods.all$Date2) then change the date format parse_date_time(prods.all$Date2, orders="mdy hms")

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

Saving and Reading Bitmaps/Images from Internal memory in Android

// mutiple image retrieve

 File folPath = new File(getIntent().getStringExtra("folder_path"));
 File[] imagep = folPath.listFiles();

 for (int i = 0; i < imagep.length ; i++) {
     imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
 }
 imagesAdapter.notifyDataSetChanged();

View/edit ID3 data for MP3 files

TagLib Sharp is pretty popular.

As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.

class MusicID3Tag

{

    public byte[] TAGID = new byte[3];      //  3
    public byte[] Title = new byte[30];     //  30
    public byte[] Artist = new byte[30];    //  30 
    public byte[] Album = new byte[30];     //  30 
    public byte[] Year = new byte[4];       //  4 
    public byte[] Comment = new byte[30];   //  30 
    public byte[] Genre = new byte[1];      //  1

}

string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";

        using (FileStream fs = File.OpenRead(filePath))
        {
            if (fs.Length >= 128)
            {
                MusicID3Tag tag = new MusicID3Tag();
                fs.Seek(-128, SeekOrigin.End);
                fs.Read(tag.TAGID, 0, tag.TAGID.Length);
                fs.Read(tag.Title, 0, tag.Title.Length);
                fs.Read(tag.Artist, 0, tag.Artist.Length);
                fs.Read(tag.Album, 0, tag.Album.Length);
                fs.Read(tag.Year, 0, tag.Year.Length);
                fs.Read(tag.Comment, 0, tag.Comment.Length);
                fs.Read(tag.Genre, 0, tag.Genre.Length);
                string theTAGID = Encoding.Default.GetString(tag.TAGID);

                if (theTAGID.Equals("TAG"))
                {
                    string Title = Encoding.Default.GetString(tag.Title);
                    string Artist = Encoding.Default.GetString(tag.Artist);
                    string Album = Encoding.Default.GetString(tag.Album);
                    string Year = Encoding.Default.GetString(tag.Year);
                    string Comment = Encoding.Default.GetString(tag.Comment);
                    string Genre = Encoding.Default.GetString(tag.Genre);

                    Console.WriteLine(Title);
                    Console.WriteLine(Artist);
                    Console.WriteLine(Album);
                    Console.WriteLine(Year);
                    Console.WriteLine(Comment);
                    Console.WriteLine(Genre);
                    Console.WriteLine();
                }
            }
        }

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Extract hostname name from string

I tried to use the Given solutions, the Chosen one was an overkill for my purpose and "Creating a element" one messes up for me.

It's not ready for Port in URL yet. I hope someone finds it useful

function parseURL(url){
    parsed_url = {}

    if ( url == null || url.length == 0 )
        return parsed_url;

    protocol_i = url.indexOf('://');
    parsed_url.protocol = url.substr(0,protocol_i);

    remaining_url = url.substr(protocol_i + 3, url.length);
    domain_i = remaining_url.indexOf('/');
    domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;
    parsed_url.domain = remaining_url.substr(0, domain_i);
    parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);

    domain_parts = parsed_url.domain.split('.');
    switch ( domain_parts.length ){
        case 2:
          parsed_url.subdomain = null;
          parsed_url.host = domain_parts[0];
          parsed_url.tld = domain_parts[1];
          break;
        case 3:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2];
          break;
        case 4:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];
          break;
    }

    parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;

    return parsed_url;
}

Running this:

parseURL('https://www.facebook.com/100003379429021_356001651189146');

Result:

Object {
    domain : "www.facebook.com",
    host : "facebook",
    path : "100003379429021_356001651189146",
    protocol : "https",
    subdomain : "www",
    tld : "com"
}

How to scale an Image in ImageView to keep the aspect ratio

If image quality decreases in: use

android:adjustViewBounds="true"

instead of

android:adjustViewBounds="true"
android:scaleType="fitXY"

Which MIME type to use for a binary file that's specific to my program?

mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,

If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),

if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319

if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:

if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way

:)

Not able to change TextField Border Color

  1. Inside your lib file

  2. Create a folder called colors.

  3. Inside the colors folder create a dart file and name it color.

  4. Paste this code inside it

    const MaterialColor primaryOrange = MaterialColor(
        _orangePrimaryValue,
        <int, Color>{
            50: Color(0xFFFF9480),
            100: Color(0xFFFF9480),
            200: Color(0xFFFF9480),
            300: Color(0xFFFF9480),
            400: Color(0xFFFF9480),
            500: Color(0xFFFF9480),
            600: Color(0xFFFF9480),
            700: Color(0xFFFF9480),
            800: Color(0xFFFF9480),
            900: Color(0xFFFF9480),
        },
    );
    const int _orangePrimaryValue = 0xFFFF9480;
    
  5. Go to your main.dart file and place this code in your theme

    theme:ThemeData(
        primarySwatch: primaryOrange,
    ),
    
  6. Import the color folder in your main.dart like this import 'colors/colors.dart';

How to assign string to bytes array

Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16([]byte, uint16).

func byte16PutString(s string) [16]byte {
    var a [16]byte
    if len(s) > 16 {
        copy(a[:], s)
    } else {
        copy(a[16-len(s):], s)
    }
    return a
}

var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%v\n", b)

Output:

[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]

Notice how I wanted padding on the left, not the right.

http://play.golang.org/p/7tNumnJaiN

How could I create a function with a completion handler in Swift?

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

Hope it helps.

How to draw a dotted line with css?

Add following attribute to the element you want to have dotted line.

style="border-bottom: 1px dotted #ff0000;"

How do I resolve ClassNotFoundException?

If you have moved your project to new machine or importing it from git, then try this.

  1. Right Click on class > Run as > Run Configuration
  2. remove main class reference
  3. Apply > Close
  4. Now again right click on class > run as java application.

It worked for me.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

Angular and Typescript: Can't find names - Error: cannot find name

 typings install dt~es6-shim --save --global

and add the correct path to index.d.ts

///<reference path="../typings/index.d.ts"/>

Tried on @angular-2.0.0-rc3

How to disable text selection using jQuery?

1 line solution for CHROME:

body.style.webkitUserSelect = "none";

and FF:

body.style.MozUserSelect = "none";

IE requires setting the "unselectable" attribute (details on bottom).

I tested this in Chrome and it works. This property is inherited so setting it on the body element will disable selection in your entire document.

Details here: http://help.dottoro.com/ljrlukea.php

If you're using Closure, just call this function:

goog.style.setUnselectable(myElement, true);

It handles all browsers transparently.

The non-IE browsers are handled like this:

goog.style.unselectableStyle_ =
    goog.userAgent.GECKO ? 'MozUserSelect' :
    goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
    null;

Defined here: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html

The IE portion is handled like this:

if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
  for (var i = 0, descendant; descendant = descendants[i]; i++) {
    descendant.setAttribute('unselectable', value);
  }
}

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

Cannot install packages using node package manager in Ubuntu

you can create a link ln -s nodejs node in /usr/bin hope this solves your problem.

Reading a key from the Web.Config using ConfigurationManager

Sorry I've not tested this but I think it's done like this:

var filemap = new System.Configuration.ExeConfigurationFileMap();            
System.Configuration.Configuration config =  System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);

//usage: config.AppSettings["xxx"]

How to invoke a Linux shell command from Java

Building on @Tim's example to make a self-contained method:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)

By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.

Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.

Can we call the function written in one JavaScript in another JS file?

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:

function localStorageGet( pKey ) {
    if( localStorageSupported() ) {
        return localStorage[pKey];
    } else {
        return docCookies.getItem( 'localstorage.'+pKey );
    }
}

function localStorageSet( pKey, pValue ) {
    if( localStorageSupported() ) {
        localStorage[pKey] = pValue;
    } else {
        docCookies.setItem( 'localstorage.'+pKey, pValue );
    }
}

// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
    var testKey = 'test', storage = window.sessionStorage;
    if( gStorageSupported === undefined ) {
        try {
            storage.setItem(testKey, '1');
            storage.removeItem(testKey);
            gStorageSupported = true;
        } catch (error) {
            gStorageSupported = false;
        }
    }
    return gStorageSupported;
}

In your source, just use:

localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...

How to put a link on a button with bootstrap?

This is how I solved

   <a href="#" >
      <button type="button" class="btn btn-info">Button Text</button>
   </a>  

How do you stash an untracked file?

I thought this could be solved by telling git that the file exists, rather than committing all of the contents of it to the staging area, and then call git stash. Araqnid describes how to do the former.

git add --intent-to-add path/to/untracked-file

or

git update-index --add --cacheinfo 100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 path/to/untracked-file

However, the latter doesn't work:

$ git stash
b.rb: not added yet
fatal: git-write-tree: error building trees
Cannot save the current index state

git with IntelliJ IDEA: Could not read from remote repository

what @yabin ya says is a cool solution, just remind you that: if u still get the same problem,go to Settings-Version Control-GitHub and uncheck the Clone git repositories using ssh.

why numpy.ndarray is object is not callable in my simple for python loop

Avoid the for loopfor XY in xy: Instead read up how the numpy arrays are indexed and handled.

Numpy Indexing

Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.

PHP code is not being executed, instead code shows on the page

Add AddType application/x-httpd-php .php to your httpd.conf file if you are using Apache 2.4

Add Marker function with Google Maps API

function initialize() {
    var location = new google.maps.LatLng(44.5403, -78.5463);
    var mapCanvas = document.getElementById('map_canvas');
    var map_options = {
      center: location,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options);

    new google.maps.Marker({
        position: location,
        map: map
    });
}
google.maps.event.addDomListener(window, 'load', initialize);

Javascript Src Path

If you have

<base href="/" />

It's will not load file right. Just delete it.

submitting a form when a checkbox is checked

Yes, this is possible.

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
    <input type="submit" name="submit" value="Search" />
</form>

By adding onchange="document.getElementById('formName').submit()" to each checkbox, you'll submit any time a checkbox is changed.

If you're OK with jQuery, it's even easier (and unobtrusive):

$(document).ready(function(){
    $("#formname").on("change", "input:checkbox", function(){
        $("#formname").submit();
    });
});

For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on() method.

Cannot get OpenCV to compile because of undefined references?

This is a linker issue. Try:

g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`

This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:

sudo ldconfig

(grep) Regex to match non-ASCII characters?

This will match a single non-ASCII character:

[^\x00-\x7F]

This is a valid PCRE (Perl-Compatible Regular Expression).

You can also use the POSIX shorthands:

  • [[:ascii:]] - matches a single ASCII char
  • [^[:ascii:]] - matches a single non-ASCII char

[^[:print:]] will probably suffice for you.**

sqlalchemy: how to join several tables by one query?

Expanding on Abdul's answer, you can obtain a KeyedTuple instead of a discrete collection of rows by joining the columns:

q = Session.query(*User.__table__.columns + Document.__table__.columns).\
        select_from(User).\
        join(Document, User.email == Document.author).\
        filter(User.email == 'someemail').all()

Why is my Spring @Autowired field null?

It seems to be rare case but here is what happened to me:

We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same

@Inject
Calculator myCalculator

At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !

So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Get model's fields in Django

As per the django documentation 2.2 you can use:

To get all fields: Model._meta.get_fields()

To get an individual field: Model._meta.get_field('field name')

ex. Session._meta.get_field('expire_date')

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

You need to add icon.png through visual.

Resouces... / Dravable/ Add ///

Select second last element with css

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9

How do I serialize a C# anonymous type to a JSON string?

Assuming you are using this for a web service, you can just apply the following attribute to the class:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

Swift 3 - Comparing Date objects

Look this http://iswift.org/cookbook/compare-2-dates

Get Dates:

// Get current date
let dateA = NSDate()

// Get a later date (after a couple of milliseconds)
let dateB = NSDate()

Using SWITCH Statement

// Compare them
switch dateA.compare(dateB) {
    case .OrderedAscending     :   print("Date A is earlier than date B")
    case .OrderedDescending    :   print("Date A is later than date B")
    case .OrderedSame          :   print("The two dates are the same")
}

using IF Statement

 if dateA.compare(dateB) == .orderedAscending {
     datePickerTo.date = datePicker.date
 }

 //OR

 if case .orderedAcending = dateA.compare(dateB) {

 }

Where do I find the current C or C++ standard documents?

PDF versions of the standard

As of 1st September 2014, the best locations by price for C and C++ standards documents in PDF are:

You cannot usually get old revisions of a standard (any standard) directly from the standards bodies shortly after a new edition of the standard is released. Thus, standards for C89, C90, C99, C++98, C++03 will be hard to find for purchase from a standards body. If you need an old revision of a standard, check Techstreet as one possible source. For example, it can still provide the Canadian version CAN/CSA-ISO/IEC 9899:1990 standard in PDF, for a fee.

Non-PDF electronic versions of the standard

Print versions of the standard

Print copies of the standards are available from national standards bodies and ISO but are very expensive.

If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt's book The Annotated ANSI Standard at Amazon, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).

The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):

Standards committee draft versions (free)

The working drafts for future standards are often available from the committee websites:

If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:

For C:

(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")

For C++:

Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.

Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.


It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version.


The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers:


The current draft of the standard is maintained as LaTeX sources on Github. These sources can be converted to HTML using cxxdraft-htmlgen. The following sites maintain HTML pages so generated:

Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.

How to convert integer to decimal in SQL Server query?

select cast (height as decimal)/10 as HeightDecimal

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Years after everyone's answer, I too want to present how I did it for my project

    /// <summary>
    /// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="headers">If set to true the first row will be considered as headers</param>
    /// <returns></returns>
    public DataSet Import(string filename, bool headers = true)
    {
        var _xl = new Excel.Application();
        var wb = _xl.Workbooks.Open(filename);
        var sheets = wb.Sheets;
        DataSet dataSet = null;
        if (sheets != null && sheets.Count != 0)
        {
            dataSet = new DataSet();
            foreach (var item in sheets)
            {
                var sheet = (Excel.Worksheet)item;
                DataTable dt = null;
                if (sheet != null)
                {
                    dt = new DataTable();
                    var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                    var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[1, j + 1];
                        var column = new DataColumn(headers ? cell.Value : string.Empty);
                        dt.Columns.Add(column);
                    }

                    for (int i = 0; i < rowCount; i++)
                    {
                        var r = dt.NewRow();
                        for (int j = 0; j < ColumnCount; j++)
                        {
                            var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                            r[j] = cell.Value;
                        }
                        dt.Rows.Add(r);
                    }

                }
                dataSet.Tables.Add(dt);
            }
        }
        _xl.Quit();
        return dataSet;
    }

Chmod recursively

You can use chmod with the X mode letter (the capital X) to set the executable flag only for directories.

In the example below the executable flag is cleared and then set for all directories recursively:

~$ mkdir foo
~$ mkdir foo/bar
~$ mkdir foo/baz
~$ touch foo/x
~$ touch foo/y

~$ chmod -R go-X foo 
~$ ls -l foo
total 8
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 bar
drwxrw-r-- 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 y

~$ chmod -R go+X foo 
~$ ls -l foo
total 8
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 bar
drwxrwxr-x 2 wq wq 4096 Nov 14 15:31 baz
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 x
-rw-rw-r-- 1 wq wq    0 Nov 14 15:31 y

A bit of explaination:

  • chmod -x foo - clear the eXecutable flag for foo
  • chmod +x foo - set the eXecutable flag for foo
  • chmod go+x foo - same as above, but set the flag only for Group and Other users, don't touch the User (owner) permission
  • chmod go+X foo - same as above, but apply only to directories, don't touch files
  • chmod -R go+X foo - same as above, but do this Recursively for all subdirectories of foo

How do I rename a local Git branch?

For Locally

at first change your current branch from the branch you want to update name for example I have 3 branch branch1 , branch2 , branch3

check current branch

git branch --show-current

output may : branch1

then you can update name of branch2 and branch3 not the current one

git branch -m old_branchname new_branchname



For remote

Just three steps to replicate change in name on remote as well as on GitHub:

git branch -m old_branchname new_branchname
git push origin :old_branchname new_branchname
git push --set-upstream origin new_branchname

SVN repository backup strategies

svnbackup over at Google Code, a .NET console application.

How can I return an empty IEnumerable?

That's of course only a matter of personal preference, but I'd write this function using yield return:

public IEnumerable<Friend> FindFriends()
{
    //Many thanks to Rex-M for his help with this one.
    //http://stackoverflow.com/users/67/rex-m
    if (userExists)
    {
        foreach(var user in doc.Descendants("user"))
        {
            yield return new Friend
                {
                    ID = user.Element("id").Value,
                    Name = user.Element("name").Value,
                    URL = user.Element("url").Value,
                    Photo = user.Element("photo").Value
                }
        }
    }
}

Adding external library into Qt Creator project

I would like to add for the sake of completeness that you can also add just the LIBRARY PATH where it will look for a dependent library (which may not be directly referenced in your code but a library you use may need it).

For comparison, this would correspond to what LIBPATH environment does but its kind of obscure in Qt Creator and not well documented.

The way i came around this is following:

LIBS += -L"$$_PRO_FILE_PWD_/Path_to_Psapi_lib/"

Essentially if you don't provide the actual library name, it adds the path to where it will search dependent libraries. The difference in syntax is small but this is very useful to supply just the PATH where to look for dependent libraries. It sometime is just a pain to supply each path individual library where you know they are all in certain folder and Qt Creator will pick them up.

How to display an unordered list in two columns?

I like the solution for modern browsers, but the bullets are missing, so I add it a little trick:

http://jsfiddle.net/HP85j/419/

ul {
    list-style-type: none;
    columns: 2;
    -webkit-columns: 2;
    -moz-columns: 2;
}


li:before {
  content: "• ";
}

enter image description here

Repeat rows of a data.frame

Another way to do this would to first get row indices, append extra copies of the df, and then order by the indices:

df$index = 1:nrow(df)
df = rbind(df,df)
df = df[order(df$index),][,-ncol(df)]

Although the other solutions may be shorter, this method may be more advantageous in certain situations.

How to read input with multiple lines in Java

Use BufferedReader, you can make it read from standard input like this:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;

while ((line = stdin.readLine()) != null && line.length()!= 0) {
    String[] input = line.split(" ");
    if (input.length == 2) {
        System.out.println(calculateAnswer(input[0], input[1]));
    }
}

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):

Gen ADID

  • prepare web-page https://mypage.com/manager-login where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to https://mypage.com/statistics and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.

UPDATE

Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK https://mypage.com/access-link/ZD34jse24Sfses3J (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from https://mypage.com/statistics because it has ADID which is on servers whitelist

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

How to upload files to server using JSP/Servlet?

Introduction

To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.

Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

Don't manually parse it!

You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.

When you're already on Servlet 3.0 or newer, use native API

If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.

First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    // ...
}

Then, implement its doPost() as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
    InputStream fileContent = filePart.getInputStream();
    // ... (do your job here)
}

Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...
    List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName()) && part.getSize() > 0).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

    for (Part filePart : fileParts) {
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        // ... (do your job here)
    }
}

When you're not on Servlet 3.1 yet, manually get submitted file name

Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.

private static String getSubmittedFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
        }
    }
    return null;
}
String fileName = getSubmittedFileName(filePart);

Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

When you're not on Servlet 3.0 yet, use Apache Commons FileUpload

If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.

In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:

Your initial attempt failed most likely because you forgot the commons IO.

Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.

Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.

Workaround for GlassFish3 bug of getParameter() still returning null

Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:

private static String getValue(Part part) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        value.append(buffer, 0, length);
    }
    return value.toString();
}
String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">

Saving uploaded file (don't use getRealPath() nor part.write()!)

Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:

Serving uploaded file

Head to the following answers for detail on properly serving the saved file from disk or database back to the client:

Ajaxifying the form

Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).


Hope this all helps :)

Regular vs Context Free Grammars

I think what you want to think about are the various pumping lemmata. A regular language can be recognized by a finite automaton. A context-free language requires a stack, and a context sensitive language requires two stacks (which is equivalent to saying it requires a full Turing machine.)

So, if we think about the pumping lemma for regular languages, what it says, essentially, is that any regular language can be broken down into three pieces, x, y, and z, where all instances of the language are in xy*z (where * is Kleene repetition, ie, 0 or more copies of y.) You basically have one "nonterminal" that can be expanded.

Now, what about context-free languages? There's an analogous pumping lemma for context-free languages that breaks the strings in the language into five parts, uvxyz, and where all instances of the language are in uvixyiz, for i ≥ 0. Now, you have two "nonterminals" that can be replicated, or pumped, as long as you have the same number.

How to generate class diagram from project in Visual Studio 2013?

Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.


For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio


This feature still available, but it is NOT available by default, you have to install it separately.

  1. Open VS 2019 go to Tools -> Get Tools and Features
  2. Select the Individual components tab and search for Class Designer
  3. Select this Component and Install it, After finish installing this component (you may need to restart visual studio)
  4. Right-click on the project and select Add -> Add New Item
  5. Search for 'class' word and NOW you can see Class Diagram component

see this answer also to see an image associated

https://stackoverflow.com/a/66289543/4390133

(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)


Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)

  1. Add class diagram to the project
  2. if the option Preview Selected Items is enabled in the solution explorer, disabled it temporarily, you can re-enable it later

enter image description here

  1. open the class diagram that you created in step 2 (by double-clicking on it)
  2. drag-and-drop the project from the solution explorer to the class diagram

you could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)

Shortest way to check for null and assign another value if not

I use extention method SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

string a = null;
"A".SC(ref a);

Ways to save enums in database

I would argue that the only safe mechanism here is to use the String name() value. When writing to the DB, you could use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without "imposing" this on the DB.

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Trying to handle "back" navigation button action in iOS

The problem with didMoveToParentViewController it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.

And it doesn't work with the driven animation gesture. Using willMoveToParentViewController works better.

Objective-c

- (void)willMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        // ...
    }
}

Swift

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // ...  
    }
}

Date object to Calendar [Java]

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Date at all. You could use an approach like this:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Capitalize only first character of string and leave others alone? (Rails)

No-one's mentioned gsub, which lets you do this concisely.

string.gsub(/^([a-z])/) { $1.capitalize }

Example:

 > 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

1067 error on attempt to start MySQL

Check the file "C:\Program Files\MySQL\MySQL Server 5.1\my.ini"

The datadir line in my.ini should specify a path. Check the contents of that datadir path. Does it contain a folder named "mysql" and another folder named "test"?

If not, here are two choices:

  1. Change the datadir line in my.ini to the correct location. This will probably be C:\ProgramData\MySQL\MySQL Server 5.1\data

  2. Clean out the existing contents of your datadir path. Copy the contents of the C:\ProgramData\MySQL\MySQL Server 5.1\data to your datadir path. Restarting the mysql service should rebuild your empty database.

How can getContentResolver() be called in Android?

getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance of Context ( Activity or Service for example).

Java: how to represent graphs?

class Graph<E> {
    private List<Vertex<E>> vertices;

    private static class Vertex<E> {
        E elem;
        List<Vertex<E>> neighbors;
    }
}

Boolean.parseBoolean("1") = false...?

Java is strongly typed. 0 and 1 are numbers, which is a different type than a boolean. A number will never be equal to a boolean.

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

Adding HTML entities using CSS content

Update: PointedEars mentions that the correct stand in for &nbsp; in all css situations would be
'\a0 ' implying that the space is a terminator to the hex string and is absorbed by the escaped sequence. He further pointed out this authoritative description which sounds like a good solution to the problem I described and fixed below.

What you need to do is use the escaped unicode. Despite what you've been told \00a0 is not a perfect stand-in for &nbsp; within CSS; so try:

content:'>\a0 ';          /* or */
content:'>\0000a0';       /* because you'll find: */
content:'No\a0 Break';    /* and */
content:'No\0000a0Break'; /* becomes No&nbsp;Break as opposed to below */

Specifically using \0000a0 as &nbsp;. If you try, as suggested by mathieu and millikin:

content:'No\00a0Break'   /* becomes No&#2571;reak */

It takes the B into the hex escaped characters. The same occurs with 0-9a-fA-F.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Format of the initialization string does not conform to specification starting at index 0

I had the same problem and finally I managed to resolve it in the following way:

The problem was in the connection string definition in my web.config.

<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>

The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:

<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>

NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).

Get class name using jQuery

To complete Whitestock answer (which is the best I found) I did :

className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');

So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Yes, in your formula, you can cbind the numeric variables to be aggregated:

aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
   year month         x1          x2
1  2000     1   7.862002   -7.469298
2  2001     1 276.758209  474.384252
3  2000     2  13.122369 -128.122613
...
23 2000    12  63.436507  449.794454
24 2001    12 999.472226  922.726589

See ?aggregate, the formula argument and the examples.

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I just uninstalled my Java8 update and tried again. It worked ok!

c# dictionary How to add multiple values for single key?

You could use my implementation of a multimap, which derives from a Dictionary<K, List<V>>. It is not perfect, however it does a good job.

/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

    public MultiMap()
        : base()
    {
    }

    public MultiMap(int capacity)
        : base(capacity)
    {
    }

    /// <summary>
    /// Adds an element with the specified key and value into the MultiMap. 
    /// </summary>
    /// <param name="key">The key of the element to add.</param>
    /// <param name="value">The value of the element to add.</param>
    public void Add(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            valueList.Add(value);
        } else {
            valueList = new List<TValue>();
            valueList.Add(value);
            Add(key, valueList);
        }
    }

    /// <summary>
    /// Removes first occurence of an element with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <param name="value">The value of the element to remove.</param>
    /// <returns>true if the an element is removed;
    /// false if the key or the value were not found.</returns>
    public bool Remove(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            if (valueList.Remove(value)) {
                if (valueList.Count == 0) {
                    Remove(key);
                }
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Removes all occurences of elements with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the elements to remove.</param>
    /// <param name="value">The value of the elements to remove.</param>
    /// <returns>Number of elements removed.</returns>
    public int RemoveAll(TKey key, TValue value)
    {
        List<TValue> valueList;
        int n = 0;

        if (TryGetValue(key, out valueList)) {
            while (valueList.Remove(value)) {
                n++;
            }
            if (valueList.Count == 0) {
                Remove(key);
            }
        }
        return n;
    }

    /// <summary>
    /// Gets the total number of values contained in the MultiMap.
    /// </summary>
    public int CountAll
    {
        get
        {
            int n = 0;

            foreach (List<TValue> valueList in Values) {
                n += valueList.Count;
            }
            return n;
        }
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific
    /// key / value pair.
    /// </summary>
    /// <param name="key">Key of the element to search for.</param>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            return valueList.Contains(value);
        }
        return false;
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific value.
    /// </summary>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TValue value)
    {
        foreach (List<TValue> valueList in Values) {
            if (valueList.Contains(value)) {
                return true;
            }
        }
        return false;
    }

}

Note that the Add method looks if a key is already present. If the key is new, a new list is created, the value is added to the list and the list is added to the dictionary. If the key was already present, the new value is added to the existing list.

How to install a Notepad++ plugin offline?

For me the with NPP V7.6.6 (x64) this worked:

  1. Download the plugin, and unzip to some local folder (e.g. Downloads). Make sure you download the correct plugin for your Notepad++ (64 or 32 bit - e.g. see ? -> About Notepad++ to find if you are 64-bit)

  2. Check each DLL to ensure it is unblocked (right-click, Properties, and check/select Unblock.

  3. Run Notepad++. If you have UAC enabled, use "Run as Administrator" to run Notepad++ (Hold Shift key down, right-click Notepad++ icon, and select "Run as Administrator").

  4. Go to menu Settings -> Import -> Import plugins...

  5. Use dialog displayed to locate you local copy of the plugin DLL.

  6. Once plugin DLL has been selected, Notepad++ should tell you you need to restart. If it doesn't, then Notepad++ has had some problem - though it doesn't tell you what...!

  7. Restart Notepad++.

The above causes a copy of the plugin DLL to be copied under a subfolder of the same name in C:\Program Files\Notepad++\plugins.

Putting plugins directly into one of the following folders (or sub-folders for each plugin), as suggested in other answers, did not work for me:

a) %PROGRAMDATA%\Notepad++\plugins. b) %ALLDATA%\Notepad++\plugins.

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

Java Refuses to Start - Could not reserve enough space for object heap

I wrote two applications, one medium sized, and the other, fairly small. I'd fire up the medium sized one (on linux, centos), without any args, (java server), and it would run just fine. But when I then fired up the smaller app with "java client", it would tell me it couldn't reserve enough space, and wouldn't run. I experimented, and used the -Xms and -Xmx both with 10m, and they would both run without complaint... Go figure!

Symbol for any number of any characters in regex?

You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.

[\s\S]*

This expression will match as few as possible, but as many as necessary for the rest of the expression.

[\s\S]*?

For example, in this regex [\s\S]*?B will match aB in aBaaaaB. But in this regex [\s\S]*B will match aBaaaaB in aBaaaaB.

SQL Server - Case Statement

The query can be written slightly simpler, like this:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T

PHP Warning: Division by zero

You can try with this. You have this error because we can not divide by 'zero' (0) value. So we want to validate before when we do calculations.

if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL) 
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}

And also we can validate POST data. Refer following

$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;

$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;

$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;

$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;

Accessing variables from other functions without using global variables

To make a variable calculated in function A visible in function B, you have three choices:

  • make it a global,
  • make it an object property, or
  • pass it as a parameter when calling B from A.

If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:

function A()
{
    var rand_num = calculate_random_number();
    B(rand_num);
}

function B(r)
{
    use_rand_num(r);
}

How to send parameters with jquery $.get()

This is what worked for me:

$.get({
    method: 'GET',
    url: 'api.php',
    headers: {
        'Content-Type': 'application/json',
    },
    // query parameters go under "data" as an Object
    data: {
        client: 'mikescafe'
    }
});

will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe

Good Luck.

What is your most productive shortcut with Vim?

Vim Plugins

There are a lot of good answers here, and one amazing one about the zen of vi. One thing I don't see mentioned is that vim is extremely extensible via plugins. There are scripts and plugins to make it do all kinds of crazy things the original author never considered. Here are a few examples of incredibly handy vim plugins:

rails.vim

Rails.vim is a plugin written by tpope. It's an incredible tool for people doing rails development. It does magical context-sensitive things that allow you to easily jump from a method in a controller to the associated view, over to a model, and down to unit tests for that model. It has saved dozens if not hundreds of hours as a rails developer.

gist.vim

This plugin allows you to select a region of text in visual mode and type a quick command to post it to gist.github.com. This allows for easy pastebin access, which is incredibly handy if you're collaborating with someone over IRC or IM.

space.vim

This plugin provides special functionality to the spacebar. It turns the spacebar into something analogous to the period, but instead of repeating actions it repeats motions. This can be very handy for moving quickly through a file in a way you define on the fly.

surround.vim

This plugin gives you the ability to work with text that is delimited in some fashion. It gives you objects which denote things inside of parens, things inside of quotes, etc. It can come in handy for manipulating delimited text.

supertab.vim

This script brings fancy tab completion functionality to vim. The autocomplete stuff is already there in the core of vim, but this brings it to a quick tab rather than multiple different multikey shortcuts. Very handy, and incredibly fun to use. While it's not VS's intellisense, it's a great step and brings a great deal of the functionality you'd like to expect from a tab completion tool.

syntastic.vim

This tool brings external syntax checking commands into vim. I haven't used it personally, but I've heard great things about it and the concept is hard to beat. Checking syntax without having to do it manually is a great time saver and can help you catch syntactic bugs as you introduce them rather than when you finally stop to test.

fugitive.vim

Direct access to git from inside of vim. Again, I haven't used this plugin, but I can see the utility. Unfortunately I'm in a culture where svn is considered "new", so I won't likely see git at work for quite some time.

nerdtree.vim

A tree browser for vim. I started using this recently, and it's really handy. It lets you put a treeview in a vertical split and open files easily. This is great for a project with a lot of source files you frequently jump between.

FuzzyFinderTextmate.vim

This is an unmaintained plugin, but still incredibly useful. It provides the ability to open files using a "fuzzy" descriptive syntax. It means that in a sparse tree of files you need only type enough characters to disambiguate the files you're interested in from the rest of the cruft.

Conclusion

There are a lot of incredible tools available for vim. I'm sure I've only scratched the surface here, and it's well worth searching for tools applicable to your domain. The combination of traditional vi's powerful toolset, vim's improvements on it, and plugins which extend vim even further, it's one of the most powerful ways to edit text ever conceived. Vim is easily as powerful as emacs, eclipse, visual studio, and textmate.

Thanks

Thanks to duwanis for his vim configs from which I have learned much and borrowed most of the plugins listed here.

git error: failed to push some refs to remote

Well if none of the above answers are working and if you have messed up something with ssh-add lately. Try

ssh-add -D

How to set maximum height for table-cell?

By CSS 2.1 rules, the height of a table cell is “the minimum height required by the content”. Thus, you need to restrict the height indirectly using inner markup, normally a div element (<td><div>content</div></td>), and set height and overflow properties on the the div element (without setting display: table-cell on it, of course, as that would make its height obey CSS 2.1 table cell rules).

Create HTML table using Javascript

The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.

Instead of writing your table line by line, concatenate your table into a variable and insert it once created:

<script language="javascript" type="text/javascript">
<!--

var myArray    = new Array();
    myArray[0] = 1;
    myArray[1] = 2.218;
    myArray[2] = 33;
    myArray[3] = 114.94;
    myArray[4] = 5;
    myArray[5] = 33;
    myArray[6] = 114.980;
    myArray[7] = 5;

    var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
    myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
    myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";

    myTable+="<tr><td style='width: 100px;                   '>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td></tr>";

  for (var i=0; i<8; i++) {
    myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
    myArray[i] = myArray[i].toFixed(3);
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
  }  
   myTable+="</table>";

 document.write( myTable);

//-->
</script> 

If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:

<div id="tablePrint"> </div>

And in JS instead of document.write(myTable) use the following code:

document.getElementById('tablePrint').innerHTML = myTable;

Open JQuery Datepicker by clicking on an image w/ no input field

HTML:

<div class="CalendarBlock">
    <input type="hidden">
</div>

CODE:

$CalendarBlock=$('.CalendarBlock');
$CalendarBlock.click(function(){
    var $datepicker=$(this).find('input');
    datepicker.datepicker({dateFormat: 'mm/dd/yy'});
    $datepicker.focus(); });

When to use static classes in C#

Static classes are very useful and have a place, for example libraries.

The best example I can provide is the .Net Math class, a System namespace static class that contains a library of maths functions.

It is like anything else, use the right tool for the job, and if not anything can be abused.

Blankly dismissing static classes as wrong, don't use them, or saying "there can be only one" or none, is as wrong as over using the them.

C#.Net contains a number of static classes that is uses just like the Math class.

So given the correct implementation they are tremendously useful.

We have a static TimeZone class that contains a number of business related timezone functions, there is no need to create multiple instances of the class so much like the Math class it contains a set of globally accesible TimeZone realated functions (methods) in a static class.

How to programmatically determine the current checked out Git branch

I found two really simple ways to do that:

$ git status | head -1 | cut -d ' ' -f 4

and

$ git branch | grep "*" | cut -d ' ' -f 2

Get the row(s) which have the max value in groups using groupby

df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Let's revisit key phases of Mapreduce program.

The map phase is done by mappers. Mappers run on unsorted input key/values pairs. Each mapper emits zero, one, or multiple output key/value pairs for each input key/value pairs.

The combine phase is done by combiners. The combiner should combine key/value pairs with the same key. Each combiner may run zero, once, or multiple times.

The shuffle and sort phase is done by the framework. Data from all mappers are grouped by the key, split among reducers and sorted by the key. Each reducer obtains all values associated with the same key. The programmer may supply custom compare functions for sorting and a partitioner for data split.

The partitioner decides which reducer will get a particular key value pair.

The reducer obtains sorted key/[values list] pairs, sorted by the key. The value list contains all values with the same key produced by mappers. Each reducer emits zero, one or multiple output key/value pairs for each input key/value pair.

Have a look at this javacodegeeks article by Maria Jurcovicova and mssqltips article by Datta for a better understanding

Below is the image from safaribooksonline article

enter image description here

TypeError: Missing 1 required positional argument: 'self'

You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

So, simply call Pump.getPumps() .

In java, it is termed as static method.

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList();

    List<Address> allAddresses = GetAllAddresses();
    List<Employee> employees = GetAllEmployees(); // count > 1000

    List<Address> addresses = new List<Address>();

    for (int i = 0; i < employees.Count; i += 1000)
    {
        int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000;
        var query = (from address in allAddresses
                     where employees.GetRange(i, count).Contains(address.EmployeeId)
                     && address.State == "UT"
                     select address).ToList();

        addresses.AddRange(query);
    }

Hope this helps someone.

BEGIN - END block atomic transactions in PL/SQL

The default behavior of Commit PL/SQL block:

You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.

For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.

https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105

How to send password securely over HTTP?

Using HTTP with SSL will make your life much easier and you can rest at ease very smart people (smarter than me at least!) have scrutinized this method of confidential communication for years.

Visual Studio popup: "the operation could not be completed"

I was upgrading to .NET4.6 from a 3rd party app (unity3d). I would get this message when I tried to reload the solution when it wouldn't load on startup. My solution was right clicking the solution and selecting "install missing features" which prompted me to download what I needed. The download on the popup didn't work so I just installed the .NET targeting pack for what I was on (4.6) and this fixed it.

Change remote repository credentials (authentication) on Intellij IDEA 14

The easiest of all the above ways is to:

  1. Go to Settings>>Appearance & Behavior>>System Settings>>Passwords
  2. Change the setting to not store passwords at all
  3. Invalidate and restart IntelliJ
  4. Go to Settings>>Version Control>>Git>>SSH executable: Build-in
  5. Do a fetch/pull operation
  6. Enter the password when prompted
  7. Again go to Settings>>Appearance & Behavior>>System Settings>>Passwords
  8. This time select store passwords on disk(protected with master password)

Voila!

Note that this will not work if your password is in your URL itself. If that is the case then you need to follow the steps given by @moleksyuk here

You also choose to use the credentials helper option in IntelliJ to achieve similar functionality as suggested by Ramesh here

C++ callback using class member

Here's a concise version that works with class method callbacks and with regular function callbacks. In this example, to show how parameters are handled, the callback function takes two parameters: bool and int.

class Caller {
  template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
  {
    using namespace std::placeholders; 
    callbacks_.emplace_back(std::bind(mf, object, _1, _2));
  }
  void addCallback(void(* const fun)(bool,int)) 
  {
    callbacks_.emplace_back(fun);
  }
  void callCallbacks(bool firstval, int secondval) 
  {
    for (const auto& cb : callbacks_)
      cb(firstval, secondval);
  }
private:
  std::vector<std::function<void(bool,int)>> callbacks_;
}

class Callee {
  void MyFunction(bool,int);
}

//then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`

ptr->addCallback(this, &Callee::MyFunction);

//or to add a call back to a regular function
ptr->addCallback(&MyRegularFunction);

This restricts the C++11-specific code to the addCallback method and private data in class Caller. To me, at least, this minimizes the chance of making mistakes when implementing it.

When to use Task.Delay, when to use Thread.Sleep?

Use Thread.Sleep when you want to block the current thread.

Use Task.Delay when you want a logical delay without blocking the current thread.

Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.

Storing Python dictionaries

Minimal example, writing directly to a file:

import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))

or safely opening / closing:

import json
with open(filename, 'wb') as outfile:
    json.dump(data, outfile)
with open(filename) as infile:
    data = json.load(infile)

If you want to save it in a string instead of a file:

import json
json_str = json.dumps(data)
data = json.loads(json_str)

How to insert a picture into Excel at a specified cell position with VBA

I tested both @SWa and @Teamothy solution. I did not find the Pictures.Insert Method in the Microsoft Documentations and feared some compatibility issues. So I guess, the older Shapes.AddPicture Method should work on all versions. But it is slow!

On Error Resume Next
'
' first and faster method (in Office 2016)
'
    With ws.Pictures.Insert(Filename:=imageFileName, LinkToFile:=msoTrue, SaveWithDocument:=msoTrue)
        With .ShapeRange
            .LockAspectRatio = msoTrue
            .Width = destRange.Width
            .height = destRange.height '222
        End With
        .Left = destRange.Left
        .Top = destRange.Top
        .Placement = 1
        .PrintObject = True
        .Name = imageName
    End With
'
' second but slower method (in Office 2016)
'

If Err.Number <> 0 Then
    Err.Clear
    Dim myPic As Shape
    Set myPic = ws.Shapes.AddPicture(Filename:=imageFileName, _
            LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
            Left:=destRange.Left, Top:=destRange.Top, Width:=-1, height:=destRange.height)

    With myPic.OLEFormat.Object.ShapeRange
        .LockAspectRatio = msoTrue
        .Width = destRange.Width
        .height = destRange.height '222
    End With
End If

How can I get my Twitter Bootstrap buttons to right align?

for bootstrap 4 documentation

  <div class="row justify-content-end">
    <div class="col-4">
      Start of the row
    </div>
    <div class="col-4">
      End of the row
    </div>
  </div>

How to cd into a directory with space in the name?

To change to a directory with spaces on the name you just have to type like this:

cd My\ Documents

Hit enter and you will be good

How to display a JSON representation and not [Object Object] on the screen

If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:

<li *ngFor="let obj of myArray">{{obj | json}}</li>

Tested and valid using Angular 4.3.2.

How to pipe list of files returned by find command to cat to view all the files

Use ggrep.

ggrep -H -R -I "mysearchstring" *

to search for a file in unix containing text located in the current directory or a subdirectory

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?

Just read your exception stacktrace:

Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

So it seems that you are using the Microsoft.Web.Helpers which in turn depends on System.Web.WebPages.Razor, Version=2.0.0.0.

angular.js ng-repeat li items with html content

ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:

HTML-side: (the same as the accepted answer stated):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

But in the controller-side:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Java parsing XML document gives "Content not allowed in prolog." error

I assume you have proper xml encoding and matching with Schema.

If you still get this error, check code that unmarshalls the xml and input type you have used. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that XML processor can correctly handle the declared encoding [Ref Book: Java in A Nutshell ]

Hope this helps!

How to plot a function curve in R

I did some searching on the web, and this are some ways that I found:

The easiest way is using curve without predefined function

curve(x^2, from=1, to=50, , xlab="x", ylab="y")

enter image description here

You can also use curve when you have a predfined function

eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")

enter image description here

If you want to use ggplot,

library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=eq)

enter image description here

Getting value from a cell from a gridview on RowDataBound event

Regarding the index selection style of the columns i suggest you do the following. i ran into this problem but i was going to set values dynamically using an API so what i did was this : keep in mind .CastTo<T> is simply ((T)e.Row.DataItem)

and you have to call DataBind() in order to see the changes in the grid. this way you wont run into issues if you decide to add a column to the grid.

 protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType == DataControlRowType.DataRow)
            {
                var number = e.Row.DataItem.CastTo<DataRowView>().Row["number"];
                e.Row.DataItem.CastTo<DataRowView>().Row["ActivationDate"] = DateTime.Parse(userData.basic_info.creation_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["ExpirationDate"] = DateTime.Parse(userData.basic_info.nearest_exp_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["Remainder"] = Convert.ToDecimal(userData.basic_info.credit).ToStringWithSeparator();

                e.Row.DataBind();
            }
        }

Installing packages in Sublime Text 2

You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).

Then please check Package Docs Control Usage for Basic Functionality:

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

The command pallete will now show a number of commands. Most users will be interested in the following:

Install Package

Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.

Get current folder path

This works best for me, especially when using dotnet core single file publish. Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).

How can I selectively merge or pick changes from another branch in Git?

I like the previous 'git-interactive-merge' answer, but there's one easier. Let Git do this for you using a rebase combination of interactive and onto:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o master

So the case is you want C1 and C2 from the 'feature' branch (branch point 'A'), but none of the rest for now.

# git branch temp feature
# git checkout master
# git rebase -i --onto HEAD A temp

Which, as in the previous answer, drops you in to the interactive editor where you select the 'pick' lines for C1 and C2 (as above). Save and quit, and then it will proceed with the rebase and give you branch 'temp' and also HEAD at master + C1 + C2:

      A---C1---o---C2---o---o feature
     /
----o---o---o---o-master--C1---C2 [HEAD, temp]

Then you can just update master to HEAD and delete the temp branch and you're good to go:

# git branch -f master HEAD
# git branch -d temp

What is the difference between `git merge` and `git merge --no-ff`?

Graphic answer to this question

Here is a site with a clear explanation and graphical illustration of using git merge --no-ff:

difference between git merge --no-ff and git merge

Until I saw this, I was completely lost with git. Using --no-ff allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.


Basic info for newbs like me

If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.


Example Workflow

I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.

My workflow of git commands:

git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am  "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master

Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.

$ git status
# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   ecc/Desktop.php
#       modified:   ecc/Mobile.php
#       deleted:    ecc/ecc-config.php
#       modified:   ecc/readme.txt
#       modified:   ecc/test.php
#       deleted:    passthru-adapter.igs
#       deleted:    shop/mickey/index.php
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       ecc/upgrade.php
#       ecc/webgility-config.php
#       ecc/webgility-config.php.bak
#       ecc/webgility-magento.php

Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc folder) I deleted independent of this change. Instead of confusing those file deletions with ecc, I'll make a different cleanup branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.

Below: rather than do the all-inclusive git commit -am "updated ecc package" I normally would, I only wanted to add the files in the /ecc folder. Those deleted files weren't specifically part of my git add, but because they already were tracked in git, I need to remove them from this branch's commit:

$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M       passthru-adapter.igs
M       shop/mickey/index.php

$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"

$ git checkout master
D       passthru-adapter.igs
D       shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
   8a0d9ec..333eff5  master -> master



Script for automating the above

Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message"> script for doing the above steps. Here is the Gist source for that script.

Instead of git commit -am I am selecting files from the "modified" list produced via git status and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.

How can I include all JavaScript files in a directory via JavaScript file?

In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.

If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.

Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.

MD5 is 128 bits but why is it 32 characters?

That's 32 hex characters - 1 hex character is 4 bits.

Can I delete a git commit but keep the changes?

You're looking for either git reset HEAD^ --soft or git reset HEAD^ --mixed.

There are 3 modes to the reset command as stated in the docs:

git reset HEAD^ --soft

undo the git commit. Changes still exist in the working tree(the project folder) + the index (--cached)

git reset HEAD^ --mixed

undo git commit + git add. Changes still exist in the working tree

git reset HEAD^ --hard

Like you never made these changes to the codebase. Changes are gone from the working tree.

Need to list all triggers in SQL Server database with table name and table's schema

One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet. example

SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
 ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;

you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Converting ISO 8601-compliant String to java.util.Date

I faced the same problem and solved it by the following code .

 public static Calendar getCalendarFromISO(String datestring) {
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()) ;
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    try {
        Date date = dateformat.parse(datestring);
        date.setHours(date.getHours() - 1);
        calendar.setTime(date);

        String test = dateformat.format(calendar.getTime());
        Log.e("TEST_TIME", test);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return calendar;
}

Earlier I was using SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());

But later i found the main cause of the exception was the yyyy-MM-dd'T'HH:mm:ss.SSSZ ,

So i used

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());

It worked fine for me .

After installing with pip, "jupyter: command not found"

Here what I did on Linux mint 19:

I installed jupyter with:

pip install jupyter

and command:

jupyter notebook

didn't work, so with:

sudo apt install jupyter-notebook

I fixed the issue, jupyter notebook worked then.

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

matplotlib: Group boxplots

Grouped boxplots, towards subtle academic publication styling... (source)

(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.

grouped boxplot example png for Python 2.7.12 Matplotlib v1.5.3 grouped boxplot example png for Python 3.7.3 Matplotlib v3.1.0

Code:

import numpy as np
import matplotlib.pyplot as plt

# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]

# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]

# --- Labels for your data:
labels_list = ['a','b']
xlocations  = range(len(data_group1))
width       = 0.3
symbol      = 'r+'
ymin        = 0
ymax        = 10

ax = plt.gca()
ax.set_ylim(ymin,ymax)
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
ax.set_axisbelow(True)
ax.set_xticks(xlocations)
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.title('title')

# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations

plt.boxplot(data_group1, 
            sym=symbol,
            labels=['']*len(labels_list),
            positions=positions_group1, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.boxplot(data_group2, 
            labels=labels_list,
            sym=symbol,
            positions=positions_group2, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.savefig('boxplot_grouped.png')  
plt.savefig('boxplot_grouped.pdf')    # when publishing, use high quality PDFs
#plt.show()                   # uncomment to show the plot. 

Get Number of Rows returned by ResultSet in Java

You can use res.previous() as follows:

ResulerSet res = getDate();
if(!res.next()) {
    System.out.println("No Data Found.");
} else {
    res.previous();
    while(res.next()) {
      //code to display the data in the table.
    }
}

How to watch for form changes in Angular

To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.

Observables allow not only to use the subscribe method (something similar to the then method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.

I mean you can specify at this level the debounce time with the debounceTime method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:

this.form.valueChanges
    .debounceTime(500)
    .subscribe(data => console.log('form changes', data));

You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap method:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

You even go further by linking the returned observable directly to a property of your component:

this.list = this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

and display it using the async pipe:

<ul>
  <li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>

Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).

Hope it helps you, Thierry

inherit from two classes in C#

An common alternative to inheritance is delegation (also called composition): X "has a" Y rather than X "is a" Y. So if A has functionality for dealing with Foos, and B has functionality for dealing with Bars, and you want both in C, then something like this:

public class A() {
  private FooManager fooManager = new FooManager(); // (or inject, if you have IoC)

  public void handleFoo(Foo foo) {
    fooManager.handleFoo(foo);
  }
}

public class B() {
  private BarManager barManager = new BarManager(); // (or inject, if you have IoC)

  public void handleBar(Bar bar) {
    barManager.handleBar(bar);
  }
}

public class C() {
  private FooManager fooManager = new FooManager(); // (or inject, if you have IoC)
  private BarManager barManager = new BarManager(); // (or inject, if you have IoC)

  ... etc
}

Is there a way to detect if a browser window is not currently active?

I create a Comet Chat for my app, and when I receive a message from another user I use:

if(new_message){
    if(!document.hasFocus()){
        audio.play();
        document.title="Have new messages";
    }
    else{
        audio.stop();
        document.title="Application Name";
    } 
}

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

Check if a number has a decimal place/is a whole number

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

Embedding a media player in a website using HTML

Definitely the HTML5 element is the way to go. There's at least basic support for it in the most recent versions of almost all browsers:

http://caniuse.com/#feat=audio

And it allows to specify what to do when the element is not supported by the browser. For example you could add a link to a file by doing:

<audio controls src="intro.mp3">
   <a href="intro.mp3">Introduction to HTML5 (10:12) - MP3 - 3.2MB</a>
</audio>

You can find this examples and more information about the audio element in the following link:

http://hacks.mozilla.org/2012/04/enhanceyourhtml5appwithaudio/

Finally, the good news are that mozilla's April's dev Derby is about this element so that's probably going to provide loads of great examples of how to make the most out of this element:

http://hacks.mozilla.org/2012/04/april-dev-derby-show-us-what-you-can-do-with-html5-audio/

The ternary (conditional) operator in C

Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const correctness in a compact way.

Something like this:

const int n = (x != 0) ? 10 : 20;

so basically n is a const whose initial value is dependent on a condition statement. The easiest alternative is to make n not a const, this would allow an ordinary if to initialize it. But if you want it to be const, it cannot be done with an ordinary if. The best substitute you could make would be to use a helper function like this:

int f(int x) {
    if(x != 0) { return 10; } else { return 20; }
}

const int n = f(x);

but the ternary if version is far more compact and arguably more readable.

Getting the parent div of element

I had to do recently something similar, I used this snippet:

const getNode = () =>
  for (let el = this.$el; el && el.parentNode; el = el.parentNode){
    if (/* insert your condition here */) return el;
  }
  return null
})

The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null

In case somebody would look for multiple elements it only returns closest parent to the element that you provided.

My example was:

if (el.classList?.contains('o-modal')) return el;

I used it in a vue component (this.$el) change that to your document.getElementById function and you're good to go. Hope it will be useful for some people ??

Using % for host when creating a MySQL user

Let's just test.

Connect as superuser, and then:

SHOW VARIABLES LIKE "%version%"; 
+-------------------------+------------------------------+ 
| Variable_name           | Value                        | 
+-------------------------+------------------------------+ 
| version                 | 10.0.23-MariaDB-0+deb8u1-log | 

and then

USE mysql;

Setup

Create a user foo with password bar for testing:

CREATE USER foo@'%' IDENTIFIED BY 'bar'; FLUSH PRIVILEGES;

Connect

To connect to the Unix Domain Socket (i.e. the I/O pipe that is named by the filesystem entry /var/run/mysqld/mysqld.sock or some such), run this on the command line (use the --protocol option to make doubly sure)

mysql -pbar -ufoo
mysql -pbar -ufoo --protocol=SOCKET

One expects that the above matches "user comes from localhost" but certainly not "user comes from 127.0.0.1".

To connect to the server from "127.0.0.1" instead, run this on the command line

mysql -pbar -ufoo --bind-address=127.0.0.1 --protocol=TCP

If you leave out --protocol=TCP, the mysql command will still try to use the Unix domain socket. You can also say:

mysql -pbar -ufoo --bind-address=127.0.0.1 --host=127.0.0.1

The two connection attempts in one line:

export MYSQL_PWD=bar; \
mysql -ufoo --protocol=SOCKET --execute="SELECT 1"; \
mysql -ufoo --bind-address=127.0.0.1 --host=127.0.0.1 --execute="SELECT 1"

(the password is set in the environment so that it is passed to the mysql process)

Verification In Case Of Doubt

To really check whether the connection goes via a TCP/IP socket or a Unix Domain socket

  1. get the PID of the mysql client process by examining the output of ps faux
  2. run lsof -n -p<yourpid>.

You will see something like:

mysql [PID] quux 3u IPv4 [code] 0t0 TCP 127.0.0.1:[port]->127.0.0.1:mysql (ESTABLISHED)

or

mysql [PID] quux 3u unix [code] 0t0 [code] socket

So:

Case 0: Host = '10.10.10.10' (null test)

update user set host='10.10.10.10' where user='foo'; flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Case 1: Host = '%'

update user set host='%' where user='foo'; flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

Case 2: Host = 'localhost'

update user set host='localhost' where user='foo';flush privileges;

Behaviour varies and this apparently depends on skip-name-resolve. If set, causes lines with localhost to be ignored according to the log. The following can be seen in the error log: "'user' entry 'root@localhost' ignored in --skip-name-resolve mode.". This means no connecting through the Unix Domain Socket. But this is empirically not the case. localhost now means ONLY the Unix Domain Socket, and no longer matched 127.0.0.1.

skip-name-resolve is off:

  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

skip-name-resolve is on:

  • Connect using socket: OK
  • Connect from 127.0.0.1: FAILURE

Case 3: Host = '127.0.0.1'

update user set host='127.0.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: OK

Case 4: Host = ''

update user set host='' where user='foo';flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

(According to MySQL 5.7: 6.2.4 Access Control, Stage 1: Connection Verification, The empty string '' also means “any host” but sorts after '%'. )

Case 5: Host = '192.168.0.1' (extra test)

('192.168.0.1' is one of my machine's IP addresses, change appropriately in your case)

update user set host='192.168.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

but

  • Connect using mysql -pbar -ufoo -h192.168.0.1: OK (!)

The latter because this is actually TCP connection coming from 192.168.0.1, as revealed by lsof:

TCP 192.168.0.1:37059->192.168.0.1:mysql (ESTABLISHED)

Edge Case A: Host = '0.0.0.0'

update user set host='0.0.0.0' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case B: Host = '255.255.255.255'

update user set host='255.255.255.255' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case C: Host = '127.0.0.2'

(127.0.0.2 is perfectly valid loopback address equivalent to 127.0.0.1 as defined in RFC6890)

update user set host='127.0.0.2' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Interestingly:

  • mysql -pbar -ufoo -h127.0.0.2 connects from 127.0.0.1 and is FAILURE
  • mysql -pbar -ufoo -h127.0.0.2 --bind-address=127.0.0.2 is OK

Cleanup

delete from user where user='foo';flush privileges;

Addendum

To see what is actually in the mysql.user table, which is one of the permission tables, use:

SELECT SUBSTR(password,1,6) as password, user, host,
Super_priv AS su,
Grant_priv as gr,
CONCAT(Select_priv, Lock_tables_priv) AS selock,
CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif,
CONCAT(References_priv, Index_priv, Alter_priv) AS ria,
CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views,
CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) AS funcs,
CONCAT(Repl_slave_priv, Repl_client_priv) AS replic,
CONCAT(Shutdown_priv, Process_priv, File_priv, Show_db_priv, Reload_priv, Create_user_priv) AS admin
FROM user ORDER BY user, host;

this gives:

+----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | password | user     | host      | su | gr | selock | modif | ria | views | funcs | replic | admin  |
    +----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | *E8D46   | foo      |           | N  | N  | NN     | NNNNN | NNN | NNN   | NNNNN | NN     | NNNNNN |

Similarly for table mysql.db:

SELECT host,db,user, 
       Grant_priv as gr,
       CONCAT(Select_priv, Lock_tables_priv) AS selock, 
       CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif, 
       CONCAT(References_priv, Index_priv, Alter_priv) AS ria, 
       CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views, 
       CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv) AS funcs 
       FROM db ORDER BY user, db, host;

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

Check status of one port on remote host

In Bash, you can use pseudo-device files which can open a TCP connection to the associated socket. The syntax is /dev/$tcp_udp/$host_ip/$port.

Here is simple example to test whether Memcached is running:

</dev/tcp/localhost/11211 && echo Port open || echo Port closed

Here is another test to see if specific website is accessible:

$ echo "HEAD / HTTP/1.0" > /dev/tcp/example.com/80 && echo Connection successful.
Connection successful.

For more info, check: Advanced Bash-Scripting Guide: Chapter 29. /dev and /proc.

Related: Test if a port on a remote system is reachable (without telnet) at SuperUser.

For more examples, see: How to open a TCP/UDP socket in a bash shell (article).

Is there any way to do HTTP PUT in python

Httplib seems like a cleaner choice.

import httplib
connection =  httplib.HTTPConnection('1.2.3.4:1234')
body_content = 'BODY CONTENT GOES HERE'
connection.request('PUT', '/url/path/to/put/to', body_content)
result = connection.getresponse()
# Now result.status and result.reason contains interesting stuff

Removing viewcontrollers from navigation stack

Use this code and enjoy:

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

// [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.
[navigationArray removeObjectAtIndex: 2];  // You can pass your index here
self.navigationController.viewControllers = navigationArray;
[navigationArray release];

Hope this will help you.

Edit: Swift Code

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
navigationArray.remove(at: navigationArray.count - 2) // To remove previous UIViewController
self.navigationController?.viewControllers = navigationArray

Edit: To remove all ViewController except last one -> no Back Button in the upper left corner

guard let navigationController = self.navigationController else { return }
var navigationArray = navigationController.viewControllers // To get all UIViewController stack as Array
let temp = navigationArray.last
navigationArray.removeAll()
navigationArray.append(temp!) //To remove all previous UIViewController except the last one
self.navigationController?.viewControllers = navigationArray

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

Pythonic way to find maximum value and its index in a list?

max([(v,i) for i,v in enumerate(my_list)])

scp files from local to remote machine error: no such file or directory

Your problem can be caused by different things. I will provide you three possible scenarios in Linux:

  • The File location

When you use scp name , you mean that your File name is in Home directory. When it is in Home but inside in another Folder, for example, my_folder, you should write:

scp /home/my-username/my_folder/name [email protected]:/Path....
  • You File Permission

You must know the File Permission your File has. If you have Read-only you should change it.

To change the Permission:

As Root ,sudo caja ( the default file manager for the MATE Desktop) or another file manager ,then with you Mouse , right-click to the File name , select Properties + Permissions and change it on Group and Other to Read and write .

Or with chmod .

  • You Port Number

Maybe you remote machine or Server can only communicate with a Port Number, so you should write -P and the Port Number.

scp -P 22 /home/my-username/my_folder/name [email protected] /var/www/html

Get index of current item in a PowerShell loop

For those coming here from Google like I did, later versions of Powershell have a $foreach automatic variable. You can find the "current" object with $foreach.Current

Google Maps JavaScript API RefererNotAllowedMapError

I got mine working finally by using this tip from Google: (https://support.google.com/webmasters/answer/35179)

Here are our definitions of domain and site. These definitions are specific to Search Console verification:

http://example.com/ - A site (because it includes the http:// prefix)
example.com/ - A domain (because it doesn't include a protocol prefix)
puppies.example.com/ - A subdomain of example.com
http://example.com/petstore/ - A subdirectory of http://example.com site

Mock MVC - Add Request Parameter to test

@ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

What is the C# version of VB.net's InputDialog?

There is no such thing: I recommend to write it for yourself and use it whenever you need.

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

Access denied for user 'test'@'localhost' (using password: YES) except root user

In my case the same error happen because I was trying to use mysql by just typing "mysql" instead of "mysql -u root -p"

Javascript to stop HTML5 video playback on modal window close

I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.

$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});

How to get pip to work behind a proxy server

On Ubuntu, you can set proxy by using

export http_proxy=http://username:password@proxy:port
export https_proxy=http://username:password@proxy:port

or if you are having SOCKS error use

export all_proxy=http://username:password@proxy:port

Then run pip

sudo -E pip3 install {packageName}

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

Laravel - Forbidden You don't have permission to access / on this server

I had a problem with non-www website URL version - the PUT method has been not working. But when entering the website with www. - it works fine!

How can I send an Ajax Request on button click from a form with 2 buttons?

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});

How to transfer data from JSP to servlet when submitting HTML form

http://oreilly.com/catalog/javacook/chapter/ch18.html

Search for :

"Problem

You want to process the data from an HTML form in a servlet. "

Change some value inside the List<T>

You can do something like this:

var newList = list.Where(w => w.Name == "height")
              .Select(s => new {s.Name, s.Value= 30 }).ToList();

But I would rather choose to use foreach because LINQ is for querying while you want to edit the data.

What is Dispatcher Servlet in Spring?

Dispatcher Controller are displayed in the figure all the incoming request is in intercepted by the dispatcher servlet that works as front controller. The dispatcher servlet gets an entry to handler mapping from the XML file and forwords the request to the Controller.

How to clear react-native cache?

Currently, it is built using npx, so it needs to be updated.

Terminal : npx react-native start --reset-cache

IOS : Xcode -> Product -> Clean Build Folder

Android : Android Studio -> Build -> Clean Project

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

Create an Array of Arraylists

As per Oracle Documentation:

"You cannot create arrays of parameterized types"

Instead, you could do:

ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);

As suggested by Tom Hawting - tackline, it is even better to do:

List<List<Individual>> group = new ArrayList<List<Individual>>(4);