Programs & Examples On #Groupwise maximum

SQL select only rows with max value on a column

I like to do this by ranking the records by some column. In this case, rank rev values grouped by id. Those with higher rev will have lower rankings. So highest rev will have ranking of 1.

select id, rev, content
from
 (select
    @rowNum := if(@prevValue = id, @rowNum+1, 1) as row_num,
    id, rev, content,
    @prevValue := id
  from
   (select id, rev, content from YOURTABLE order by id asc, rev desc) TEMP,
   (select @rowNum := 1 from DUAL) X,
   (select @prevValue := -1 from DUAL) Y) TEMP
where row_num = 1;

Not sure if introducing variables makes the whole thing slower. But at least I'm not querying YOURTABLE twice.

LEFT JOIN only first row

based on several answers here, i found something that worked for me and i wanted to generalize and explain what's going on.

convert:

LEFT JOIN table2 t2 ON (t2.thing = t1.thing)

to:

LEFT JOIN table2 t2 ON (t2.p_key = (SELECT MIN(t2_.p_key) 
    FROM table2 t2_ WHERE (t2_.thing = t1.thing) LIMIT 1))

the condition that connects t1 and t2 is moved from the ON and into the inner query WHERE. the MIN(primary key) or LIMIT 1 makes sure that only 1 row is returned by the inner query.

after selecting one specific row we need to tell the ON which row it is. that's why the ON is comparing the primary key of the joined tabled.

you can play with the inner query (i.e. order+limit) but it must return one primary key of the desired row that will tell the ON the exact row to join.

Update - for MySQL 5.7+

another option relevant to MySQL 5.7+ is to use ANY_VALUE+GROUP BY. it will select an artist name that is not necessarily the first one.

SELECT feeds.*,ANY_VALUE(feeds_artists.name) artist_name
    FROM feeds 
    LEFT JOIN feeds_artists ON feeds.id = feeds_artists.feed_id 
GROUP BY feeds.id

more info about ANY_VALUE: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

Convert a video to MP4 (H.264/AAC) with ffmpeg

You need to compile ffmpeg with an AAC encoder. You can find one at AudioCoding.

JavaScript naming conventions

That's an individual question that could depend on how you're working. Some people like to put the variable type at the begining of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").

I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".

In short: english, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

SQL Server 2008: How to query all databases sizes?

I don't know exactly what you mean by efficiency but this is straightforward and it works for me:

SELECT
    DB_NAME(db.database_id) DatabaseName,
    (CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,
    (CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB,
    (CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,
    (CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB
FROM sys.databases db
    LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) StreamSize FROM sys.master_files WHERE type = 2 GROUP BY database_id, type) mfstream ON mfstream.database_id = db.database_id
    LEFT JOIN (SELECT database_id, SUM(size) TextIndexSize FROM sys.master_files WHERE type = 4 GROUP BY database_id, type) mftext ON mftext.database_id = db.database_id

With results like:

DatabaseName  RowSizeMB LogSizeMB StreamSizeMB TextIndexSizeMB
------------- --------- --------- ------------ ---------------
master        4         1.25      NULL         NULL
model         2.25      0.75      NULL         NULL
msdb          14.75     8.1875    NULL         NULL
tempdb        8         0.5       NULL         NULL

Note: was inspired by this article

Characters allowed in a URL

These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.

scipy.misc module has no attribute imread?

I have all the packages required for the image extraction on jupyter notebook, but even then it shows me the same error.

Error on Jupyter Notebook

Reading the above comments, I have installed the required packages. Please do tell if I have missed some packages.

pip3 freeze | grep -i -E "pillow|scipy|scikit-image"
Pillow==5.4.1
scikit-image==0.14.2

scipy==1.2.1

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

add to array if it isn't there already

You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

if (!in_array($value, $array))
{
    $array[] = $value; 
}

This is what the documentation says about in_array:

Returns TRUE if needle is found in the array, FALSE otherwise.

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

How do I remove the "extended attributes" on a file in Mac OS X?

Another recursive approach:

# change directory to target folder:
cd /Volumes/path/to/folder

# find all things of type "f" (file), 
# then pipe "|" each result as an argument (xargs -0) 
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c

# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

Determining the path that a yum package installed to

I don't know about yum, but rpm -ql will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.

How to recursively list all the files in a directory in C#?

Listing files and folders to model, custom implementation.
This creates a full listing of all files and folders starting from your start directory.

public class DirOrFileModel
    {
        #region Private Members

        private string _name;
        private string _location;
        private EntryType _entryType;

        #endregion

        #region Bindings

        public string Name
        {
            get { return _name; }
            set
            {
                if (value == _name) return;
                _name = value;
            }
        }

        public string Location
        {
            get { return _location; }
            set
            {
                if (value == _location) return;
                _location = value;
            }
        }

        public EntryType EntryType
        {
            get { return _entryType; }
            set
            {
                if (value == _entryType) return;
                _entryType = value;
            }
        }

        public ObservableCollection<DirOrFileModel> Entries { get; set; }

        #endregion

        #region Constructor

        public DirOrFileModel()
        {
            Entries = new ObservableCollection<DirOrFileModel>();
        }

        #endregion
    }

    public enum EntryType
    {
        Directory = 0,
        File = 1
    }

Method:

 static DirOrFileModel DirSearch(DirOrFileModel startDir)
        {
            var currentDir = startDir;
            try
            {
                foreach (string d in Directory.GetDirectories(currentDir.Location))
                {
                    var newDir = new DirOrFileModel
                    {
                        EntryType = EntryType.Directory,
                        Location = d,
                        Name = Path.GetFileName(d)
                    };
                    currentDir.Entries.Add(newDir);

                    DirSearch(newDir);
                }

                foreach (string f in Directory.GetFiles(currentDir.Location))
                {
                    var newFile = new DirOrFileModel
                    {
                        EntryType = EntryType.File,
                        Location = f,
                        Name = Path.GetFileNameWithoutExtension(f)
                    };
                    currentDir.Entries.Add(newFile);
                }

            }
            catch (Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
            return startDir;
        }

Usage:

var dir = new DirOrFileModel
            {
                Name = "C",
                Location = @"C:\",
                EntryType = EntryType.Directory
            };

            dir = DirSearch(dir);

Get the time difference between two datetimes

The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):

// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end   = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');

// Getting the difference: hours (h), minutes (m) and seconds (s)
let h  = end.diff(start, 'hours');
let m  = end.diff(start, 'minutes') - (60 * h);
let s  = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);

// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);

console.log(`${hh}:${mm}:${ss}`); // 00:39:30

Disable back button in android

You can override the onBackPressed() method in your activity and remove the call to super class.

@Override
public void onBackPressed() {
  //remove call to the super class
  //super.onBackPressed();
}

How to create a POJO?

According to Martin Fowler

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.

Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.

  1. Each variable in a POJO should be declared as private.
  2. Default constructor should be overridden with public accessibility.
  3. Each variable should have its Setter-Getter method with public accessibility.
  4. Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
  5. Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).

And according to Java Language Specification, a POJO should not have to

  1. Extend pre-specified classes
  2. Implement pre-specified interfaces
  3. Contain pre-specified annotations

However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.

A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

Read more on Plain Old Java Object (POJO) Explained.

What's the Use of '\r' escape sequence?

\r move the cursor to the begin of the line.

Line breaks are managed differently on different systems. Some only use \n (line feed, e.g. Unix), some use (\r e.g. MacOS before OS X afaik) and some use \r\n (e.g. Windows afaik).

Turn off warnings and errors on PHP and MySQL

If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors) in a .htaccess file in any directory by adding the following line:

php_flag display_errors off

additionally, you can add error logging to a file:

php_flag log_errors on

How to convert a GUID to a string in C#?

According to MSDN the method Guid.ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.

Examples:

  • guidVal.ToString() or guidVal.ToString("D") returns 32 hex digits separated by hyphens: 00000000-0000-0000-0000-000000000000
  • guidVal.ToString("N") returns 32 hex digits:00000000000000000000000000000000
  • guidVal.ToString("B") returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
  • guidVal.ToString("P") returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)

Find most frequent value in SQL column

Below query seems to work good for me in SQL Server database:

select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC

Result:

column          MOST_FREQUENT
item1           highest count
item2           second highest 
item3           third higest
..
..

Query comparing dates in SQL

If You are comparing only with the date vale, then converting it to date (not datetime) will work

select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= convert(date,'2013-04-12',102)

This conversion is also applicable during using GetDate() function

How to retrieve value from elements in array using jQuery?

to read an array, you can also utilize "each" method of jQuery:

$.each($("input[name^='card']"), function(index, val){
    console.log(index + " : " + val);
});

bonus: you can also read objects through this method.

source

Correct way to quit a Qt program?

//How to Run App

bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() <<  "Run = " << ok;


//How to Kill App

system("taskkill /im CozxyLogger.exe /f");
qDebug() << "Close";

example

Creating an Instance of a Class with a variable in Python

Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:

class Toy:
    num = 0
    def __init__(self, name, kind, *args):
        self.name = name
        self.kind = kind
        self.data = args
        self.num = Toy.num
        Toy.num += 1

    def __repr__(self):
        return ' '.join([self.name,self.kind,str(self.num)])

    def playWith(self):
        print self

def getNewToy(name, kind):
    return Toy(name, kind)

t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()

Running it:

$ python toy.py 
Suzie doll 0
Jack robot 1

As you can see, getNewToy is really unnecessary. Now you can modify playWith to check the value of self.kind and change behavior, you can redefine playWith to designate a playmate:

def playWith(self, who=None):
    if who:  pass
    print self

t1.playWith(t2)

How to save the output of a console.log(object) to a file?

There is an open-source javascript plugin that does just that - debugout.js

Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. It also toggles live-logging in one place.

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

This worked for me.

app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin", "*");
    res.send('hello world')
})

You can change * to fit your needs. Hope this can help.

Prevent form submission on Enter key press

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

How to merge rows in a column into one cell in excel?

In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:

  1. In any cell write next code

    =Transpose(A1:A9) 
    

Where A1:A9 are cells you would like to merge.

  1. Without leaving the cell press F9

After that, the cell will contain the string:

={A1,A2,A3,A4,A5,A6,A7,A8,A9}

Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/

Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)

How to update/refresh specific item in RecyclerView

The problem is RecyclerView.Adatper does not provide any methods that return the index of element

public abstract static class Adapter<VH extends ViewHolder> {
  /**
   * returns index of the given element in adapter, return -1 if not exist
   */
  public int indexOf(Object elem);
}

My workaround is to create a map instance for (element, position)s

public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
  private Map<Friend, Integer> posMap ;
  private List<Friend> friends;

  public FriendAdapter(List<Friend> friends ) {
    this.friends = new ArrayList<>(friends);
    this.posMap = new HashMap<>();
    for(int i = 0; i < this.friends.size(); i++) {
      posMap.put(this.friends.get(i), i);
    }
  }

  public int indexOf(Friend friend) {
    Integer position = this.posMap.get(elem);
    return position == null ? -1 : position;
  }
  // skip other methods in class Adapter
}
  • the element type(here class Friend) should implements hashCode() and equals() because it is key in hashmap.

when an element changed,

  void someMethod() {
    Friend friend = ...;
    friend.setPhoneNumber('xxxxx');

    int position = friendAdapter.indexOf(friend);
    friendAdapter.notifyItemChanged(position);

  }

It is good to define an helper method

public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {

  public void friendUpdated(Friend friend) {
    int position = this.indexOf(friend);
    this.notifyItemChanged(position);
  }
}

Map instance(Map<Friend, Integer> posMap) is not necessarily required. If map is not used, looping throughout list can find the position of an element.

How to convert int[] into List<Integer> in Java?

Here is a solution:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

INSERT with SELECT

Sure, what do you want to use for the gid? a static value, PHP var, ...

A static value of 1234 could be like:

INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid

Add context path to Spring Boot application

The correct properties are

server.servlet.path

to configure the path of the DispatcherServlet

and

server.servlet.context-path

to configure the path of the applications context below that.

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

Understanding typedefs for function pointers in C

cdecl is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.

As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:

typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);

rather than:

typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);

cdecl can help you out with this stuff:

cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )

And is (in fact) exactly how I generated that crazy mess above.

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

YouTube: How to present embed video with sound muted

Updated

Add &mute=1 to the end of your url.

Your new code would be:

_x000D_
_x000D_
<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&amp;autoplay=1&mute=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
_x000D_
_x000D_
_x000D_

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

Advantages of using display:inline-block vs float:left in CSS

If you want to align the div with pixel accurate, then use float. inline-block seems to always requires you to chop off a few pixels (at least in IE)

Programmatically navigate to another view controller/scene

Programmatically there are different ways based on different situations

  1. load storyenter code hereboard nib file

    let yourVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YourViewController") as! YourViewController;
    self.present(yourVc, animated: true, completion: nil)
    
  2. Load from xib

    let yourVc = YourViewController.init(nibName: "YourViewController", bundle: nil)
    self.present(yourVc, animated: true, completion: nil)
    
  3. Navigate through Segue

    self.performSegue(withIdentifier: "your UIView", sender: self)
    

Programmatically saving image to Django ImageField

Another possible way to do that:

from django.core.files import File

with open('path_to_file', 'r') as f:   # use 'rb' mode for python3
    data = File(f)
    model.image.save('filename', data, True)

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

The issue for me was the type I was using was in objective-c in a swift project and I had forgotten to import the type's objective-c header file in the bridging header file

How to post a file from a form with Axios

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

Get folder name of the file in Python

you can use pathlib

from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]

The output of the above was this:

'folder2'

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

Ping site and return result in PHP

ping is available on almost every OS. So you could make a system call and fetch the result.

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

iPhone hide Navigation Bar only on first page

Give my credit to @chad-m 's answer.

Here is the Swift version:

  1. Create a new file MyNavigationController.swift

import UIKit

class MyNavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController == self.viewControllers.first {
            self.setNavigationBarHidden(true, animated: animated)
        } else {
            self.setNavigationBarHidden(false, animated: animated)
        }
    }

}
  1. Set your UINavigationController's class in StoryBoard to MyNavigationController MyNavigationController That's it!

Difference between chad-m's answer and mine:

  1. Inherit from UINavigationController, so you won't pollute your rootViewController.

  2. use self.viewControllers.first rather than homeViewController, so you won't do this 100 times for your 100 UINavigationControllers in 1 StoryBoard.

npm install errors with Error: ENOENT, chmod

I got a similar error message when trying to npm install a bunch of dependencies. Turns out some of them fail to install on Debian/Ubuntu because they expect /usr/bin/node to be the node executable. To fix, you need do

sudo ln -s nodejs /usr/bin/node 

or better yet,

sudo apt-get install nodejs-legacy

For more info: https://stackoverflow.com/a/21171188/7581

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

Using XPATH to search text containing &nbsp;

I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...

//table[@id='TableID']//td[text()=' ']

worked for me with the special char.

From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.

Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.

What is the way of declaring an array in JavaScript?

To declare it:

var myArr = ["apples", "oranges", "bananas"];

To use it:

document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);

Reload content in modal (twitter bootstrap)

I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):

$('#my-modal').on 'hidden.bs.modal', (event) ->
  $(this).removeData('bs.modal').children().remove()

Call php function from JavaScript

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php

Simple example usage:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Best way to log POST data in Apache?

Though It's late to answer. This module can do: https://github.com/danghvu/mod_dumpost

.htaccess rewrite subdomain to directory

You can use the following rule in .htaccess to rewrite a subdomain to a subfolder:

RewriteEngine On

 # If the host is "sub.domain.com"
 RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
 # Then rewrite any request to /folder
 RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]

Line-by-line explanation:

  RewriteEngine on

The line above tells the server to turn on the engine for rewriting URLs.

  RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]

This line is a condition for the RewriteRule where we match against the HTTP host using a regex pattern. The condition says that if the host is sub.domain.com then execute the rule.

 RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]

The rule matches http://sub.domain.com/foo and internally redirects it to http://sub.domain.com/folder/foo.

Replace sub.domain.com with your subdomain and folder with name of the folder you want to point your subdomain to.

How to create Custom Ratings bar in Android

You can create custom material rating bar by defining drawable xml using material icon of your choice and then applying custom drawable to rating bar using progressDrawable attribute.

For infomration about customizing rating bar see http://www.zoftino.com/android-ratingbar-and-custom-ratingbar-example

Below drawable xml uses thumbs up icon for rating bar.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlNormal" />
    </item>
    <item android:id="@android:id/secondaryProgress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
    <item android:id="@android:id/progress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
</layer-list>

How to make scipy.interpolate give an extrapolated result beyond the input range?

I'm afraid that there is no easy to do this in Scipy to my knowledge. You can, as I'm fairly sure that you are aware, turn off the bounds errors and fill all function values beyond the range with a constant, but that doesn't really help. See this question on the mailing list for some more ideas. Maybe you could use some kind of piecewise function, but that seems like a major pain.

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

How do I compile C++ with Clang?

I do not know why there is no answer directly addressing the problem. When you want to compile C++ program, it is best to use clang++. For example, the following works for me:

clang++ -Wall -std=c++11 test.cc -o test

If compiled correctly, it will produce the executable file test, and you can run the file by using ./test.

Or you can just use clang++ test.cc to compile the program. It will produce a default executable file named a.out. Use ./a.out to run the file.

The whole process is a lot like g++ if you are familiar with g++. See this post to check which warnings are included with -Wall option. This page shows a list of diagnostic flags supported by Clang.

A note on using clang -x c++: Kim Gräsman says that you can also use clang -x c++ to compile cpp programs, but that may not be true. For example, I am having a simple program below:

#include <iostream>
#include <vector>

int main() {
    /* std::vector<int> v = {1, 2, 3, 4, 5}; */
    std::vector<int> v(10, 5);
    int sum = 0;
    for (int i = 0; i < v.size(); i++){
        sum += v[i]*2;
    }
    std::cout << "sum is " << sum << std::endl;
    return 0;
}                                                      

clang++ test.cc -o test will compile successfully, but clang -x c++ will not, showing a lot undefined references errors. So I guess they are not exactly equivalent. It is best to use clang++ instead of clang -x c++ when compiling c++ programs to avoid extra troubles.

  • clang version: 11.0.0
  • Platform: Ubuntu 16.04

Compare two files line by line and generate the difference in another file

diff(1) is not the answer, but comm(1) is.

NAME
       comm - compare two sorted files line by line

SYNOPSIS
       comm [OPTION]... FILE1 FILE2

...

       -1     suppress lines unique to FILE1

       -2     suppress lines unique to FILE2

       -3     suppress lines that appear in both files

So

comm -2 -3 file1 file2 > file3

The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...

comm -2 -3 <(sort file1) <(sort file2) > file3

provided that your shell supports process substitution (bash does).

What is the default username and password in Tomcat?

Only this helped me:

To use the web administration gui you have to add the gui role :

<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager"/>
<role rolename="manager-gui"/>

<user username="name" password="pwd" roles="admin,admin-gui,manager,manager-gui"/>

Google Maps v3 - limit viewable area and zoom level

myOptions = {
        center: myLatlng,
        minZoom: 6,
        maxZoom: 9,
        styles: customStyles,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

Using Regular Expressions to Extract a Value in Java

Simple Solution

// Regexplanation:
// ^       beginning of line
// \\D+    1+ non-digit characters
// (\\d+)  1+ digit characters in a capture group
// .*      0+ any character
String regexStr = "^\\D+(\\d+).*";

// Compile the regex String into a Pattern
Pattern p = Pattern.compile(regexStr);

// Create a matcher with the input String
Matcher m = p.matcher(inputStr);

// If we find a match
if (m.find()) {
    // Get the String from the first capture group
    String someDigits = m.group(1);
    // ...do something with someDigits
}

Solution in a Util Class

public class MyUtil {
    private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
    private static Matcher matcher = pattern.matcher("");

    // Assumptions: inputStr is a non-null String
    public static String extractFirstNumber(String inputStr){
        // Reset the matcher with a new input String
        matcher.reset(inputStr);

        // Check if there's a match
        if(matcher.find()){
            // Return the number (in the first capture group)
            return matcher.group(1);
        }else{
            // Return some default value, if there is no match
            return null;
        }
    }
}

...

// Use the util function and print out the result
String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
System.out.println(firstNum);

How to copy a collection from one database to another in MongoDB

I would abuse the connect function in mongo cli mongo doc. so that means you can start one or more connection. if you want to copy customer collection from test to test2 in same server. first you start mongo shell

use test
var db2 = connect('localhost:27017/test2')

do a normal find and copy the first 20 record to test2.

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

or filter by some criteria

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

just change the localhost to IP or hostname to connect to remote server. I use this to copy test data to a test database for testing.

Error: Can't set headers after they are sent to the client

Came here from nuxt, the problem was in the component's asyncData method, I forgot to return promise which was fetching data and setting header there.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

This is a Server-Side issue.

Server side have .crt file for HTTPS, here we have to do combine

cat your_domain.**crt** your_domain.**ca-bundle** >> ssl_your_domain_.crt 

then restart.

sudo service nginx restart

For me working fine.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

So node got kicked out of path. you can do

       SET PATH=C:\Program Files\Nodejs;%PATH%

Or simply reinstall node to fix this. which ever you think is easiest for you

How to post SOAP Request from PHP

PHP has SOAP support. Just call

$client = new SoapClient($url);

to connect to the SoapServer and then you can get list of functions and call functions simply by doing...

$client->__getTypes();      
$client->__getFunctions();  

$result = $client->functionName();  

for more http://www.php.net/manual/en/soapclient.soapclient.php

Difference between UTF-8 and UTF-16?

I believe there are a lot of good articles about this around the Web, but here is a short summary.

Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.

Main UTF-8 pros:

  • Basic ASCII characters like digits, Latin characters with no accents, etc. occupy one byte which is identical to US-ASCII representation. This way all US-ASCII strings become valid UTF-8, which provides decent backwards compatibility in many cases.
  • No null bytes, which allows to use null-terminated strings, this introduces a great deal of backwards compatibility too.
  • UTF-8 is independent of byte order, so you don't have to worry about Big Endian / Little Endian issue.

Main UTF-8 cons:

  • Many common characters have different length, which slows indexing by codepoint and calculating a codepoint count terribly.
  • Even though byte order doesn't matter, sometimes UTF-8 still has BOM (byte order mark) which serves to notify that the text is encoded in UTF-8, and also breaks compatibility with ASCII software even if the text only contains ASCII characters. Microsoft software (like Notepad) especially likes to add BOM to UTF-8.

Main UTF-16 pros:

  • BMP (basic multilingual plane) characters, including Latin, Cyrillic, most Chinese (the PRC made support for some codepoints outside BMP mandatory), most Japanese can be represented with 2 bytes. This speeds up indexing and calculating codepoint count in case the text does not contain supplementary characters.
  • Even if the text has supplementary characters, they are still represented by pairs of 16-bit values, which means that the total length is still divisible by two and allows to use 16-bit char as the primitive component of the string.

Main UTF-16 cons:

  • Lots of null bytes in US-ASCII strings, which means no null-terminated strings and a lot of wasted memory.
  • Using it as a fixed-length encoding “mostly works” in many common scenarios (especially in US / EU / countries with Cyrillic alphabets / Israel / Arab countries / Iran and many others), often leading to broken support where it doesn't. This means the programmers have to be aware of surrogate pairs and handle them properly in cases where it matters!
  • It's variable length, so counting or indexing codepoints is costly, though less than UTF-8.

In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.

docker run <IMAGE> <MULTIPLE COMMANDS>

To run multiple commands in docker, use /bin/bash -c and semicolon ;

docker run image_name /bin/bash -c "cd /path/to/somewhere; python a.py"

In case we need command2 (python) will be executed if and only if command1 (cd) returned zero (no error) exit status, use && instead of ;

docker run image_name /bin/bash -c "cd /path/to/somewhere && python a.py"

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

Adding asterisk to required fields in Bootstrap 3

This works for me:

CSS

.form-group.required.control-label:before{
   content: "*";
   color: red;
}

OR

.form-group.required.control-label:after{
   content: "*";
   color: red;
}

Basic HTML

<div class="form-group required control-label">
  <input class="form-control" />
</div>

Set Focus After Last Character in Text Box

Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

It uses setSelectionRange if supported, else has a solid fallback.

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

Then you can just do:

input.putCursorAtEnd();

Which websocket library to use with Node.js?

Update: This answer is outdated as newer versions of libraries mentioned are released since then.

Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.

"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.

See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539

Convert string with commas to array

use the built-in map function with an anonymous function, like so:

string.split(',').map(function(n) {return Number(n);});

[edit] here's how you would use it

var string = "0,1";
var array = string.split(',').map(function(n) {
    return Number(n);
});
alert( array[0] );

What are the rules for casting pointers in C?

When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

d in main is a pointer to c which is of type char. A char is one byte of memory, so when d is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.

-+----+----+----+----+----+----+-
 |    | c  |    |    |    |    | 
-+----+----+----+----+----+----+-
       ^~~~
       | char
       d

When you cast d to int*, you're saying that d really points to an int value. On most systems today, an int occupies 4 bytes.

-+----+----+----+----+----+----+-
 |    | c  | ?1 | ?2 | ?3 |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       (int*)d

When you dereference (int*)d, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?, and on how an int is represented in memory.

A PC is little-endian, which means that the value of an int is calculated this way (assuming that it spans 4 bytes): * ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)), the last two digits will always be 35 (that's the value of the character '5').

Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3. On these systems, you'd find that the value always starts with 35 when printed in hexadecimal. Some systems have a size of int that's different from 4 bytes. A rare few systems arrange int in different ways but you're extremely unlikely to encounter them.

Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.

On some systems, an int value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c happens to be properly aligned or not, the program may crash.

In contrast with your program, here's what happens when you have an int value and take a pointer to it.

int x = 42;
int *p = &x;
-+----+----+----+----+----+----+-
 |    |         x         |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       p

The pointer p points to an int value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.

Run react-native application on iOS device directly from command line?

Got mine working with

react-native run-ios --device="My’s iPhone"

And notice that your iphone name, the apostrophe s ' might be different. Mine is using this ’

How to check that Request.QueryString has a specific value or not in ASP.NET?

string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value

Will return if there is a value

Delete element in a slice

I'm getting an index out of range error with the accepted answer solution. Reason: When range start, it is not iterate value one by one, it is iterate by index. If you modified a slice while it is in range, it will induce some problem.

Old Answer:

chars := []string{"a", "a", "b"}

for i, v := range chars {
    fmt.Printf("%+v, %d, %s\n", chars, i, v)
    if v == "a" {
        chars = append(chars[:i], chars[i+1:]...)
    }
}
fmt.Printf("%+v", chars)

Expected :

[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]

Actual:

// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]

Correct Way (Solution):

chars := []string{"a", "a", "b"}

for i := 0; i < len(chars); i++ {
    if chars[i] == "a" {
        chars = append(chars[:i], chars[i+1:]...)
        i-- // form the remove item index to start iterate next item
    }
}

fmt.Printf("%+v", chars)

Source: https://dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html

JavaScript calculate the day of the year (1 - 366)

Following OP's edit:

_x000D_
_x000D_
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = now - start;_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
_x000D_
_x000D_

Edit: The code above will fail when now is a date in between march 26th and October 29th andnow's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:

_x000D_
_x000D_
var now = new Date();_x000D_
var start = new Date(now.getFullYear(), 0, 0);_x000D_
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);_x000D_
var oneDay = 1000 * 60 * 60 * 24;_x000D_
var day = Math.floor(diff / oneDay);_x000D_
console.log('Day of year: ' + day);
_x000D_
_x000D_
_x000D_

How do I disable the security certificate check in Python requests

Also can be done from the environment variable:

export CURL_CA_BUNDLE=""

How to comment multiple lines with space or indent

One way to do it would be:

  1. Select the text, Press CTRL + K, C to comment (CTRL+E+C )
  2. Move the cursor to the first line after the delimiter // and before the Code text.
  3. Press Alt + Shift and use arrow keys to make selection. (Remember to make line selection(using down, up arrow keys), not the text selection - See Box Selection and Multi line editing)
  4. Once the selection is done, press space bar to enter a single space.

Notice the vertical blue line in the below image( that will appear once the selection is made, then you can insert any number of characters in between them)

enter image description here

I couldn't find a direct way to do that. The interesting thing is that it is mentioned in the C# Coding Conventions (C# Programming Guide) under Commenting Conventions.

Insert one space between the comment delimiter (//) and the comment text

But the default implementation of commenting in visual studio doesn't insert any space

How can I get color-int from color resource?

Found an easier way that works as well:

Color.parseColor(getString(R.color.idname);

How can I clear the SQL Server query cache?

While the question is just a bit old, this might still help. I'm running into similar issues and using the option below has helped me. Not sure if this is a permanent solution, but it's fixing it for now.

OPTION (OPTIMIZE FOR UNKNOWN)

Then your query will be like this

select * from Table where Col = 'someval' OPTION (OPTIMIZE FOR UNKNOWN)

How to display svg icons(.svg files) in UI using React Component?

Just write require with path inside the src of image. it will work. like:

<img alt="Clock" src={require('../assets/images/search_icon.svg')}/>

How to check if a number is a power of 2

The following addendum to the accepted answer may be useful for some people:

A power of two, when expressed in binary, will always look like 1 followed by n zeroes where n is greater than or equal to 0. Ex:

Decimal  Binary
1        1     (1 followed by 0 zero)
2        10    (1 followed by 1 zero)
4        100   (1 followed by 2 zeroes)
8        1000  (1 followed by 3 zeroes)
.        .
.        .
.        .

and so on.

When we subtract 1 from these kind of numbers, they become 0 followed by n ones and again n is same as above. Ex:

Decimal    Binary
1 - 1 = 0  0    (0 followed by 0 one)
2 - 1 = 1  01   (0 followed by 1 one)
4 - 1 = 3  011  (0 followed by 2 ones)
8 - 1 = 7  0111 (0 followed by 3 ones)
.          .
.          .
.          .

and so on.

Coming to the crux

What happens when we do a bitwise AND of a number x, which is a power of 2, and x - 1?

The one of x gets aligned with the zero of x - 1 and all the zeroes of x get aligned with ones of x - 1, causing the bitwise AND to result in 0. And that is how we have the single line answer mentioned above being right.


Further adding to the beauty of accepted answer above -

So, we have a property at our disposal now:

When we subtract 1 from any number, then in the binary representation the rightmost 1 will become 0 and all the zeroes to the left of that rightmost 1 will now become 1.

One awesome use of this property is in finding out - How many 1s are present in the binary representation of a given number? The short and sweet code to do that for a given integer x is:

byte count = 0;
for ( ; x != 0; x &= (x - 1)) count++;
Console.Write("Total ones in the binary representation of x = {0}", count);

Another aspect of numbers that can be proved from the concept explained above is "Can every positive number be represented as the sum of powers of 2?".

Yes, every positive number can be represented as the sum of powers of 2. For any number, take its binary representation. Ex: Take number 117.

The binary representation of 117 is 1110101

Because  1110101 = 1000000 + 100000 + 10000 + 0000 + 100 + 00 + 1
we have  117     = 64      + 32     + 16    + 0    + 4   + 0  + 1

Visual Studio Code: Auto-refresh file changes

SUPER-SHIFT-p > File: Revert File is the only way

(where SUPER is Command on Mac and Ctrl on PC)

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

How to call function on child component on parent events

What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would watch that prop. When the child takes action, it notifies the parent via an emit, and the parent might then change the state again.

_x000D_
_x000D_
var Child = {_x000D_
  template: '<div>{{counter}}</div>',_x000D_
  props: ['canI'],_x000D_
  data: function () {_x000D_
    return {_x000D_
      counter: 0_x000D_
    };_x000D_
  },_x000D_
  watch: {_x000D_
    canI: function () {_x000D_
      if (this.canI) {_x000D_
        ++this.counter;_x000D_
        this.$emit('increment');_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  components: {_x000D_
    'my-component': Child_x000D_
  },_x000D_
  data: {_x000D_
    childState: false_x000D_
  },_x000D_
  methods: {_x000D_
    permitChild: function () {_x000D_
      this.childState = true;_x000D_
    },_x000D_
    lockChild: function () {_x000D_
      this.childState = false;_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>_x000D_
<div id="app">_x000D_
<my-component :can-I="childState" v-on:increment="lockChild"></my-component>_x000D_
<button @click="permitChild">Go</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.

In C# check that filename is *possibly* valid (not that it exists)

This will get you the drives on the machine:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();

How do I print an IFrame from javascript in Safari/Chrome

Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()

What is the "continue" keyword and how does it work in Java?

Continue is a keyword in Java & it is used to skip the current iteration.

Suppose you want to print all odd numbers from 1 to 100

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

        for(int i=1 ; i<=100 ; i++) {
            if(i % 2 == 0) {
                continue;
            }
            System.out.println(i);
        }

    }
}

continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.

Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Dissatisfied with the other answers. The top voted answer as of 2019/3/13 is factually wrong.

The short terse version of what => means is it's a shortcut writing a function AND for binding it to the current this

const foo = a => a * 2;

Is effectively a shortcut for

const foo = function(a) { return a * 2; }.bind(this);

You can see all the things that got shortened. We didn't need function, nor return nor .bind(this) nor even braces or parentheses

A slightly longer example of an arrow function might be

const foo = (width, height) => {
  const area = width * height;
  return area;
};

Showing that if we want multiple arguments to the function we need parentheses and if we want write more than a single expression we need braces and an explicit return.

It's important to understand the .bind part and it's a big topic. It has to do with what this means in JavaScript.

ALL functions have an implicit parameter called this. How this is set when calling a function depends on how that function is called.

Take

function foo() { console.log(this); }

If you call it normally

function foo() { console.log(this); }
foo();

this will be the global object.

If you're in strict mode

`use strict`;
function foo() { console.log(this); }
foo();

// or

function foo() {
   `use strict`;
   console.log(this);
 }
foo();

It will be undefined

You can set this directly using call or apply

function foo(msg) { console.log(msg, this); }

const obj1 = {abc: 123}
const obj2 = {def: 456}

foo.call(obj1, 'hello');  // prints Hello {abc: 123}
foo.apply(obj2, ['hi']);  // prints Hi {def: 456}

You can also set this implicitly using the dot operator .

function foo(msg) { console.log(msg, this); }
const obj = {
   abc: 123,
   bar: foo,
}
obj.bar('Hola');  // prints Hola {abc:123, bar: f}

A problem comes up when you want to use a function as a callback or a listener. You make class and want to assign a function as the callback that accesses an instance of the class.

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name);  // won't work
    }); 
  }
}

The code above will not work because when the element fires the event and calls the function the this value will not be the instance of the class.

One common way to solve that problem is to use .bind

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name); 
    }.bind(this); // <=========== ADDED! ===========
  }
}

Because the arrow syntax does the same thing we can write

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click',() => {
       console.log(this.name); 
    });
  }
}

bind effectively makes a new function. If bind did not exist you could basically make your own like this

function bind(functionToBind, valueToUseForThis) {
  return function(...args) {
    functionToBind.call(valueToUseForThis, ...args);
  };
}

In older JavaScript without the spread operator it would be

function bind(functionToBind, valueToUseForThis) {
  return function() {
    functionToBind.apply(valueToUseForThis, arguments);
  };
}

Understanding that code requires an understanding of closures but the short version is bind makes a new function that always calls the original function with the this value that was bound to it. Arrow functions do the same thing since they are a shortcut for bind(this)

Google map V3 Set Center to specific Marker

may be this will help:

map.setCenter(window.markersArray[2].getPosition());

all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:

window.markersArray[2] = new google.maps.Marker({
            position: new google.maps.LatLng(23.81927, 90.362349),          
            map: map,
            title: 'your info '  
        });

Hope this will help.

Log all queries in mysql

Besides what I came across here, running the following was the simplest way to dump queries to a log file without restarting

SET global log_output = 'FILE';
SET global general_log_file='/Applications/MAMP/logs/mysql_general.log';
SET global general_log = 1;

can be turned off with

SET global general_log = 0;

how to display none through code behind

if(displayit){
  login_div.Style["display"]="inline"; //the default display mode
}else{
  login_div.Style["display"]="none";
}

Adding this code into Page_Load should work. (if doing it at Page_Init you'll have to contend with viewstate changing what you put in it)

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

How to configure Fiddler to listen to localhost?

The Light,

You can configure the process acting as the client to use fiddler as a proxy.

Fiddler sets itself up as a proxy conveniently on 127.0.0.1:8888, and by default overrides the system settings under Internet Options in the Control Panel (if you've configured any) such that all traffic from the common protocols (http, https, and ftp) goes to 127.0.0.1:8888 before leaving your machine.

Now these protocols are often from common processes such as browsers, and so are easily picked up by fiddler. However, in your case, the process initiating the requests is probably not a browser, but one for a programming language like php.exe, or java.exe, or whatever language you are using.

If, say, you're using php, you can leverage curl. Ensure that the curl module is enabled, and then right before your code that invokes the request, include:

curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

Hope this helps. You can also always lookup stuff like so from the fiddler documentation for a basis for you to build upon e.g. http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigurePHPcURL

How to update a single pod without touching other dependencies

It's 2015

So because pod update SomePod touches everything in the latest versions of cocoapods, I found a workaround.

Follow the next steps:

  1. Remove SomePod from the Podfile

  2. Run pod install

pods will now remove SomePod from our project and from the Podfile.lock file.

  1. Put back SomePod into the Podfile

  2. Run pod install again

This time the latest version of our pod will be installed and saved in the Podfile.lock.

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

How can I control Chromedriver open window size?

RUBY


Approach #1

options = {
      'chromeOptions' => {
          'args' => ['start-fullscreen']
      }
  }

caps = Selenium::WebDriver::Remote::Capabilities.chrome(options)
@driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps

Approach #2

options = {
      'chromeOptions' => {
          'args' => ['window-size=640,480']
      }
  }

caps = Selenium::WebDriver::Remote::Capabilities.chrome(options)
@driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps

Approach #3

max_width, max_height = @driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
@driver.manage.window.resize_to(max_width, max_height)

Approach #4

@driver.manage.window.maximize

Approach #5

target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
@driver.manage.window.size = target_size

Approach #6

@driver.manage.window.resize_to(640, 480)

Approach #7

@driver.execute_script("window.resizeTo(640, 480);")

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

Unknown Column In Where Clause

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.

How do I make this file.sh executable via double click?

  1. Launch Terminal
  2. Type -> nano fileName
  3. Paste Batch file content and save it
  4. Type -> chmod +x fileName
  5. It will create exe file now you can double click and it.

File name should in under double quotes. Since i am using Mac->In my case content of batch file is

cd /Users/yourName/Documents/SeleniumServer

java -jar selenium-server-standalone-3.3.1.jar -role hub

It will work for sure

Android statusbar icons color

Setting windowLightStatusBar to true not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc. I've found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.

And I think, it would be better to tell your customer that coloring status bar (for example) white - is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark according to the guidelines

Close Window from ViewModel

You can close the current window just by using the following code:

Application.Current.Windows[0].Close();

How can we generate getters and setters in Visual Studio?

In addition to the 'prop' snippet and auto-properties, there is a refactor option to let you select an existing field and expose it via a property (right click on the field → RefactorEncapsulate Field...).

Also, if you don't like the 'prop' implementation, you can create your own snippets. Additionally, a third-party refactoring tool like ReSharper will give you even more features and make it easier to create more advanced snippets. I'd recommend ReSharper if you can afford it.

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

Raise error in a Bash script

Basic error handling

If your test case runner returns a non-zero code for failed tests, you can simply write:

test_handler test_case_x; test_result=$?
if ((test_result != 0)); then
  printf '%s\n' "Test case x failed" >&2  # write error message to stderr
  exit 1                                  # or exit $test_result
fi

Or even shorter:

if ! test_handler test_case_x; then
  printf '%s\n' "Test case x failed" >&2
  exit 1
fi

Or the shortest:

test_handler test_case_x || { printf '%s\n' "Test case x failed" >&2; exit 1; }

To exit with test_handler's exit code:

test_handler test_case_x || { ec=$?; printf '%s\n' "Test case x failed" >&2; exit $ec; }

Advanced error handling

If you want to take a more comprehensive approach, you can have an error handler:

exit_if_error() {
  local exit_code=$1
  shift
  [[ $exit_code ]] &&               # do nothing if no error code passed
    ((exit_code != 0)) && {         # do nothing if error code is 0
      printf 'ERROR: %s\n' "$@" >&2 # we can use better logging here
      exit "$exit_code"             # we could also check to make sure
                                    # error code is numeric when passed
    }
}

then invoke it after running your test case:

run_test_case test_case_x
exit_if_error $? "Test case x failed"

or

run_test_case test_case_x || exit_if_error $? "Test case x failed"

The advantages of having an error handler like exit_if_error are:

  • we can standardize all the error handling logic such as logging, printing a stack trace, notification, doing cleanup etc., in one place
  • by making the error handler get the error code as an argument, we can spare the caller from the clutter of if blocks that test exit codes for errors
  • if we have a signal handler (using trap), we can invoke the error handler from there

Error handling and logging library

Here is a complete implementation of error handling and logging:

https://github.com/codeforester/base/blob/master/lib/stdlib.sh


Related posts

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.

C++: Where to initialize variables in constructor

See Should my constructors use "initialization lists" or "assignment"?

Briefly: in your specific case, it does not change anything. But:

  • for class/struct members with constructors, it may be more efficient to use option 1.
  • only option 1 allows you to initialize reference members.
  • only option 1 allows you to initialize const members
  • only option 1 allows you to initialize base classes using their constructor
  • only option 2 allows you to initialize array or structs that do not have a constructor.

My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.

How do I determine file encoding in OS X?

The @ sign means the file has extended attributes. xattr file shows what attributes it has, xattr -l file shows the attribute values too (which can be large sometimes — try e.g. xattr /System/Library/Fonts/HelveLTMM to see an old-style font that exists in the resource fork).

How can I set the max-width of a table cell using percentages?

the percent should be relative to an absolute size, try this :

_x000D_
_x000D_
table {
  width:200px;
}

td {
  width:65%;
  border:1px solid black;
}
_x000D_
<table>
  <tr>
    <td>Testasdas 3123 1 dasd as da</td>
    <td>A long string blah blah blah</td>
  </tr>
</table>
    
_x000D_
_x000D_
_x000D_

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

Could not complete the operation due to error 80020101. IE

Switch off compatibility view if you use IE9.

Can RDP clients launch remote applications and not desktops

Another way is shown in this CodeProject article:

http://www.codeproject.com/KB/IP/tswindowclipper.aspx

The basic idea is to create a virutal channel that sends the windows position of the app(s) you want to show, then only render that part of the window on the client.

Editable 'Select' element

Nothing is impossible. Here's a solution that simply sets the value of a text input whenever the value of the <select> changes (rendering has been tested on Firefox and Google Chrome):

_x000D_
_x000D_
.select-editable {position:relative; background-color:white; border:solid grey 1px;  width:120px; height:18px;}_x000D_
.select-editable select {position:absolute; top:0px; left:0px; font-size:14px; border:none; width:120px; margin:0;}_x000D_
.select-editable input {position:absolute; top:0px; left:0px; width:100px; padding:1px; font-size:12px; border:none;}_x000D_
.select-editable select:focus, .select-editable input:focus {outline:none;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" name="format" value=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/nwH8A/

The next example adds the user input to the empty option slot of the <select> (thanks to @TomerPeled). It also has a little bit more flexible/variable CSS:

_x000D_
_x000D_
.select-editable {position:relative; width:120px;}_x000D_
.select-editable > * {position:absolute; top:0; left:0; box-sizing:border-box; outline:none;}_x000D_
.select-editable select {width:100%;}_x000D_
.select-editable input {width:calc(100% - 20px); margin:1px; border:none; text-overflow:ellipsis;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" onchange="this.previousElementSibling.selectedIndex=0" value="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/pu7cndLv/1/


DataList

In HTML5 you can also do this with the <input> list attribute and <datalist> element:

_x000D_
_x000D_
<input list="browsers" name="browser">_x000D_
<datalist id="browsers">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>_x000D_
(click once to focus and edit, click again to see option dropdown)
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/hrkxebtw/

But this acts more like an auto-complete list; once you start typing, only the options that contain the typed string are left as suggestions. Depending on what you want to use it for, this may or may not be practical.

How to add option to select list in jQuery

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");

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

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

How to get 30 days prior to current date?

You can do that simply through 1 line of code using moment in Node JS. :)

    let lastOneMonthDate = moment().subtract(30,"days").utc().toISOString()

Don't want UTC format, EASIER :P

    let lastOneMonthDate = moment().subtract(30,"days").toISOString()

Add Twitter Bootstrap icon to Input box

Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).

Make EditText ReadOnly

As android:editable="" is deprecated,

Setting

  • android:clickable="false"
  • android:focusable="false"
  • android:inputType="none"
  • android:cursorVisible="false"

will make it "read-only".

However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:

  • myEditText.setOnLongClickListener { true }

suffices.

intellij incorrectly saying no beans of type found for autowired repository

I had this same issue when creating a Spring Boot application using their @SpringBootApplication annotation. This annotation represents @Configuration, @EnableAutoConfiguration and @ComponentScan according to the spring reference.

As expected, the new annotation worked properly and my application ran smoothly but, Intellij kept complaining about unfulfilled @Autowire dependencies. As soon as I changed back to using @Configuration, @EnableAutoConfiguration and @ComponentScan separately, the errors ceased. It seems Intellij 14.0.3 (and most likely, earlier versions too) is not yet configured to recognise the @SpringBootApplication annotation.

For now, if the errors disturb you that much, then revert back to those three separate annotations. Otherwise, ignore Intellij...your dependency resolution is correctly configured, since your test passes.

Always remember...

Man is always greater than machine.

How to parse the AndroidManifest.xml file inside an .apk package

it can be helpful

public static int vCodeApk(String path) {
    PackageManager pm = G.context.getPackageManager();
    PackageInfo info = pm.getPackageArchiveInfo(path, 0);
    return info.versionCode;
    //        Toast.makeText(this, "VersionCode : " + info.versionCode + ", VersionName : " + info.versionName, Toast.LENGTH_LONG).show();
}

G is my Application class :

public class G extends Application {

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

What is the difference between a string and a byte string?

Unicode is an agreed-upon format for the binary representation of characters and various kinds of formatting (e.g. lower case/upper case, new line, carriage return), and other "things" (e.g. emojis). A computer is no less capable of storing a unicode representation (a series of bits), whether in memory or in a file, than it is of storing an ascii representation (a different series of bits), or any other representation (series of bits).

For communication to take place, the parties to the communication must agree on what representation will be used.

Because unicode seeks to represent all the possible characters (and other "things") used in inter-human and inter-computer communication, it requires a greater number of bits for the representation of many characters (or things) than other systems of representation that seek to represent a more limited set of characters/things. To "simplify," and perhaps to accommodate historical usage, unicode representation is almost exclusively converted to some other system of representation (e.g. ascii) for the purpose of storing characters in files.

It is not the case that unicode cannot be used for storing characters in files, or transmitting them through any communications channel, simply that it is not.

The term "string," is not precisely defined. "String," in its common usage, refers to a set of characters/things. In a computer, those characters may be stored in any one of many different bit-by-bit representations. A "byte string" is a set of characters stored using a representation that uses eight bits (eight bits being referred to as a byte). Since, these days, computers use the unicode system (characters represented by a variable number of bytes) to store characters in memory, and byte strings (characters represented by single bytes) to store characters to files, a conversion must be used before characters represented in memory will be moved into storage in files.

How to check Oracle patches are installed?

Here is an article on how to check and or install new patches :


To find the OPatch tool setup your database enviroment variables and then issue this comand:

cd $ORACLE_HOME/OPatch 
> pwd
/oracle/app/product/10.2.0/db_1/OPatch

To list all the patches applies to your database use the lsinventory option:

[oracle@DCG023 8828328]$ opatch lsinventory
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation. All rights reserved.

Oracle Home : /u00/product/11.2.0/dbhome_1
Central Inventory : /u00/oraInventory
from : /u00/product/11.2.0/dbhome_1/oraInst.loc
OPatch version : 11.2.0.3.4
OUI version : 11.2.0.1.0
Log file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/opatch2013-11-13_13-55-22PM_1.log
Lsinventory Output file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/lsinv/lsinventory2013-11-13_13-55-22PM.txt


Installed Top-level Products (1):
Oracle Database 11g 11.2.0.1.0
There are 1 products installed in this Oracle Home.

Interim patches (1) :
Patch 8405205 : applied on Mon Aug 19 15:18:04 BRT 2013
Unique Patch ID: 11805160
Created on 23 Sep 2009, 02:41:32 hrs PST8PDT
Bugs fixed:
8405205

OPatch succeeded.

To list the patches using sql :

select * from registry$history;

PHP check if date between two dates

You cannot compare date-strings. It is good habit to use PHP's DateTime object instead:

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

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

What's the idiomatic syntax for prepending to a short python list?

If someone finds this question like me, here are my performance tests of proposed methods:

Python 2.7.8

In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop

In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop

In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop

As you can see, insert and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert is more common option and I, personally prefer this way to prepend to list.

curl : (1) Protocol https not supported or disabled in libcurl

I just recompiled curl with configure options pointing to the openssl 1.0.2g library folder and include folder, and I still get this message. When I do ldd on curl, it does not show that it uses either libcrypt.so or libssl.so, so I assume this must mean that even though the make and make install succeeded without errors, nevertheless curl does not have HTTPS support? Configure and make was as follows:

./configure --prefix=/local/scratch/PACKAGES/local --with-ssl=/local/scratch/PACKAGES/local/openssl/openssl-1.0.2g --includedir=/local/scratch/PACKAGES/local/include/openssl/openssl-1.0.2g
make
make test
make install

I should mention that libssl.so.1 is in /local/scratch/PACKAGES/local/lib. It is unclear whether the --with-ssl option should point there or to the directory where the openssl install placed the openssl.cnf file. I chose the latter. But if it were supposed to be the former, the make should have failed with an error that it couldn't find the library.

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If the ActiveDirectory module is present add

import-module activedirectory

before your code.

To check if exist try:

get-module -listavailable

ActiveDirectory module is default present in windows server 2008 R2, install it in this way:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

For have it to work you need at least one DC in the domain as windows 2008 R2 and have Active Directory Web Services (ADWS) installed on it.

For Windows Server 2008 read here how to install it

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id

I would run

sp_helpconstraint sup_item

and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

There is one more solution to set column Full text to true.

These solution for example didn't work for me

ALTER TABLE news ADD FULLTEXT(headline, story);

My solution.

  1. Right click on table
  2. Design
  3. Right Click on column which you want to edit
  4. Full text index
  5. Add
  6. Close
  7. Refresh

NEXT STEPS

  1. Right click on table
  2. Design
  3. Click on column which you want to edit
  4. On bottom of mssql you there will be tab "Column properties"
  5. Full-text Specification -> (Is Full-text Indexed) set to true.

Refresh

Version of mssql 2014

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:

Import the self-signed certificate:

keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks

Add the official root certificates:

keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks

Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.

ORIGINAL POSTING:

Nobody will believe this, I know. Still, if all else fails, give it a try: After a reboot of my Mac the problem was gone. Grrr.

Background: ./gradlew jar kept giving me "unable to find valid certification path to requested target"

I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:

org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit

As mentioned, this only worked after a reboot.

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Extracting numbers from vectors of strings

Extract numbers from any string at beginning position.

x <- gregexpr("^[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

Extract numbers from any string INDEPENDENT of position.

x <- gregexpr("[0-9]+", years)  # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))

Are strongly-typed functions as parameters possible in TypeScript?

Besides what other said, a common problem is to declare the types of the same function that is overloaded. Typical case is EventEmitter on() method which will accept multiple kind of listeners. Similar could happen When working with redux actions - and there you use the action type as literal to mark the overloading, In case of EventEmitters, you use the event name literal type:

interface MyEmitter extends EventEmitter {
  on(name:'click', l: ClickListener):void
  on(name:'move', l: MoveListener):void
  on(name:'die', l: DieListener):void
  //and a generic one
  on(name:string, l:(...a:any[])=>any):void
}

type ClickListener = (e:ClickEvent)=>void
type MoveListener = (e:MoveEvent)=>void
... etc

// will type check the correct listener when writing something like:
myEmitter.on('click', e=>...<--- autocompletion

How to export a Vagrant virtual machine to transfer it

As of 2019 there is a subcommand: vagrant box repackage

vagrant box repackage --help 
Usage: vagrant box repackage <name> <provider> <version>
    -h, --help                       Print this help

You can find name provider and version by running vagrant box list

vagrant box list
macinbox (virtualbox, 10.14.5)

The ouput of vagrant box repackage is a file called package.box which is basically a tgz file which the content can be listed as below:

tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk

Responsive image map

Similar to Orland's answer here: https://stackoverflow.com/a/32870380/462781

Combined with Chris' code here: https://stackoverflow.com/a/12121309/462781

If the areas fit in a grid you can overlay the areas by transparent pictures using a width in % that keep their aspect ratio.

_x000D_
_x000D_
    .wrapperspace {_x000D_
      width: 100%;_x000D_
      display: inline-block;_x000D_
      position: relative;_x000D_
    }_x000D_
    .mainspace {_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      bottom: 0;_x000D_
      right: 0;_x000D_
      left: 0;_x000D_
    }
_x000D_
<div class="wrapperspace">_x000D_
 <img style="float: left;" title="" src="background-image.png" width="100%" />_x000D_
 <div class="mainspace">_x000D_
     <div>_x000D_
         <img src="space-top.png" style="margin-left:6%;width:15%;"/>_x000D_
     </div>_x000D_
     <div>_x000D_
       <a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:15%;"></a>_x000D_
     </div>_x000D_
  <div>_x000D_
   <a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:10%;"></a>_x000D_
   <a href="http://www.example.com"><img src="space-company.png" style="width:20%;"></a>_x000D_
  </div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can use a margin in %. Additionally "space" images can be placed next to each other inside a 3rd level div.

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

Greater than and less than in one statement

Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).

Using classes such as this you could express your constraint similar to:

if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh

with the added bonus that the range object could be defined as a constant value elsewhere in the class.

However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.

How to create a <style> tag with Javascript?

Here's a script which adds IE-style createStyleSheet() and addRule() methods to browsers which don't have them:

if(typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if(typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if(typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if(typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if(typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

You can add external files via

document.createStyleSheet('foo.css');

and dynamically create rules via

var sheet = document.createStyleSheet();
sheet.addRule('h1', 'background: red;');

Ring Buffer in Java

Since Guava 15.0 (released September 2013) there's EvictingQueue:

A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.

This class is not thread-safe, and does not accept null elements.

Example use:

EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>
</a>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

int array to string

To avoid the creation of an extra array you could do the following.

var builder = new StringBuilder();
Array.ForEach(arr, x => builder.Append(x));
var res = builder.ToString();

Comparing Class Types in Java

If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.

This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.

String hello  = "Hello";
String world = "world";

if (hello.getClass() == world.getClass()) {
    System.out.println("true");
} // prints true

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Reading specific columns from a text file in python

f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

You can do the same using a list comprehension

print([x.split(' ')[1] for x in open(file).readlines()])

Docs on split()

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.

So, you can omit the space I used and do just x.split() but this will also remove tabs and newlines, be aware of that.

Clear back stack using fragments

Reading the documentation and studying what the fragment id is, it appears to simply be the stack index, so this works:

fragmentManager.popBackStackImmediate(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Zero (0) is the the bottom of the stack, so popping up to it inclusive clears the stack.

CAVEAT: Although the above works in my program, I hesitate a bit because the FragmentManager documentation never actually states that the id is the stack index. It makes sense that it would be, and all my debug logs bare out that it is, but perhaps in some special circumstance it would not? Can any one confirm this one way or the other? If it is, then the above is the best solution. If not, this is the alternative:

while(fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); }

Redirect From Action Filter Attribute

Alternatively to a redirect, if it is calling your own code, you could use this:

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

It is not a pure redirect but gives a similar result without unnecessary overhead.

Get battery level and state in Android

try this function no need permisson or any reciver

void getBattery_percentage()
{
      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
      int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level / (float)scale;
      float p = batteryPct * 100;

      Log.d("Battery percentage",String.valueOf(Math.round(p)));
  }

preventDefault() on an <a> tag

After several operations, when the page should finally go to <a href"..."> link you can do the following:

jQuery("a").click(function(e){
    var self = jQuery(this);
    var href = self.attr('href');
    e.preventDefault();
    // needed operations

    window.location = href;
});

Print array to a file

file_put_contents($file, print_r($array, true), FILE_APPEND)

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Push existing project into Github

  1. From command line, navigate to your local repository directory.
  2. Create new repository in GitHub, it will provide you with a link ends with .git.
  3. in cmd run : git remote add origin [your_GitHub_Repository_link] (remember link should end with .git )
  4. then run : git push -u origin master

Hope this was useful.

PHP random string generator

You can try this:

<?php
    function random($len){

        $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        // ----------------------------------------------
        // Number of possible combinations
        // ----------------------------------------------
        $pos = strlen($char);
        $pos = pow($pos, $len);
        echo $pos.'<br>';
        // ----------------------------------------------

        $total = strlen($char)-1;
        $text = "";

        for ($i=0; $i<$len; $i++){
            $text = $text.$char[rand(0, $total)];
        }
        return $text;
    }

    $string = random(15);
    echo $string;
?>

You can also use md5 on time but be careful.

You need to use microtime() and not time() function, because if multiple threads run within the same second, you need to get different string for all of them.

<?php

    $string = md5(microtime());
    echo $string;
?>

How to display both icon and title of action inside ActionBar?

Some of you guys have great answers, but I found some additional thing. If you want create a MenuItem with some SubMenu programmatically:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu = menu.addSubMenu(0, Menu.NONE, 0, "Menu title");
        subMenu.getItem().setIcon(R.drawable.ic_action_child);
        subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        subMenu.add(0, Menu.NONE, 0, "Subitem 1");
        subMenu.add(0, Menu.NONE, 1, "Subitem 2");
        subMenu.add(0, Menu.NONE, 2, "Subitem 3");

        return true;
    }

Install Windows Service created in Visual Studio

Here is an alternate way to make the installer and get rid of that error message. Also it seems that VS2015 express does not have the "Add Installer" menu item.

You simply need to create a class and add the below code and add the reference System.Configuration.Install.dll.

using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;


namespace SAS
{
    [RunInstaller(true)]
    public class MyProjectInstaller : Installer
    {
        private ServiceInstaller serviceInstaller1;
        private ServiceProcessInstaller processInstaller;

        public MyProjectInstaller()
        {
            // Instantiate installer for process and service.
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller1 = new ServiceInstaller();

            // The service runs under the system account.
            processInstaller.Account = ServiceAccount.LocalSystem;

            // The service is started manually.
            serviceInstaller1.StartType = ServiceStartMode.Manual;

            // ServiceName must equal those on ServiceBase derived classes.
            serviceInstaller1.ServiceName = "SAS Service";

            // Add installer to collection. Order is not important if more than one service.
            Installers.Add(serviceInstaller1);
            Installers.Add(processInstaller);
        }
    }
}

Using ffmpeg to change framerate

You can use this command and the video duration is still unaltered.

ffmpeg -i input.mp4 -r 24 output.mp4

How to disable JavaScript in Chrome Developer Tools?

To temporarily block JavaScript on a domain :

  1. Click on the Button left to the address on the address bar (which says View site information)
  2. In the drop-down next to JavaScript, select Always block on this site
  3. Reload Page

Selenium C# WebDriver: Wait until element is present

Python:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

driver.find_element_by_id('someId').click()

WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.ID, 'someAnotherId'))

From EC (import of expected_conditions), you can choose other conditions as well. Try this: Expected conditions Support

How can I sanitize user input with PHP?

Just wanted to add that on the subject of output escaping, if you use php DOMDocument to make your html output it will automatically escape in the right context. An attribute (value="") and the inner text of a <span> are not equal. To be safe against XSS read this: OWASP XSS Prevention Cheat Sheet

How to add jQuery to an HTML page?

You can include JQuery using any of the following:

  • Link Using jQuery with a CDN

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

  • Download Jquery From Here and include in your project
  • Download latest version using this link

Your code placement can look something like this

  • Your Jquery should be included before using it any where else it will throw an error

```

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type=radio]').change(function() {

    $('input[type=radio]').each(function(index) {
        $(this).closest('tr').removeClass('selected');
    });

        $(this).closest('tr').addClass('selected');
    });
});
</script>

```

Regex to match only uppercase "words" with some exceptions

I'm not a regex guru by any means. But try:

<[A-Z0-9][A-Z0-9]+>

<           start of word
[A-Z0-9]    one character
[A-Z0-9]+   and one or more of them
>           end of word

I won't try for the bonus points of the whole upper case sentence. hehe

Unable to run Java code with Intellij IDEA

right click on the "SRC folder", select "Mark directory as:, select "Resource Root".

Then Edit the run configuration. select Run, run, edit configuration, with the plus button add an application configuration, give it a name (could be any name), and in the main class write down the full name of the main java class for example, com.example.java.MaxValues.

you might also need to check file, project structure, project settings-project, give it a folder for the compiler output, preferably a separate folder, under the java folder,

Git will not init/sync/update new submodules

Sort of magically, but today I ran git submodule init followed by git submodule sync followed by git submodule update and it started pulling my submodules... Magic? Perhaps! This is truly one of the most annoying experiences with Git…

Scratch that. I actually got it working by doing git submodule update --init --recursive. Hope this helps.

PS: Make sure you are in the root git directory, not the submodule's.

View markdown files offline

An easy solution for most situations: copy/paste the markdown into a viewer in the "cloud." Here are two choices:

  1. Dillinger.io
  2. Dingus

Nothing to install! Cross platform! Cross browser! Always available!

Disadvantages: could be hassle for large files, standard cloud application security issues.

Retrieving subfolders names in S3 bucket from boto3

The big realisation with S3 is that there are no folders/directories just keys. The apparent folder structure is just prepended to the filename to become the 'Key', so to list the contents of myBucket's some/path/to/the/file/ you can try:

s3 = boto3.client('s3')
for obj in s3.list_objects_v2(Bucket="myBucket", Prefix="some/path/to/the/file/")['Contents']:
    print(obj['Key'])

which would give you something like:

some/path/to/the/file/yo.jpg
some/path/to/the/file/meAndYou.gif
...

.prop() vs .attr()

Gary Hole answer is very relevant to solve the problem if the code is written in such way

obj.prop("style","border:1px red solid;")

Since the prop function return CSSStyleDeclaration object, above code will not working properly in some browser(tested with IE8 with Chrome Frame Plugin in my case).

Thus changing it into following code

obj.prop("style").cssText = "border:1px red solid;"

solved the problem.

Manually adding a Userscript to Google Chrome

The best thing to do is to install the Tampermonkey extension.

This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

Chrome After about August, 2014:

You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

Chrome 21+ :

Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

Older Chrome versions:

Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

You'll get an installation warning:
Initial warning

Click Continue.


You'll get a confirmation dialog:
confirmation dialog

Click Add.


Notes:

  1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

Controlling the Script and name:

By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

To control the directories and filenames to something more meaningful, you can:

  1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

  2. For each script create its own subdirectory. For example, HelloWorld.

  3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

  4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

    For our example, it should contain:

    {
        "manifest_version": 2,
        "content_scripts": [ {
            "exclude_globs":    [  ],
            "include_globs":    [ "*" ],
            "js":               [ "HelloWorld.user.js" ],
            "matches":          [   "https://stackoverflow.com/*",
                                    "https://stackoverflow.com/*"
                                ],
            "run_at": "document_end"
        } ],
        "converted_from_user_script": true,
        "description":  "My first sensibly named script!",
        "name":         "Hello World",
        "version":      "1"
    }
    

    The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

  5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

  6. Click the Load unpacked extension... button.

  7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

  8. Your script is now installed, and operational!

  9. If you make any changes to the script source, hit the Reload link for them to take effect:

    Reload link




1 The folder defaults to:

Windows XP:
  Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
  Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\

Windows Vista/7/8:
  Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
  Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\

Linux:
  Chrome  : ~/.config/google-chrome/Default/Extensions/
  Chromium: ~/.config/chromium/Default/Extensions/

Mac OS X:
  Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
  Chromium: ~/Library/Application Support/Chromium/Default/Extensions/

Although you can change it by running Chrome with the --user-data-dir= option.

Count character occurrences in a string in C++

#include <algorithm>

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');

Java 8: Difference between two LocalDateTime in multiple units

Here is a very simple answer to your question. It works.

import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class MyClass {
public static void main(String args[]) {
    DateTimeFormatter T = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
    Scanner h = new Scanner(System.in);

    System.out.print("Enter date of birth[dd/mm/yyyy hh:mm]: ");
    String b = h.nextLine();

    LocalDateTime bd = LocalDateTime.parse(b,T);
    LocalDateTime cd = LocalDateTime.now();

    long minutes = ChronoUnit.MINUTES.between(bd, cd);
    long hours = ChronoUnit.HOURS.between(bd, cd);

    System.out.print("Age is: "+hours+ " hours, or " +minutes+ " minutes old");
}
}

Adding items to end of linked list

If you keep track of the tail node, you don't need to loop through every element in the list.

Just update the tail to point to the new node:

AddValueToListEnd(value) {
    var node = new Node(value);

    if(!this.head) {
        this.head = node;
        this.tail = node;
    } else {
        this.tail.next = node; //point old tail to new node
    }
        
    this.tail = node; //now set the new node as the new tail
}

In plain English:

  • Create a new node with the given value
  • If the list is empty, point head and tail to the new node
  • If the list is not empty, set the old tail.next to be the new node
  • In either case, update the tail pointer to be the new node

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In scripts you have more options and a better shot at rational decomposition. Look into SQLCMD mode (Query Menu -> SQLCMD mode), specifically the :setvar and :r commands.

Within a stored procedure your options are very limited. You can't create define a function directly with the body of a procedure. The best you can do is something like this, with dynamic SQL:

create proc DoStuff
as begin

  declare @sql nvarchar(max)

  /*
  define function here, within a string
  note the underscore prefix, a good convention for user-defined temporary objects
  */
  set @sql = '
    create function dbo._object_name_twopart (@object_id int)
    returns nvarchar(517) as
    begin
      return 
        quotename(object_schema_name(@object_id))+N''.''+
        quotename(object_name(@object_id))
    end
  '

  /*
  create the function by executing the string, with a conditional object drop upfront
  */
  if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart
  exec (@sql)

  /*
  use the function in a query
  */
  select object_id, dbo._object_name_twopart(object_id) 
  from sys.objects
  where type = 'U'

  /*
  clean up
  */
  drop function _object_name_twopart

end
go

This approximates a global temporary function, if such a thing existed. It's still visible to other users. You could append the @@SPID of your connection to uniqueify the name, but that would then require the rest of the procedure to use dynamic SQL too.

Removing cordova plugins from the project

This is the commandline for removing plugins in Cordova

cordova plugin remove <pluginid>

For example I ran cordova plugin and got a list of plugins then I used the id for the plugin to uninstall

cordova plugin remove com.monday.contact-chooser

You can get help in the commandline by typing

cordova help <command>

What's a good IDE for Python on Mac OS X?

"Which editor/IDE for ...?" is a longstanding way to start a "My dog is too prettier than yours!" slapfest. Nowadays most editors from vim upwards can be used, there are multiple good alternatives, and even IDEs that started as C or Java tools work pretty well with Python and other dynamic languages.

That said, having tried a bunch of IDEs (Eclipse, NetBeans, XCode, Komodo, PyCharm, ...), I am a fan of ActiveState's Komodo IDE. I use it on Mac OS X primarily, though I've used it for years on Windows as well. The one license follows you to any platform.

Komodo is well-integrated with popular ActiveState builds of the languages themselves (esp. for Windows), works well with the fabulous (and Pythonic) Mercurial change management system (among others), and has good-to-excellent abilities for core tasks like code editing, syntax coloring, code completion, real-time syntax checking, and visual debugging. It is a little weak when it comes to pre-integrated refactoring and code-check tools (e.g. rope, pylint), but it is extensible and has a good facility for integrating external and custom tools.

Some of the things I like about Komodo go beyond the write-run-debug loop. ActiveState has long supported the development community (e.g. with free language builds, package repositories, a recipes site, ...), since before dynamic languages were the trend. The base Komodo Edit editor is free and open source, an extension of Mozilla's Firefox technologies. And Komodo is multi-lingual. I never end up doing just Python, just Perl, or just whatever. Komodo works with the core language (Python, Perl, Ruby, PHP, JavaScript) alongside supporting languages (XML, XSLT, SQL, X/HTML, CSS), non-dynamic languages (Java, C, etc.), and helpers (Makefiles, INI and config files, shell scripts, custom little languages, etc.) Others can do that too, but Komodo puts them all in once place, ready to go. It's a Swiss Army Knife for dynamic languages. (This is contra PyCharm, e.g., which is great itself, but I'd need like a half-dozen of JetBrains' individual IDEs to cover all the things I do).

Komodo IDE is by no means perfect, and editors/IDEs are the ultimate YMMV choice. But I am regularly delighted to use it, and every year I re-up my support subscription quite happily. Indeed, I just remembered! That's coming up this month. Credit card: Out. I have no commercial connection to ActiveState--just a happy customer.

Using AND/OR in if else PHP statement

You have 2 issues here.

  1. use == for comparison. You've used = which is for assignment.

  2. use && for "and" and || for "or". and and or will work but they are unconventional.

How can I get a JavaScript stack trace when I throw an exception?

one way to get a the real stack trace on Firebug is to create a real error like calling an undefined function:

function foo(b){
  if (typeof b !== 'string'){
    // undefined Error type to get the call stack
    throw new ChuckNorrisError("Chuck Norris catches you.");
  }
}

function bar(a){
  foo(a);
}

foo(123);

Or use console.error() followed by a throw statement since console.error() shows the stack trace.

How Stuff and 'For Xml Path' work in SQL Server?

Here is how it works:

1. Get XML element string with FOR XML

Adding FOR XML PATH to the end of a query allows you to output the results of the query as XML elements, with the element name contained in the PATH argument. For example, if we were to run the following statement:

SELECT ',' + name 
              FROM temp1
              FOR XML PATH ('')

By passing in a blank string (FOR XML PATH('')), we get the following instead:

,aaa,bbb,ccc,ddd,eee

2. Remove leading comma with STUFF

The STUFF statement literally "stuffs” one string into another, replacing characters within the first string. We, however, are using it simply to remove the first character of the resultant list of values.

SELECT abc = STUFF((
            SELECT ',' + NAME
            FROM temp1
            FOR XML PATH('')
            ), 1, 1, '')
FROM temp1

The parameters of STUFF are:

  • The string to be “stuffed” (in our case the full list of name with a leading comma)
  • The location to start deleting and inserting characters (1, we’re stuffing into a blank string)
  • The number of characters to delete (1, being the leading comma)

So we end up with:

aaa,bbb,ccc,ddd,eee

3. Join on id to get full list

Next we just join this on the list of id in the temp table, to get a list of IDs with name:

SELECT ID,  abc = STUFF(
             (SELECT ',' + name 
              FROM temp1 t1
              WHERE t1.id = t2.id
              FOR XML PATH (''))
             , 1, 1, '') from temp1 t2
group by id;

And we have our result:

Id Name
1 aaa,bbb,ccc,ddd,eee

Hope this helps!

How to calculate 1st and 3rd quartiles?

Using np.percentile.

q75, q25 = np.percentile(DataFrame, [75,25])
iqr = q75 - q25

Answer from How do you find the IQR in Numpy?

How to set all elements of an array to zero or any same value?

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

How to make a list of n numbers in Python and randomly select any number?

You can try this code

import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)

while count_list:
    value = count_list.pop()
    # do whatever you want with 'value'

String replace method is not replacing characters

package com.tulu.ds;

public class EmailSecurity {
    public static void main(String[] args) {
        System.out.println(returnSecuredEmailID("[email protected]"));
    }
    private static String returnSecuredEmailID(String email){
        String str=email.substring(1, email.lastIndexOf("@")-1);
        return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
    }
    private static String replacewith(int length,String replace) {
        String finalStr="";
        for(int i=0;i<length;i++){
            finalStr+=replace;
        }
        return finalStr;
    }   
}

Convert string to Boolean in javascript

I am still amazed how people vote blindly for solutions that won't work, like:

var myBool = myString == "true";

The above is so BUGGY!!!

Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!

Alternative

var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!

will always evaluate right!