Programs & Examples On #Looper

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a similar issue but from reading this question I figured I could run on UI thread:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        alertDialog.show();
    }
});

Seems to do the trick for me.

How to use Collections.sort() in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {

    @Override
    public int compare(Recipe o1, Recipe o2) {
        // write comparison logic here like below , it's just a sample
        return o1.getID().compareTo(o2.getID());
    }
}

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare());

How can I get an int from stdio in C?

The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.

printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);

Outputs

> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, IntelliJ could autocomplete packages, but never seemed to admit there were actual classes at any level of the hierarchy. Neither re-choosing the SDK nor re-creating the project seemed to fix it.

What did fix it was to delete the per-user IDEA directory ( in my case ~/.IntelliJIdea2017.1/) which meant losing all my other customizations... But at least it made the issue go away.

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Is it a good practice to use try-except-else in Python?

This is my simple snippet on howto understand try-except-else-finally block in Python:

def div(a, b):
    try:
        a/b
    except ZeroDivisionError:
        print("Zero Division Error detected")
    else:
        print("No Zero Division Error")
    finally:
        print("Finally the division of %d/%d is done" % (a, b))

Let's try div 1/1:

div(1, 1)
No Zero Division Error
Finally the division of 1/1 is done

Let's try div 1/0

div(1, 0)
Zero Division Error detected
Finally the division of 1/0 is done

Given URL is not permitted by the application configuration

Update to Anvesh Saxena's answer(correct but outdated as FB App interface has changed):

In your FB App configuration you need to add a Website platform with your website's URL set. Then you can add App Domains which I set to our website's base domain (e.g. for a URL like http://www.mycoolwebsite.com, just use mycoolwebsite.com).

New FB Settings Screenshot

IMPORTANT: In order for this to work you'll need to be using a subdomain of your app's URL for your local development. You can do this easily by modifying your hosts file on your development computer to use a non-existent subdomain of your website such as local.mycoolwebsite.com. Just google 'edit hosts file' for your platform (e.g. mac / windows) if you're not familiar with how to do this.

java.lang.Exception: No runnable methods exception in running JUnits

In my case, I was using the wrong Test import. The correct one was import org.junit.Test;

Create a Cumulative Sum Column in MySQL

You could also create a trigger that will calculate the sum before each insert

delimiter |

CREATE TRIGGER calCumluativeSum  BEFORE INSERT ON someTable
  FOR EACH ROW BEGIN

  SET cumulative_sum = (
     SELECT SUM(x.count)
        FROM someTable x
        WHERE x.id <= NEW.id
    )

    set  NEW.cumulative_sum = cumulative_sum;
  END;
|

I have not tested this

Use python requests to download CSV

To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently.

import requests
from contextlib import closing
import csv

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
    for row in reader:
        print row   

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

Detect if the app was launched/opened from a push notification

For swift

 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){

    ++notificationNumber
    application.applicationIconBadgeNumber =  notificationNumber;

    if let aps = userInfo["aps"] as? NSDictionary {

        var message = aps["alert"]
        println("my messages : \(message)")

    }
}

How do I load a file from resource folder?

if you are loading file in static method then ClassLoader classLoader = getClass().getClassLoader(); this might give you an error.

You can try this e.g. file you want to load from resources is resources >> Images >> Test.gif

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("Images/Test.gif");

    File file = resource.getFile();

Currently running queries in SQL Server

I use the below query

SELECT   SPID       = er.session_id
    ,STATUS         = ses.STATUS
    ,[Login]        = ses.login_name
    ,Host           = ses.host_name
    ,BlkBy          = er.blocking_session_id
    ,DBName         = DB_Name(er.database_id)
    ,CommandType    = er.command
    ,ObjectName     = OBJECT_NAME(st.objectid)
    ,CPUTime        = er.cpu_time
    ,StartTime      = er.start_time
    ,TimeElapsed    = CAST(GETDATE() - er.start_time AS TIME)
    ,SQLStatement   = st.text
FROM    sys.dm_exec_requests er
    OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
WHERE   st.text IS NOT NULL

How can you find the height of text on an HTML canvas?

one line answer

var height = parseInt(ctx.font) * 1.2; 

CSS "line-height: normal" is between 1 and 1.2

read here for more info

Does Typescript support the ?. operator? (And, what's it called?)

As answered before, it's currently still being considered but it has been dead in the water for a few years by now.

Building on the existing answers, here's the most concise manual version I can think of:

jsfiddle

function val<T>(valueSupplier: () => T): T {
  try { return valueSupplier(); } catch (err) { return undefined; }
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(val(() => obj1.a.b)); // 'c'

obj1 = { a: {} };
console.log(val(() => obj1.a.b)); // undefined
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

It simply silently fails on missing property errors. It falls back to the standard syntax for determining default value, which can be omitted completely as well.


Although this works for simple cases, if you need more complex stuff such as calling a function and then access a property on the result, then any other errors are swallowed as well. Bad design.

In the above case, an optimized version of the other answer posted here is the better option:

jsfiddle

function o<T>(obj?: T, def: T = {} as T): T {
    return obj || def;
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(o(o(o(obj1).a)).b); // 'c'

obj1 = { a: {} };
console.log(o(o(o(obj1).a)).b); // undefined
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

A more complex example:

o(foo(), []).map((n) => n.id)

You can also go the other way and use something like Lodash' _.get(). It is concise, but the compiler won't be able to judge the validity of the properties used:

console.log(_.get(obj1, 'a.b.c'));

How do I add to the Windows PATH variable using setx? Having weird problems

This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:

If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
    CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
    WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True

Advantages of this approach:

1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.

How to query MongoDB with "like"?

If you have a string variable, you must convert it to a regex, so MongoDb will use a like statement on it.

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

Is the same result as:

db.users.find({"name": /John/})

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

If you're using the new emulator that comes with Android Studio 2.0, the keyboard shortcut for the menu key is now Cmd+M, just like in Genymotion.

Alternatively, you can always send a menu button press using adb in a terminal:

adb shell input keyevent KEYCODE_MENU

Also note that the menu button shortcut isn't a strict requirement, it's just the default behavior provided by the ReactActivity Java class (which is used by default if you created your project with react-native init). Here's the relevant code from onKeyUp in ReactActivity.java:

if (keyCode == KeyEvent.KEYCODE_MENU) {
  mReactInstanceManager.showDevOptionsDialog();
  return true;
}

If you're adding React Native to an existing app (documentation here) and you aren't using ReactActivity, you'll need to hook the menu button up in a similar way. You can also call ReactInstanceManager.showDevOptionsDialog through any other mechanism. For example, in an app I'm working on, I added a dev-only Action Bar menu item that brings up the menu, since I find that more convenient than shaking the device when working on a physical device.

Which version of C# am I using

It depends upon the .NET Framework that you use. Check Jon Skeet's answer about Versions.

Here is short version of his answer.

C# 1.0 released with .NET 1.0

C# 1.2 (bizarrely enough); released with .NET 1.1

C# 2.0 released with .NET 2.0

C# 3.0 released with .NET 3.5

C# 4.0 released with .NET 4

C# 5.0 released with .NET 4.5

C# 6.0 released with .NET 4.6

C# 7.0 is released with .NET 4.6.2

C# 7.3 is released with .NET 4.7.2

C# 8.0 is released with NET Core 3.0

C# 9.0 is released with NET 5.0

How do you concatenate Lists in C#?

Concat returns a new sequence without modifying the original list. Try myList1.AddRange(myList2).

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

In my case, I had to setup the public key for another user, as I already had one for my main user. once I switched users and performed the commands in the link above I was able to perform the setup for my test server without a problem.

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

throwing exceptions out of a destructor

I am in the group that considers that the "scoped guard" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to std::terminate since destructors are implicitly annotated with noexcept.

Andrzej Krzemienski has a great post on the topic of destructors that throw:

He points out that C++11 has a mechanism to override the default noexcept for destructors:

In C++11, a destructor is implicitly specified as noexcept. Even if you add no specification and define your destructor like this:

  class MyType {
        public: ~MyType() { throw Exception(); }            // ...
  };

The compiler will still invisibly add specification noexcept to your destructor. And this means that the moment your destructor throws an exception, std::terminate will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:

  • Explicitly specify your destructor as noexcept(false),
  • Inherit your class from another one that already specifies its destructor as noexcept(false).
  • Put a non-static data member in your class that already specifies its destructor as noexcept(false).

Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to std::terminate and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using std::uncaught_exception().

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How do I insert datetime value into a SQLite database?

    This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.

    I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.

    Difference between null and empty ("") Java String

    String s=null;

    String is not initialized for null. if any string operation tried it can throw null pointer exception

    String t="null";

    It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.

    String u="";

    It is as empty string , It will not throw null pointer.

    ORDER BY using Criteria API

    You need to create an alias for the mother.kind. You do this like so.

    Criteria c = session.createCriteria(Cat.class);
    c.createAlias("mother.kind", "motherKind");
    c.addOrder(Order.asc("motherKind.value"));
    return c.list();
    

    How does String.Index work in Swift

    enter image description here

    All of the following examples use

    var str = "Hello, playground"
    

    startIndex and endIndex

    • startIndex is the index of the first character
    • endIndex is the index after the last character.

    Example

    // character
    str[str.startIndex] // H
    str[str.endIndex]   // error: after last character
    
    // range
    let range = str.startIndex..<str.endIndex
    str[range]  // "Hello, playground"
    

    With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

    let range = str.startIndex...
    let range = ..<str.endIndex
    

    I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

    after

    As in: index(after: String.Index)

    • after refers to the index of the character directly after the given index.

    Examples

    // character
    let index = str.index(after: str.startIndex)
    str[index]  // "e"
    
    // range
    let range = str.index(after: str.startIndex)..<str.endIndex
    str[range]  // "ello, playground"
    

    before

    As in: index(before: String.Index)

    • before refers to the index of the character directly before the given index.

    Examples

    // character
    let index = str.index(before: str.endIndex)
    str[index]  // d
    
    // range
    let range = str.startIndex..<str.index(before: str.endIndex)
    str[range]  // Hello, playgroun
    

    offsetBy

    As in: index(String.Index, offsetBy: String.IndexDistance)

    • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

    Examples

    // character
    let index = str.index(str.startIndex, offsetBy: 7)
    str[index]  // p
    
    // range
    let start = str.index(str.startIndex, offsetBy: 7)
    let end = str.index(str.endIndex, offsetBy: -6)
    let range = start..<end
    str[range]  // play
    

    limitedBy

    As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

    • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

    Example

    // character
    if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
        str[index]  // p
    }
    

    If the offset had been 77 instead of 7, then the if statement would have been skipped.

    Why is String.Index needed?

    It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

    It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

    GridView sorting: SortDirection always Ascending

    protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = (DataTable)Cache["GridData"];
    
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            string Field1 = e.SortExpression;
            string whichWay = "ASC";
            if (HttpContext.Current.Session[Field1] != null)
            {
                whichWay = HttpContext.Current.Session[Field1].ToString();
                if (whichWay == "ASC")
                    whichWay = "DESC";
                else
                    whichWay = "ASC";               
            }
    
            HttpContext.Current.Session[Field1] = whichWay;
            dataView.Sort = Field1 + " " + whichWay;      
            gv.DataSource = dataView;
            gv.DataBind();
        }
    }
    

    and you store the information that previously was retrieved

        string SqlConn = ConfigurationManager.ConnectionStrings["Sql28"].ConnectionString;
        SqlConnection sqlcon = new SqlConnection(SqlConn);
        sqlcon.Open();
    
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = sqlcon;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = HttpContext.Current.Session["sql"].ToString();
    
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable employees = new DataTable();
        adapter.Fill(employees);
    
        gv.DataSource = employees;
        gv.DataBind();
    
        Cache.Insert("GridData", employees, null, System.Web.Caching.Cache.NoAbsoluteExpiration,new TimeSpan(0, 360000, 0));
    

    How do I list all the columns in a table?

    Just a slight correction on the others in SQL Server (schema prefix is becoming more important!):

    SELECT name
      FROM sys.columns 
      WHERE [object_id] = OBJECT_ID('dbo.tablename');
    

    Python concatenate text files

    If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

    import glob2
    
    filenames = glob2.glob('*.txt')  # list of all .txt files in the directory
    
    with open('outfile.txt', 'w') as f:
        for file in filenames:
            with open(file) as infile:
                f.write(infile.read()+'\n')
    

    How to determine the current shell I'm working on

    Kindly use the below command:

    ps -p $$ | tail -1 | awk '{print $4}'
    

    Execute PHP script in cron job

    I had the same problem... I had to run it as a user.

    00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php
    

    Process escape sequences in a string in Python

    unicode_escape doesn't work in general

    It turns out that the string_escape or unicode_escape solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.

    If you can be sure that every non-ASCII character will be escaped (and remember, anything beyond the first 128 characters is non-ASCII), unicode_escape will do the right thing for you. But if there are any literal non-ASCII characters already in your string, things will go wrong.

    unicode_escape is fundamentally designed to convert bytes into Unicode text. But in many places -- for example, Python source code -- the source data is already Unicode text.

    The only way this can work correctly is if you encode the text into bytes first. UTF-8 is the sensible encoding for all text, so that should work, right?

    The following examples are in Python 3, so that the string literals are cleaner, but the same problem exists with slightly different manifestations on both Python 2 and 3.

    >>> s = 'naïve \\t test'
    >>> print(s.encode('utf-8').decode('unicode_escape'))
    naïve   test
    

    Well, that's wrong.

    The new recommended way to use codecs that decode text into text is to call codecs.decode directly. Does that help?

    >>> import codecs
    >>> print(codecs.decode(s, 'unicode_escape'))
    naïve   test
    

    Not at all. (Also, the above is a UnicodeError on Python 2.)

    The unicode_escape codec, despite its name, turns out to assume that all non-ASCII bytes are in the Latin-1 (ISO-8859-1) encoding. So you would have to do it like this:

    >>> print(s.encode('latin-1').decode('unicode_escape'))
    naïve    test
    

    But that's terrible. This limits you to the 256 Latin-1 characters, as if Unicode had never been invented at all!

    >>> print('Erno \\t Rubik'.encode('latin-1').decode('unicode_escape'))
    UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151'
    in position 3: ordinal not in range(256)
    

    Adding a regular expression to solve the problem

    (Surprisingly, we do not now have two problems.)

    What we need to do is only apply the unicode_escape decoder to things that we are certain to be ASCII text. In particular, we can make sure only to apply it to valid Python escape sequences, which are guaranteed to be ASCII text.

    The plan is, we'll find escape sequences using a regular expression, and use a function as the argument to re.sub to replace them with their unescaped value.

    import re
    import codecs
    
    ESCAPE_SEQUENCE_RE = re.compile(r'''
        ( \\U........      # 8-digit hex escapes
        | \\u....          # 4-digit hex escapes
        | \\x..            # 2-digit hex escapes
        | \\[0-7]{1,3}     # Octal escapes
        | \\N\{[^}]+\}     # Unicode characters by name
        | \\[\\'"abfnrtv]  # Single-character escapes
        )''', re.UNICODE | re.VERBOSE)
    
    def decode_escapes(s):
        def decode_match(match):
            return codecs.decode(match.group(0), 'unicode-escape')
    
        return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
    

    And with that:

    >>> print(decode_escapes('Erno \\t Rubik'))
    Erno     Rubik
    

    How to get domain URL and application name?

    I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().

    Get String in YYYYMMDD format from JS date object?

    Little bit simplified version for the most popular answer in this thread https://stackoverflow.com/a/3067896/5437379 :

    function toYYYYMMDD(d) {
        var yyyy = d.getFullYear().toString();
        var mm = (d.getMonth() + 101).toString().slice(-2);
        var dd = (d.getDate() + 100).toString().slice(-2);
        return yyyy + mm + dd;
    }
    

    Setting a width and height on an A tag

    All these suggestions work unless you put the anchors inside an UL list.

    <ul>
        <li>
            <a>click me</a>>
        </li>
    </ul>
    

    Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

    Well, it's fairly self-explanatory: you've run out of memory.

    You may want to try starting it with more memory, using the -Xmx flag, e.g.

    java -Xmx2048m [whatever you'd have written before]
    

    This will use up to 2 gigs of memory.

    See the non-standard options list for more details.

    How to customize <input type="file">?

    Here is a quick pure CSS workaround (works on chrome and has a FireFox fallback included), including the file name,a label and an custom upload button, does what it should - no need of JavaScript at all!

    Note: ? This works on Chrome and has a FireFox fallback - anyways, I would not use it on a real world website - if browser compatibility is a thing to you (what it should be). So it's more kind of experimental.

    _x000D_
    _x000D_
    .fileUploadInput {_x000D_
      display: grid;_x000D_
      grid-gap: 10px;_x000D_
      position: relative;_x000D_
      z-index: 1; }_x000D_
      _x000D_
      .fileUploadInput label {_x000D_
        display: flex;_x000D_
        align-items: center;_x000D_
        color: setColor(primary, 0.5);_x000D_
        background: setColor(white);_x000D_
        transition: .4s ease;_x000D_
        font-family: arial, sans-serif;_x000D_
        font-size: .75em;_x000D_
        font-weight: regular; }_x000D_
        _x000D_
      .fileUploadInput input {_x000D_
        position: relative;_x000D_
        z-index: 1;_x000D_
        padding: 0 gap(m);_x000D_
        width: 100%;_x000D_
        height: 50px;_x000D_
        border: 1px solid #323262;_x000D_
        border-radius: 3px;_x000D_
        font-family: arial, sans-serif;_x000D_
        font-size: 1rem;_x000D_
        font-weight: regular; }_x000D_
        .fileUploadInput input[type="file"] {_x000D_
          padding: 0 gap(m); }_x000D_
          .fileUploadInput input[type="file"]::-webkit-file-upload-button {_x000D_
            visibility: hidden;_x000D_
            margin-left: 10px;_x000D_
            padding: 0;_x000D_
            height: 50px;_x000D_
            width: 0; }_x000D_
            _x000D_
      .fileUploadInput button {_x000D_
        position: absolute;_x000D_
        right: 0;_x000D_
        bottom: 0;_x000D_
        width: 50px;_x000D_
        height: 50px;_x000D_
        line-height: 0;_x000D_
        user-select: none;_x000D_
        color: white;_x000D_
        background-color: #323262;_x000D_
        border-radius: 0 3px 3px 0;_x000D_
        font-family: arial, sans-serif;_x000D_
        font-size: 1rem;_x000D_
        font-weight: 800; }_x000D_
        .fileUploadInput button svg {_x000D_
          width: auto;_x000D_
          height: 50%; }_x000D_
    _x000D_
    * {_x000D_
      margin: 0px;_x000D_
      padding: 0px;_x000D_
      box-sizing: border-box;_x000D_
      border: 0px;_x000D_
      outline: 0;_x000D_
      background-repeat: no-repeat;_x000D_
      appearance: none;_x000D_
      border-radius: 0;_x000D_
      vertical-align: middle;_x000D_
      font-weight: inherit;_x000D_
      font-style: inherit;_x000D_
      font-family: inherit;_x000D_
      text-decoration: none;_x000D_
      list-style: none;_x000D_
      user-select: text;_x000D_
      line-height: 1.333em; }_x000D_
    _x000D_
    body {_x000D_
      display: flex;_x000D_
      align-items: center;_x000D_
      justify-content: center;_x000D_
      width: 100%;_x000D_
      height: 100vh;_x000D_
      background: rgba(66, 50, 98, 0.05); }_x000D_
    _x000D_
    .container {_x000D_
      padding: 25px;_x000D_
      box-shadow: 0 0 20px rgba(66, 50, 98, 0.35);_x000D_
      border: 1px solid #eaeaea;_x000D_
      border-radius: 3px;_x000D_
      background: white; }_x000D_
    _x000D_
    @-moz-document url-prefix() {_x000D_
    .fileUploadInput button{_x000D_
        display: none_x000D_
    }_x000D_
    }
    _x000D_
    <!-- Author: Ali Soueidan-->_x000D_
    <!-- Author URI: https//: www.alisoueidan.com-->_x000D_
    _x000D_
    <div class="container">_x000D_
        <div class="fileUploadInput">_x000D_
        <label>? Upload File</label>_x000D_
        <input type="file" />_x000D_
        <button>+</button></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    What is the difference between a process and a thread?

    1. Basically, a thread is a part of a process without process thread wouldn't able to work.
    2. A thread is lightweight whereas the process is heavyweight.
    3. communication between process requires some Time whereas thread requires less time.
    4. Threads can share the same memory area whereas process lives in separate.

    How to kill all processes with a given partial name?

    Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.

    killall -r my_pattern
    

    Getting the Username from the HKEY_USERS values

    You can use the command PSGetSid from Microsoft's SysInternals team.

    Download URL: http://technet.microsoft.com/en-gb/sysinternals/bb897417.aspx

    Usage:

    psgetsid [\\computer[,computer[,...] | @file] [-u username [-p password]]] [account|SID]
    -u  Specifies optional user name for login to remote computer.
    -p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
    Account PsGetSid will report the SID for the specified user account rather than the computer.
    SID PsGetSid will report the account for the specified SID.
    Computer    Direct PsGetSid to perform the command on the remote computer or computers specified. If you omit the computer name PsGetSid runs the command on the local system, and if you specify a wildcard (\\*), PsGetSid runs the command on all computers in the current domain.
    @file   PsGetSid will execute the command on each of the computers listed in the file.
    

    Example:

    psgetsid S-1-5-21-583907252-682003330-839522115-63941
    

    NB:

    • Where the user is a domain/AD(LDAP) user, running this on any computer on the domain should give the same results.
    • Where the user is local to the machine the command should either be run on that machine, or you should specify the computer via the optional parameter.

    Update

    If you use PowerShell, the following may be useful for resolving any AD users listed:

    #create a drive for HKEY USERS:
    New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue
    
    #List all immediate subfolders
    #where they're a folder (not a key)
    #and they's an SID (i.e. exclude .DEFAULT and SID_Classes entries)
    #return the SID
    #and return the related AD entry (should one exist).
    Get-ChildItem -Path 'HKU:\' `
    | ?{($_.PSIsContainer -eq $true) `
    -and ($_.PSChildName -match '^S-[\d-]+$')} `
    | select @{N='SID';E={$_.PSChildName}} `
    , @{N='Name';E={Get-ADUser $_.PSChildName | select -expand Name}}
    

    You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx

    warning: assignment makes integer from pointer without a cast

    What Jeremiah said, plus the compiler issues the warning because the production:

    *src ="anotherstring";

    says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

    -- pete

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

    Maybe you have added class with some "FirstNameClass" and after that manually rename to "ColoredDotView". Try to copy content of "ColoredDotView" class to clipboard, remove "ColoredDotView" from project and add agin.

    This id fix similar problem from me.

    How should you diagnose the error SEHException - External component has thrown an exception

    The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.

    Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.

    INNER JOIN same table

    I don't know how the table is created but try this...

    SELECT users1.user_id, users2.user_parent_id
    FROM users AS users1
    INNER JOIN users AS users2
    ON users1.id = users2.id
    WHERE users1.user_id = users2.user_parent_id
    

    How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

    Look for GSpread.NET. You can work with Google Spreadsheets by using API from Microsoft Excel. You don't need to rewrite old code with the new Google API usage. Just add a few row:

    Set objExcel = CreateObject("GSpreadCOM.Application");
    
    app.MailLogon(Name, ClientIdAndSecret, ScriptId);
    

    It's an OpenSource project and it doesn't require Office to be installed.

    The documentation available over here http://scand.com/products/gspread/index.html

    What is the preferred syntax for defining enums in JavaScript?

    This is how Typescript translates it's enum into Javascript:

    var makeEnum = function(obj) {
        obj[ obj['Active'] = 1 ] = 'Active';
        obj[ obj['Closed'] = 2 ] = 'Closed';
        obj[ obj['Deleted'] = 3 ] = 'Deleted';
    }
    

    Now:

    makeEnum( NewObj = {} )
    // => {1: "Active", 2: "Closed", 3: "Deleted", Active: 1, Closed: 2, Deleted: 3}
    

    At first I was confused why obj[1] returns 'Active', but then realised that its dead simple - Assignment operator assigns value and then returns it:

    obj['foo'] = 1
    // => 1
    

    How do I plot list of tuples in Python?

    In matplotlib it would be:

    import matplotlib.pyplot as plt
    
    data =  [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
     (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
     (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
    
    x_val = [x[0] for x in data]
    y_val = [x[1] for x in data]
    
    print x_val
    plt.plot(x_val,y_val)
    plt.plot(x_val,y_val,'or')
    plt.show()
    

    which would produce:

    enter image description here

    Using Pip to install packages to Anaconda Environment

    For those wishing to install a small number of packages in conda with pip then using,

    sudo $(which pip) install <instert_package_name>
    

    worked for me.

    Explainaton

    It seems, for me anyway, that which pip is very reliable for finding the conda env pip path to where you are. However, when using sudo, this seems to redirect paths or otherwise break this.

    Using the $(which pip) executes this independently of the sudo or any of the commands and is akin to running /home/<username>/(mini)conda(3)/envs/<env_name>/pip in Linux. This is because $() is run separately and the text output added to the outer command.

    How to detect when WIFI Connection has been established in Android?

    1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.

    2) I also tried Firebase Dispatcher which works but not beyond app killed.

    3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()

    The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.

    Also here

    In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.

    So far it works fine for us using Periodic WorkManager request.

    Update: I ended up writing 2 series medium post about it.

    UTF-8 problems while reading CSV file with fgetcsv

    The problem is that the function returns UTF-8 (it can check using mb_detect_encoding), but do not convert, and these characters takes as UTF-8. ?herefore, it's necessary to do the reverse-convert to initial encoding (Windows-1251 or CP1251) using iconv. But since by the fgetcsv returns an array, I suggest to write a custom function: [Sorry for my english]

    function customfgetcsv(&$handle, $length, $separator = ';'){
        if (($buffer = fgets($handle, $length)) !== false) {
            return explode($separator, iconv("CP1251", "UTF-8", $buffer));
        }
        return false;
    }
    

    How to read a file into vector in C++?

      //file name must be of the form filename.yourfileExtension
           std::vector<std::string> source;
    bool getFileContent(std::string & fileName)
    {
        if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
        {
    
            // Open the File
            std::ifstream in(fileName.c_str());
    
            // Check if object is valid
            if (!in)
            {
                std::cerr << "Cannot open the File : " << fileName << std::endl;
                return false;
            }
            std::string str;
            // Read the next line from File untill it reaches the end.
            while (std::getline(in, str))
            {
                // Line contains string of length > 0 then save it in vector
                if (str.size() > 0)
                    source.push_back(str);
            }
            /*for (size_t i = 0; i < source.size(); i++)
        {
            lexer(source[i], i);
            cout << source[i] << endl;
        }
        */
            //Close The File
            in.close();
            return true;
        }
        else
        {
            std::cerr << ":VIP doe\'s not support this file type" << std::endl;
            std::cerr << "supported extensions is filename.yourfileExtension" << endl;
        }
    }
    

    What does the symbol \0 mean in a string-literal?

    char str[]= "Hello\0";
    

    That would be 7 bytes.

    In memory it'd be:

    48 65 6C 6C 6F 00 00
    H  e  l  l  o  \0 \0
    

    Edit:

    • What does the \0 symbol mean in a C string?
      It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

    • What is the length of str array? (Answered before the edit part)
      7

    • and with how much 0s it is ending?
      You array has two "spaces" with zero; str[5]=str[6]='\0'=0

    Extra example:
    Let's assume you have a function that prints the content of that text array. You could define it as:

    char str[40];
    

    Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

    54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
    69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00
    

    So you print that char array. And then you want a new message. Let's say just "Hello"

    48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
    69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00
    

    Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

    What are naming conventions for MongoDB?

    Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

    Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

    Please do vote.

    How to split a data frame?

    If you want to split by values in one of the columns, you can use lapply. For instance, to split ChickWeight into a separate dataset for each chick:

    data(ChickWeight)
    lapply(unique(ChickWeight$Chick), function(x) ChickWeight[ChickWeight$Chick == x,])
    

    How to make a Java thread wait for another thread's output?

    The Future interface from the java.lang.concurrent package is designed to provide access to results calculated in another thread.

    Take a look at FutureTask and ExecutorService for a ready-made way of doing this kind of thing.

    I'd strongly recommend reading Java Concurrency In Practice to anyone interested in concurrency and multithreading. It obviously concentrates on Java, but there is plenty of meat for anybody working in other languages too.

    How to use the divide function in the query?

    Try something like this

    select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
    from CSPGI09_OVERSHIPMENT
    

    I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.

    Gradient of n colors ranging from color 1 and color 2

    Just to expand on the previous answer colorRampPalettecan handle more than two colors.

    So for a more expanded "heat map" type look you can....

    colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
    plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)
    

    The resulting image:

    enter image description here

    How to add "required" attribute to mvc razor viewmodel text input editor

    @Erik's answer didn't fly for me.

    Following did:

     @Html.TextBoxFor(m => m.ShortName,  new { data_val_required = "You need me" })
    

    plus doing this manually under field I had to add error message container

    @Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
    

    Hope this saves you some time.

    Bootstrap 4 align navbar items to the right

    Just add mr-auto class at ul:

    <ul class="nav navbar-nav mr-auto">
    

    If you have menu list in both side you can do something like this:

    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">left 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">left 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">left disable</a>
      </li>
    </ul>
    

    GROUP BY without aggregate function

    Given this data:

    Col1  Col2  Col3
     A     X     1
     A     Y     2
     A     Y     3
     B     X     0
     B     Y     3
     B     Z     1
    

    This query:

    SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3
    

    Would result in exactly the same table.

    However, this query:

    SELECT Col1, Col2 FROM data GROUP BY Col1, Col2
    

    Would result in:

    Col1  Col2
     A     X  
     A     Y  
     B     X  
     B     Y  
     B     Z  
    

    Now, a query:

    SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2
    

    Would create a problem: the line with A, Y is the result of grouping the two lines

     A     Y     2
     A     Y     3
    

    So, which value should be in Col3, '2' or '3'?

    Normally you would use a GROUP BY to calculate e.g. a sum:

    SELECT Col1, Col2, SUM(Col3) FROM data GROUP BY Col1, Col2
    

    So in the line, we had a problem with we now get (2+3) = 5.

    Grouping by all your columns in your select is effectively the same as using DISTINCT, and it is preferable to use the DISTINCT keyword word readability in this case.

    So instead of

    SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3
    

    use

    SELECT DISTINCT Col1, Col2, Col3 FROM data
    

    Loading a properties file from Java package

    When loading the Properties from a Class in the package com.al.common.email.templates you can use

    Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("foo.properties");
    prop.load(in);
    in.close();
    

    (Add all the necessary exception handling).

    If your class is not in that package, you need to aquire the InputStream slightly differently:

    InputStream in = 
     getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
    

    Relative paths (those without a leading '/') in getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.

    Using java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file /java/lang/String/foo.txt on the classpath.

    Using an absolute path (one that starts with '/') means that the current package is ignored.

    How do I count a JavaScript object's attributes?

    There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

    Here's one way:

    var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
    Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted
    
    var count = 0;
    for (var k in foo) {
        if (foo.hasOwnProperty(k)) {
           ++count;
        }
    }
    alert("Found " + count + " properties specific to foo");
    

    The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

    Read text from response

    The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.

    To perform an HTTP GET and read the response text, do the following.

    .NET 1.1 - 4.0

    public static string GetResponseText(string address)
    {
        var request = (HttpWebRequest)WebRequest.Create(address);
    
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            var encoding = Encoding.GetEncoding(response.CharacterSet);
    
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream, encoding))
                return reader.ReadToEnd();
        }
    }
    

    .NET 4.5

    private static readonly HttpClient httpClient = new HttpClient();
    
    public static async Task<string> GetResponseText(string address)
    {
        return await httpClient.GetStringAsync(address);
    }
    

    How do I select between the 1st day of the current month and current day in MySQL?

    SET @date:='2012-07-11';
    SELECT date_add(date_add(LAST_DAY(@date),interval 1 DAY), 
           interval -1 MONTH) AS first_day
    

    Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

    I think the solution is to combine techniques from video encoding, namely the discrete cosine transformation. In digital video, rather recording the changing the brightness or colour of video as regular values such as 110 112 115 116, each is subtracted from the last (similar to run length encoding). 110 112 115 116 becomes 110 2 3 1. The values, 2 3 1 require less bits than the originals.

    So lets say we create a list of the input values as they arrive on the socket. We are storing in each element, not the value, but the offset of the one before it. We sort as we go, so the offsets are only going to be positive. But the offset could be 8 decimal digits wide which this fits in 3 bytes. Each element can't be 3 bytes, so we need to pack these. We could use the top bit of each byte as a "continue bit", indicating that the next byte is part of the number and the lower 7 bits of each byte need to be combined. zero is valid for duplicates.

    As the list fills up, the numbers should be get closer together, meaning on average only 1 byte is used to determine the distance to the next value. 7 bits of value and 1 bit of offset if convenient, but there may be a sweet spot that requires less than 8 bits for a "continue" value.

    Anyway, I did some experiment. I use a random number generator and I can fit a million sorted 8 digit decimal numbers into about 1279000 bytes. The average space between each number is consistently 99...

    public class Test {
        public static void main(String[] args) throws IOException {
            // 1 million values
            int[] values = new int[1000000];
    
            // create random values up to 8 digits lrong
            Random random = new Random();
            for (int x=0;x<values.length;x++) {
                values[x] = random.nextInt(100000000);
            }
            Arrays.sort(values);
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            int av = 0;    
            writeCompact(baos, values[0]);     // first value
            for (int x=1;x<values.length;x++) {
                int v = values[x] - values[x-1];  // difference
                av += v;
                System.out.println(values[x] + " diff " + v);
                writeCompact(baos, v);
            }
    
            System.out.println("Average offset " + (av/values.length));
            System.out.println("Fits in " + baos.toByteArray().length);
        }
    
        public static void writeCompact(OutputStream os, long value) throws IOException {
            do {
                int b = (int) value & 0x7f;
                value = (value & 0x7fffffffffffffffl) >> 7;
                os.write(value == 0 ? b : (b | 0x80));
            } while (value != 0);
        }
    }
    

    Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

    I'm not really sure this question is approprate here, but you can add a new "Build System" under Tools -> Build System -> New Build System...

    As with all configuration in Sublime Text its just JSON, so it should be pretty straight forward. The main thing you are going to want to configure is the "cmd" key/val. Here is the build config for launching chrome on my mac.

    {
        "cmd": ["open", "-a", "Google Chrome", "$file"]
    }
    

    Save that as Chrome.sublime-build, relaunch Sublime Text and you should see a new Chrome option in the build list. Select it, and then you should be able to launch Chrome with Cmd+B on a Mac (or whatever hotkey you have configured for build, maybe its F7 or Ctrl+B on a Windows machine)

    At least this should give you a push in the right direction.

    Edit:

    Another thing I end up doing a lot in Sublime Text 2 is if you right click inside a document, one of the items in the context menu is Copy File Path, which puts the current file's full path into the clipboard for easy pasting into whatever browser you want.


    Sublime Text 3 (linux example) "shell_cmd": "google-chrome '$file'"

    How do I find out what version of WordPress is running?

    Open the blog, Check source once the blog is open. It should have a meta tag like:

    <meta name="generator" content="WordPress 2.8.4" />
    

    Set variable with multiple values and use IN

    Ideally you shouldn't be splitting strings in T-SQL at all.

    Barring that change, on older versions before SQL Server 2016, create a split function:

    CREATE FUNCTION dbo.SplitStrings
    (
        @List      nvarchar(max), 
        @Delimiter nvarchar(2)
    )
    RETURNS TABLE
    WITH SCHEMABINDING
    AS
      RETURN ( WITH x(x) AS
        (
          SELECT CONVERT(xml, N'<root><i>' 
            + REPLACE(@List, @Delimiter, N'</i><i>') 
            + N'</i></root>')
        )
        SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
          FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
      );
    GO
    

    Now you can say:

    DECLARE @Values varchar(1000);
    
    SET @Values = 'A, B, C';
    
    SELECT blah
      FROM dbo.foo
      INNER JOIN dbo.SplitStrings(@Values, ',') AS s
        ON s.Item = foo.myField;
    

    On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

    DECLARE @Values varchar(1000) = 'A, B, C';
    
    SELECT blah
      FROM dbo.foo
      INNER JOIN STRING_SPLIT(@Values, ',') AS s
        ON LTRIM(s.value) = foo.myField;
    

    How can I get useful error messages in PHP?

    if you are a ubuntu user then goto your terminal and run this command

    sudo tail -50f /var/log/apache2/error.log
    

    where it will display recent 50 errors. There is a error file error.log for apache2 which logs all the errors.

    Download file and automatically save it to folder

    Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:

        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            e.Cancel = true;
            WebClient client = new WebClient();
    
            client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
    
            client.DownloadDataAsync(e.Url);
        }
    
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            string filepath = textBox1.Text;
            File.WriteAllBytes(filepath, e.Result);
            MessageBox.Show("File downloaded");
        }
    

    CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

    Just try this line:

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    

    after:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    

    Page redirect with successful Ajax request

    Another option is:

    window.location.replace("your_url")
    

    Laravel 5.4 create model, controller and migration in single artisan command

    Instead of using long command like

    php artisan make:model <Model Name> --migration --controller --resource
    

    for make migration, model and controller, you may use even shorter as -mcr.

    php artisan make:model <Model Name> -mcr
    

    For more MOST USEFUL LARAVEL ARTISAN MAKE COMMANDS LISTS

    How to use ArrayAdapter<myClass>

    You could just add a toString() method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:

    However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

    class MyClass {
    
     @Override
     public String toString() {
      return "Hello, world.";
     }
    }
    

    python : list index out of range error while iteratively popping elements

    I think the best way to solve this problem is:

    l = [1, 2, 3, 0, 0, 1]
    while 0 in l:
        l.remove(0)
    

    Instead of iterating over list I remove 0 until there aren't any 0 in list

    ruby 1.9: invalid byte sequence in UTF-8

    I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:

    ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
    ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
    t = ec2.convert ec1.convert t
    

    Set android shape color programmatically

    Expanding on Vikram's answer, if you are coloring dynamic views, like recycler view items, etc.... Then you probably want to call mutate() before you set the color. If you don't do this, any views that have a common drawable (i.e a background) will also have their drawable changed/colored.

    public static void setBackgroundColorAndRetainShape(final int color, final Drawable background) {
    
        if (background instanceof ShapeDrawable) {
            ((ShapeDrawable) background.mutate()).getPaint().setColor(color);
        } else if (background instanceof GradientDrawable) {
            ((GradientDrawable) background.mutate()).setColor(color);
        } else if (background instanceof ColorDrawable) {
            ((ColorDrawable) background.mutate()).setColor(color);
        }else{
            Log.w(TAG,"Not a valid background type");
        }
    
    }
    

    How to get a shell environment variable in a makefile?

    for those who want some official document to confirm the behavior

    Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

    https://www.gnu.org/software/make/manual/html_node/Environment.html

    How to convert base64 string to image?

    You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

    import cv2
    import numpy as np
    
    def save(encoded_data, filename):
        nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
        return cv2.imwrite(filename, img)
    

    Then somewhere in your code you can use it like this:

    save(base_64_string, 'testfile.png');
    save(base_64_string, 'testfile.jpg');
    save(base_64_string, 'testfile.bmp');
    

    Calculating difference between two timestamps in Oracle in milliseconds

    Here's a stored proc to do it:

    CREATE OR REPLACE function timestamp_diff(a timestamp, b timestamp) return number is 
    begin
      return extract (day    from (a-b))*24*60*60 +
             extract (hour   from (a-b))*60*60+
             extract (minute from (a-b))*60+
             extract (second from (a-b));
    end;
    /
    

    Up Vote if you also wanted to beat the crap out of the Oracle developer who negated to his job!

    BECAUSE comparing timestamps for the first time should take everyone an hour or so...

    Update value of a nested dictionary of varying depth

    The code below should solve the update({'k1': 1}, {'k1': {'k2': 2}}) issue in @Alex Martelli's answer the right way.

    def deepupdate(original, update):
        """Recursively update a dict.
    
        Subdict's won't be overwritten but also updated.
        """
        if not isinstance(original, abc.Mapping):
            return update
        for key, value in update.items():
            if isinstance(value, abc.Mapping):
                original[key] = deepupdate(original.get(key, {}), value)
            else:
                original[key] = value
        return original
    

    calling Jquery function from javascript

    jQuery functions are called just like JavaScript functions.

    For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:

    $("#orderedlist").addClass("red");
    

    As opposed to a regular line of JavaScript calling a regular function:

    var x = document.getElementById("orderedlist");
    

    addClass() is a jQuery function, getElementById() is a JavaScript function.

    The dollar sign function makes the jQuery addClass function available.

    The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.

    In your code

    $(function() {
    // code to execute when the DOM is ready
    });
    

    Is used to specify code to run when the DOM is ready.

    It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.

    So, to answer your question, just call functions you defined as you normally would.

    //create a function
    function my_fun(){
      // call a jQuery function:
      $("#orderedlist").addClass("red");
    }
    
    //call the function you defined:
    myfun();
    

    When to use throws in a Java method declaration?

    If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

    Typically, if you are not going to do anything with the exception, you should not catch it.

    The most dangerous thing you can do is catch an exception and not do anything with it.

    A good discussion of when it is appropriate to throw exceptions is here

    When to throw an exception?

    How do you split and unsplit a window/view in Eclipse IDE?

    This is possible with the menu items Window>Editor>Toggle Split Editor.

    Current shortcut for splitting is:

    Azerty keyboard:

    • Ctrl + _ for split horizontally, and
    • Ctrl + { for split vertically.

    Qwerty US keyboard:

    • Ctrl + Shift + - (accessing _) for split horizontally, and
    • Ctrl + Shift + [ (accessing {) for split vertically.

    MacOS - Qwerty US keyboard:

    • + Shift + - (accessing _) for split horizontally, and
    • + Shift + [ (accessing {) for split vertically.

    On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

    • Alt + ASCII code + Ctrl then release Alt

    Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

    Example of vertical split:

    https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

    PS:

    • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
    • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
    • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

    When should I really use noexcept?

    When can I realistically except to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

    Um, never? Is never a time? Never.

    noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never.

    noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something. So noexcept is not a matter of giving the compiler hints about how to optimize a function so much as giving you hints about how to use a function.

    Templates like move_if_noexcept will detect if the move constructor is defined with noexcept and will return a const& instead of a && of the type if it is not. It's a way of saying to move if it is very safe to do so.

    In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.

    In short: use it for move constructors and similar constructs, but don't feel like you have to go nuts with it.

    Display calendar to pick a date in java

    I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import org.jdesktop.swingx.JXDatePicker;
    
    public class DatePickerExample extends JPanel {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame("JXPicker Example");
            JPanel panel = new JPanel();
    
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(400, 400, 250, 100);
    
            JXDatePicker picker = new JXDatePicker();
            picker.setDate(Calendar.getInstance().getTime());
            picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));
    
            panel.add(picker);
            frame.getContentPane().add(panel);
    
            frame.setVisible(true);
        }
    }
    

    How to scroll to bottom in a ScrollView on activity startup

    This is the best way of doing this.

    scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
    });
    

    SQL Query - Using Order By in UNION

    SELECT field1 FROM table1
    UNION
    SELECT field1 FROM table2
    ORDER BY field1
    

    How to get input field value using PHP

    Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.

    For Example, change the method in your form and then echo out the value by the name of the input:

    Using $_GET method:

    <form name="form" action="" method="get">
      <input type="text" name="subject" id="subject" value="Car Loan">
    </form>
    

    To show the value:

    <?php echo $_GET['subject']; ?>
    

    Using $_POST method:

    <form name="form" action="" method="post">
      <input type="text" name="subject" id="subject" value="Car Loan">
    </form>
    

    To show the value:

    <?php echo $_POST['subject']; ?>
    

    How to update an "array of objects" with Firestore?

    Other than the answers mentioned above. This will do it. Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

      // say you have have the following object and 
      // database structure as you mentioned in your post
      data = { who: "[email protected]", when: new Date() };
    
      ...othercode
    
    
      addSharedWith(data) {
    
        const postDocRef = this.afs.collection('posts').doc('docID');
    
        postDocRef.subscribe( post => {
    
          // Grab the existing sharedWith Array
          // If post.sharedWith doesn`t exsit initiated with empty array
          const foo = { 'sharedWith' : post.sharedWith || []};
    
          // Grab the existing sharedWith Array
          foo['sharedWith'].push(data);
    
          // pass updated to fireStore
          postsDocRef.update(foo);
          // using .set() will overwrite everything
          // .update will only update existing values, 
          // so we initiated sharedWith with empty array
        });
     }  
    

    Codeigniter: does $this->db->last_query(); execute a query?

    For me save_queries option was turned off so,

    $this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
    $str = $this->db->last_query();
    echo $str;
    

    Ref: Can't get result from $this->db->last_query(); codeigniter

    What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

    nchar requires more space than nvarchar.

    eg,

    A nchar(100) will always store 100 characters even if you only enter 5, the remaining 95 chars will be padded with spaces. Storing 5 characters in a nvarchar(100) will save 5 characters.

    Is the buildSessionFactory() Configuration method deprecated in Hibernate

    If you are using Hibernate 5.2 and above then you can use this:

      private static StandardServiceRegistry registry;
      private static SessionFactory sessionFactory;
    
      public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
          try {
            // Creating a registry
            registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
    
            // Create the MetadataSources
            MetadataSources sources = new MetadataSources(registry);
    
            // Create the Metadata
            Metadata metadata = sources.getMetadataBuilder().build();
    
            // Create SessionFactory
            sessionFactory = metadata.getSessionFactoryBuilder().build();
    
          } catch (Exception e) {
            e.printStackTrace();
            if (registry != null) {
              StandardServiceRegistryBuilder.destroy(registry);
            }
          }
        }
        return sessionFactory;
      }
    
      //To shut down
     public static void shutdown() {
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    

    Insert and set value with max()+1 problems

    We declare a variable 'a'

    SET **@a** = (SELECT MAX( customer_id ) FROM customers) +1;
    
    INSERT INTO customers
      ( customer_id, firstname, surname )
    VALUES 
      (**@a**, 'jim', 'sock')
    

    Parcelable encountered IOException writing serializable object getactivity()

    Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode
    

    Your DSLL class appears to have a DNode static inner class, and DNode is not Serializable.

    Change background color of selected item on a ListView

    You can keep track the position of the current selected element:

        OnItemClickListener listViewOnItemClick = new OnItemClickListener() {
    
            @Override
            public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                    mSelectedItem = position;
                    mAdapter.notifyDataSetChanged();
            }
        };
    

    And override the getView method of your adapter:

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final View view = View.inflate(context, R.layout.item_list, null);
    
            if (position == mSelectedItem) {
                // set your color
            }
    
            return view;
        }
    

    For me it did the trick.

    Excel function to make SQL-like queries on worksheet data?

    If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.

    The MSDN information on how to hit Excel using ADO can be found here.

    How should I throw a divide by zero exception in Java without actually dividing by zero?

    Do this:

    if (denominator == 0) throw new ArithmeticException("denominator == 0");
    

    ArithmeticException is the exception which is normally thrown when you divide by 0.

    Using SimpleXML to create an XML object from scratch

    In PHP5, you should use the Document Object Model class instead. Example:

    $domDoc = new DOMDocument;
    $rootElt = $domDoc->createElement('root');
    $rootNode = $domDoc->appendChild($rootElt);
    
    $subElt = $domDoc->createElement('foo');
    $attr = $domDoc->createAttribute('ah');
    $attrVal = $domDoc->createTextNode('OK');
    $attr->appendChild($attrVal);
    $subElt->appendChild($attr);
    $subNode = $rootNode->appendChild($subElt);
    
    $textNode = $domDoc->createTextNode('Wow, it works!');
    $subNode->appendChild($textNode);
    
    echo htmlentities($domDoc->saveXML());
    

    How can I alter a primary key constraint using SQL syntax?

    you can rename constraint objects using sp_rename (as described in this answer)

    for example:

    EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint'
    

    How can I append a string to an existing field in MySQL?

    Update image field to add full URL, ignoring null fields:

    UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
    

    Java Pass Method as Parameter

    If you don't need these methods to return something, you could make them return Runnable objects.

    private Runnable methodName (final int arg) {
        return (new Runnable() {
            public void run() {
              // do stuff with arg
            }
        });
    }
    

    Then use it like:

    private void otherMethodName (Runnable arg){
        arg.run();
    }
    

    VB.NET Inputbox - How to identify when the Cancel Button is pressed?

    Try this. I've tried the solution and it works.

    Dim ask = InputBox("")
    If ask.Length <> 0 Then
       // your code
    Else
       // cancel or X Button 
    End If
    

    Simple way to query connected USB devices info in Python?

    If you are working on windows, you can use pywin32 (old link: see update below).

    I found an example here:

    import win32com.client
    
    wmi = win32com.client.GetObject ("winmgmts:")
    for usb in wmi.InstancesOf ("Win32_USBHub"):
        print usb.DeviceID
    

    Update Apr 2020:

    'pywin32' release versions from 218 and up can be found here at github. Current version 227.

    Prevent Sequelize from outputting SQL to the console on execution of query?

    All of these answers are turned off the logging at creation time.

    But what if we need to turn off the logging on runtime ?

    By runtime i mean after initializing the sequelize object using new Sequelize(.. function.

    I peeked into the github source, found a way to turn off logging in runtime.

    // Somewhere your code, turn off the logging
    sequelize.options.logging = false
    
    // Somewhere your code, turn on the logging
    sequelize.options.logging = true 
    

    installing urllib in Python3.6

    yu have to install the correct version for your computer 32 or 63 bits thats all

    Add a reference column migration in Rails 4

    Rails 4.x

    When you already have users and uploads tables and wish to add a new relationship between them.

    All you need to do is: just generate a migration using the following command:

    rails g migration AddUserToUploads user:references
    

    Which will create a migration file as:

    class AddUserToUploads < ActiveRecord::Migration
      def change
        add_reference :uploads, :user, index: true
      end
    end
    

    Then, run the migration using rake db:migrate. This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

    UPDATE [For Rails 4.2]

    Rails can’t be trusted to maintain referential integrity; relational databases come to our rescue here. What that means is that we can add foreign key constraints at the database level itself and ensure that database would reject any operation that violates this set referential integrity. As @infoget commented, Rails 4.2 ships with native support for foreign keys(referential integrity). It's not required but you might want to add foreign key(as it's very useful) to the reference that we created above.

    To add foreign key to an existing reference, create a new migration to add a foreign key:

    class AddForeignKeyToUploads < ActiveRecord::Migration
      def change
        add_foreign_key :uploads, :users
      end
    end
    

    To create a completely brand new reference with a foreign key(in Rails 4.2), generate a migration using the following command:

    rails g migration AddUserToUploads user:references
    

    which will create a migration file as:

    class AddUserToUploads < ActiveRecord::Migration
      def change
        add_reference :uploads, :user, index: true
        add_foreign_key :uploads, :users
      end
    end
    

    This will add a new foreign key to the user_id column of the uploads table. The key references the id column in users table.

    NOTE: This is in addition to adding a reference so you still need to create a reference first then foreign key (you can choose to create a foreign key in the same migration or a separate migration file). Active Record only supports single column foreign keys and currently only mysql, mysql2 and PostgreSQL adapters are supported. Don't try this with other adapters like sqlite3, etc. Refer to Rails Guides: Foreign Keys for your reference.

    Find character position and update file name

    If you're working with actual files (as opposed to some sort of string data), how about the following?

    $files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }
    

    (or use _.+$ if you want to cut everything from the first underscore.)

    Passing parameter to controller action from a Html.ActionLink

    You are using incorrect overload. You should use this overload

    public static MvcHtmlString ActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string actionName,
        string controllerName,
        Object routeValues,
        Object htmlAttributes
    ) 
    

    And the correct code would be

    <%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
    

    Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

    C++ convert string to hexadecimal and vice versa

    Why has nobody used sprintf?

    #include <string>
    #include <stdio.h>
    
    static const std::string str = "hello world!";
    
    int main()
    {
      //copy the data from the string to a char array
      char *strarr = new char[str.size()+1];
      strarr[str.size()+1] = 0; //set the null terminator
      memcpy(strarr, str.c_str(),str.size()); //memory copy to the char array
    
      printf(strarr);
      printf("\n\nHEX: ");
    
      //now print the data
      for(int i = 0; i < str.size()+1; i++)
      {
        char x = strarr[i];
        sprintf("%x ", reinterpret_cast<const char*>(x));
      }
    
      //DO NOT FORGET TO DELETE
      delete(strarr);
    
      return 0;
    }
    

    java.lang.IllegalArgumentException: No converter found for return value of type

    Faced same error recently - the pojo had getters/setters and all jackson dependencies were imported in pom correctly but some how "< scope > " was "provided" for jackson dependency and this caused the issue. Removing " < Scope > " from jackson dependency fixed the issue

    How to put labels over geom_bar in R with ggplot2

    To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

    dfl <- ddply(df, .(x), summarize, y=length(x))
    str(dfl)
    

    Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

    ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
        geom_text(aes(label=y), vjust=0) +
        opts(axis.text.x=theme_blank(),
            axis.ticks=theme_blank(),
            axis.title.x=theme_blank(),
            legend.title=theme_blank(),
            axis.title.y=theme_blank()
    )
    

    enter image description here

    Encoding URL query parameters in Java

    EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


    URIUtil of Apache httpclient is really useful, although there are some alternatives

    URIUtil.encodeQuery(url);
    

    For example, it encodes space as "+" instead of "%20"

    Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

    Python Graph Library

    I would like to plug my own graph python library: graph-tool.

    It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.

    Removing specific rows from a dataframe

    This boils down to two distinct steps:

    1. Figure out when your condition is true, and hence compute a vector of booleans, or, as I prefer, their indices by wrapping it into which()
    2. Create an updated data.frame by excluding the indices from the previous step.

    Here is an example:

    R> set.seed(42)
    R> DF <- data.frame(sub=rep(1:4, each=4), day=sample(1:4, 16, replace=TRUE))
    R> DF
       sub day
    1    1   4
    2    1   4
    3    1   2
    4    1   4
    5    2   3
    6    2   3
    7    2   3
    8    2   1
    9    3   3
    10   3   3
    11   3   2
    12   3   3
    13   4   4
    14   4   2
    15   4   2
    16   4   4
    R> ind <- which(with( DF, sub==2 & day==3 ))
    R> ind
    [1] 5 6 7
    R> DF <- DF[ -ind, ]
    R> table(DF)
       day
    sub 1 2 3 4
      1 0 1 0 3
      2 1 0 0 0
      3 0 1 3 0
      4 0 2 0 2
    R> 
    

    And we see that sub==2 has only one entry remaining with day==1.

    Edit The compound condition can be done with an 'or' as follows:

    ind <- which(with( DF, (sub==1 & day==2) | (sub=3 & day=4) ))
    

    and here is a new full example

    R> set.seed(1)
    R> DF <- data.frame(sub=rep(1:4, each=5), day=sample(1:4, 20, replace=TRUE))
    R> table(DF)
       day
    sub 1 2 3 4
      1 1 2 1 1
      2 1 0 2 2
      3 2 1 1 1
      4 0 2 1 2
    R> ind <- which(with( DF, (sub==1 & day==2) | (sub==3 & day==4) ))
    R> ind
    [1]  1  2 15
    R> DF <- DF[-ind, ]
    R> table(DF)
       day
    sub 1 2 3 4
      1 1 0 1 1
      2 1 0 2 2
      3 2 1 1 0
      4 0 2 1 2
    R> 
    

    R barplot Y-axis scale too short

    I see you try to set ylim but you give bad values. This will change the scale of the plot (like a zoom). For example see this:

    par(mfrow=c(2,1))
    tN <- table(Ni <- stats::rpois(100, lambda = 5))
    r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
    r <- barplot(tN, col = rainbow(20),main='short y axis')
    

    enter image description here Another option is to plot without axes and set them manually using axis and usr:

    require(grDevices) # for colours
    par(mfrow=c(1,1))
    r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
    usr <- par("usr")
    par(usr=c(usr[1:2], 0, 20))
    axis(2,at=seq(0,20,5))
    

    enter image description here

    No Android SDK found - Android Studio

    Try make New Project, and then choose same android version that you've installed sdk verions on "Target Android Device" dialog. In my case, error message gone.

    phpMyAdmin on MySQL 8.0

    As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.

    I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.

    MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.

    Good way to encapsulate Integer.parseInt()

    This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.

    Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)

    Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:

    public class IntBoxSimple {
        // IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
        // A full blown IntBox class implementation can be found in my Github project
        // Copyright (c) 2016, Peter Sulzer, Fürth
        // Program is published under the GNU General Public License (GPL) Version 1 or newer
    
        protected int _n; // this "boxes" the int value
    
        // BEGIN The following statements are only executed at the
        // first instantiation of an IntBox (i. e. only once) or
        // already compiled into the code at compile time:
        public static final int MAX_INT_LEN =
                String.valueOf(Integer.MAX_VALUE).length();
        public static final int MIN_INT_LEN =
                String.valueOf(Integer.MIN_VALUE).length();
        public static final int MAX_INT_LASTDEC =
                Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
        public static final int MAX_INT_FIRSTDIGIT =
                Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
        public static final int MIN_INT_LASTDEC =
                -Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
        public static final int MIN_INT_FIRSTDIGIT =
                Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
        // END The following statements...
    
        // ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
        public static String ltrimZeroes(String s) {
            if (s.charAt(0) == '-')
                return ltrimZeroesNegative(s);
            else
                return ltrimZeroesPositive(s);
        }
        protected static String ltrimZeroesNegative(String s) {
            int i=1;
            for ( ; s.charAt(i) == '0'; i++);
            return ("-"+s.substring(i));
        }
        protected static String ltrimZeroesPositive(String s) {
            int i=0;
            for ( ; s.charAt(i) == '0'; i++);
            return (s.substring(i));
        }
    
        public static boolean tryParse(String s,IntBoxSimple intBox) {
            if (intBox == null)
                // intBoxSimple=new IntBoxSimple(); // This doesn't work, as
                // intBoxSimple itself is passed by value and cannot changed
                // for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
                return false; // so we simply return false
            s=s.trim(); // leading and trailing whitespace is allowed for String s
            int len=s.length();
            int rslt=0, d, dfirst=0, i, j;
            char c=s.charAt(0);
            if (c == '-') {
                if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
                    s = ltrimZeroesNegative(s);
                    len = s.length();
                }
                if (len >= MIN_INT_LEN) {
                    c = s.charAt(1);
                    if (!Character.isDigit(c))
                        return false;
                    dfirst = c-'0';
                    if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
                        return false;
                }
                for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
                    c = s.charAt(i);
                    if (!Character.isDigit(c))
                        return false;
                    rslt -= (c-'0')*j;
                }
                if (len < MIN_INT_LEN) {
                    c = s.charAt(i);
                    if (!Character.isDigit(c))
                        return false;
                    rslt -= (c-'0')*j;
                } else {
                    if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
                        return false;
                    rslt -= dfirst * j;
                }
            } else {
                if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
                    s = ltrimZeroesPositive(s);
                    len=s.length();
                }
                if (len >= MAX_INT_LEN) {
                    c = s.charAt(0);
                    if (!Character.isDigit(c))
                        return false;
                    dfirst = c-'0';
                    if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
                        return false;
                }
                for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
                    c = s.charAt(i);
                    if (!Character.isDigit(c))
                        return false;
                    rslt += (c-'0')*j;
                }
                if (len < MAX_INT_LEN) {
                    c = s.charAt(i);
                    if (!Character.isDigit(c))
                        return false;
                    rslt += (c-'0')*j;
                }
                if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
                    return false;
                rslt += dfirst*j;
            }
            intBox._n=rslt;
            return true;
        }
    
        // Get the value stored in an IntBoxSimple:
        public int get_n() {
            return _n;
        }
        public int v() { // alternative shorter version, v for "value"
            return _n;
        }
        // Make objects of IntBoxSimple (needed as constructors are not public):
        public static IntBoxSimple makeIntBoxSimple() {
            return new IntBoxSimple();
        }
        public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
            return new IntBoxSimple(integerNumber);
        }
    
        // constructors are not public(!=:
        protected IntBoxSimple() {} {
            _n=0; // default value an IntBoxSimple holds
        }
        protected IntBoxSimple(int integerNumber) {
            _n=integerNumber;
        }
    }
    

    Test/example program for class IntBoxSimple:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class IntBoxSimpleTest {
        public static void main (String args[]) {
            IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
            String in = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            do {
                System.out.printf(
                        "Enter an integer number in the range %d to %d:%n",
                            Integer.MIN_VALUE, Integer.MAX_VALUE);
                try { in = br.readLine(); } catch (IOException ex) {}
            } while(! IntBoxSimple.tryParse(in, ibs));
            System.out.printf("The number you have entered was: %d%n", ibs.v());
        }
    }
    

    How to override Bootstrap's Panel heading background color?

    use this :

    .panel-heading {
        background-color: #ececb0 !important;
    }
    

    How to split a delimited string into an array in awk?

    Please be more specific! What do you mean by "it doesn't work"? Post the exact output (or error message), your OS and awk version:

    % awk -F\| '{
      for (i = 0; ++i <= NF;)
        print i, $i
      }' <<<'12|23|11'
    1 12
    2 23
    3 11
    

    Or, using split:

    % awk '{
      n = split($0, t, "|")
      for (i = 0; ++i <= n;)
        print i, t[i]
      }' <<<'12|23|11'
    1 12
    2 23
    3 11
    

    Edit: on Solaris you'll need to use the POSIX awk (/usr/xpg4/bin/awk) in order to process 4000 fields correctly.

    Java - Reading XML file

    One of the possible implementations:

    File file = new File("userdata.xml");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(file);
    String usr = document.getElementsByTagName("user").item(0).getTextContent();
    String pwd = document.getElementsByTagName("password").item(0).getTextContent();
    

    when used with the XML content:

    <credentials>
        <user>testusr</user>
        <password>testpwd</password>
    </credentials>
    

    results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

    Clear text from textarea with selenium

    Option a)

    If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence).

    Example 1:

     from selenium.webdriver.common.keys import Keys
     # ...
     webElement.sendKeys(Keys.CONTROL + "a");
     webElement.sendKeys(Keys.DELETE);
    

    Example 2:

     from selenium.webdriver.common.keys import Keys
     # ...
     webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop
    

    WebElement

    There are many ways to get the required WebElement, e.g.:

    • driver.find_element_by_id
    • driver.find_element_by_xpath
    • driver.find_element

    Option b)

     webElement.clear();
    

    If this element is a text entry element, this will clear the value.

    Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.

    How to get address of a pointer in c/c++?

    In C++ you can do:

    // Declaration and assign variable a
    int a = 7;
    // Declaration pointer b
    int* b;
    // Assign address of variable a to pointer b
    b = &a;
    
    // Declaration pointer c
    int** c;
    // Assign address of pointer b to pointer c
    c = &b;
    
    std::cout << "a: " << a << "\n";       // Print value of variable a
    std::cout << "&a: " << &a << "\n";     // Print address of variable a
    
    std::cout << "" << "" << "\n";
    
    std::cout << "b: " << b << "\n";       // Print address of variable a
    std::cout << "*b: " << *b << "\n";     // Print value of variable a
    std::cout << "&b: " << &b << "\n";     // Print address of pointer b
    
    std::cout << "" << "" << "\n";
    
    std::cout << "c: " << c << "\n";       // Print address of pointer b
    std::cout << "**c: " << **c << "\n";   // Print value of variable a
    std::cout << "*c: " << *c << "\n";     // Print address of variable a
    std::cout << "&c: " << &c << "\n";     // Print address of pointer c
    

    How to delete Project from Google Developers Console

    Simply go to https://console.developers.google.com/iam-admin/projects you must be signed in of course. There you will see the all your projects google console projects so just select the project you want to delete, and click delete project option which is shown at the top of the table. I have provided the screenshothere

    Encapsulation vs Abstraction?

    Encapsulation - the process of hiding components of the class to prevent direct access from the outside. It is achieved by using "private" modifier to prevent direct access to some class members (data field or method) from other classes or objects meanwhile providing access to these private members by public members (Interface). That make the class members protected as human organs hidden/encapsulated under the skin or some shield.

    Abstraction - A principle must be followed in writing OOP program that say "you must include in the class only components that are interesting in the task of the program". For example: the object student has a lot of characters as a human: name, age, weight, hair color, eye color, etc. But, when you create a class in OOP to work with students you should include only those characters that really matter for student database: name, age, specialty, level, marks ... etc. in C++ you can create abstract class by using the modifier "virtual" with any methods in the class and that will make it unusable in direct but you can derive other classes from it and create implementation for its members with adding required members based on the task.

    DB query builder toArray() laravel 4

    Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

    In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

    In this case, it might be more efficient to do:

    DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
    $result = DB::table('user')->where('name',=,'Jhon')->get();
    

    That way, you won't waste time creating objects and then converting them back into arrays.

    Uncaught SyntaxError: Unexpected token with JSON.parse

    Check this code. It gives you the clear solution of JSON parse error. It commonly happen by the newlines and the space between json key start and json key end

    data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")  
                   .replace(/\"[\n\s]{1,}/g, "\"")  
                   .replace(/[\n]/g, "\\n") 
    

    convert pfx format to p12

    .p12 and .pfx are both PKCS #12 files. Am I missing something?

    Have you tried renaming the exported .pfx file to have a .p12 extension?

    Base64 decode snippet in C++

    Here's my modification of the implementation that was originally written by René Nyffenegger. And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within std::string object ;)

    base64.h:

    #ifndef _BASE64_H_
    #define _BASE64_H_
    
    #include <vector>
    #include <string>
    typedef unsigned char BYTE;
    
    std::string base64_encode(BYTE const* buf, unsigned int bufLen);
    std::vector<BYTE> base64_decode(std::string const&);
    
    #endif
    

    base64.cpp:

    #include "base64.h"
    #include <iostream>
    
    static const std::string base64_chars =
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                 "abcdefghijklmnopqrstuvwxyz"
                 "0123456789+/";
    
    
    static inline bool is_base64(BYTE c) {
      return (isalnum(c) || (c == '+') || (c == '/'));
    }
    
    std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
      std::string ret;
      int i = 0;
      int j = 0;
      BYTE char_array_3[3];
      BYTE char_array_4[4];
    
      while (bufLen--) {
        char_array_3[i++] = *(buf++);
        if (i == 3) {
          char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
          char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
          char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
          char_array_4[3] = char_array_3[2] & 0x3f;
    
          for(i = 0; (i <4) ; i++)
            ret += base64_chars[char_array_4[i]];
          i = 0;
        }
      }
    
      if (i)
      {
        for(j = i; j < 3; j++)
          char_array_3[j] = '\0';
    
        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] = char_array_3[2] & 0x3f;
    
        for (j = 0; (j < i + 1); j++)
          ret += base64_chars[char_array_4[j]];
    
        while((i++ < 3))
          ret += '=';
      }
    
      return ret;
    }
    
    std::vector<BYTE> base64_decode(std::string const& encoded_string) {
      int in_len = encoded_string.size();
      int i = 0;
      int j = 0;
      int in_ = 0;
      BYTE char_array_4[4], char_array_3[3];
      std::vector<BYTE> ret;
    
      while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
        char_array_4[i++] = encoded_string[in_]; in_++;
        if (i ==4) {
          for (i = 0; i <4; i++)
            char_array_4[i] = base64_chars.find(char_array_4[i]);
    
          char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
          char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
          char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
    
          for (i = 0; (i < 3); i++)
              ret.push_back(char_array_3[i]);
          i = 0;
        }
      }
    
      if (i) {
        for (j = i; j <4; j++)
          char_array_4[j] = 0;
    
        for (j = 0; j <4; j++)
          char_array_4[j] = base64_chars.find(char_array_4[j]);
    
        char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
        char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
        char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
    
        for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);
      }
    
      return ret;
    }
    

    Here's the usage:

    std::vector<BYTE> myData;
    ...
    std::string encodedData = base64_encode(&myData[0], myData.size());
    std::vector<BYTE> decodedData = base64_decode(encodedData);
    

    Find current directory and file's directory

    Answer to #1:

    If you want the current directory, do this:

    import os
    os.getcwd()
    

    If you want just any folder name and you have the path to that folder, do this:

    def get_folder_name(folder):
        '''
        Returns the folder name, given a full folder path
        '''
        return folder.split(os.sep)[-1]
    

    Answer to #2:

    import os
    print os.path.abspath(__file__)
    

    How to create timer events using C++ 11?

    The asynchronous solution from Edward:

    • create new thread
    • sleep in that thread
    • do the task in that thread

    is simple and might just work for you.

    I would also like to give a more advanced version which has these advantages:

    • no thread startup overhead
    • only a single extra thread per process required to handle all timed tasks

    This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.

    Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.

    Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html

    #include <cstdio>
    #include <boost/asio.hpp>
    #include <boost/date_time/posix_time/posix_time.hpp>
    
    int main()
    {
      boost::asio::io_service io;
    
      boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
      t.async_wait([](const boost::system::error_code& /*e*/){
        printf("Printed after 1s\n"); });
    
      boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
      t2.async_wait([](const boost::system::error_code& /*e*/){
        printf("Printed after 1s\n"); });
    
      // both prints happen at the same time,
      // but only a single thread is used to handle both timed tasks
      // - namely the main thread calling io.run();
    
      io.run();
    
      return 0;
    }
    

    php timeout - set_time_limit(0); - don't work

    ini_set('max_execution_time', 300);
    

    use this

    How to display image from URL on Android

    I tried this code working for me,get image directly from url

          private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
          ImageView bmImage;
          public DownloadImageTask(ImageView bmImage) {
              this.bmImage = bmImage;
          }
    
          protected Bitmap doInBackground(String... urls) {
              String urldisplay = urls[0];
              Bitmap mIcon11 = null;
              try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
              } catch (Exception e) {
                  Log.e("Error", e.getMessage());
                  e.printStackTrace();
              }
              return mIcon11;
          }
    
          protected void onPostExecute(Bitmap result) {
              bmImage.setImageBitmap(result);
          }
        }
    

    use inside onCreate() method

    new DownloadImageTask((ImageView) findViewById(R.id.image)) .execute("http://scoopak.com/wp-content/uploads/2013/06/free-hd-natural-wallpapers-download-for-pc.jpg");

    Android Webview - Webpage should fit the device screen

    This seems like an XML problem. Open the XML document containing your Web-View. Delete the padding code at the top.

    Then in the layout , add

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    

    In the Web-View, add

    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    

    This makes the Web-View fit the device screen.

    SQL Stored Procedure: If variable is not null, update statement

    Use a T-SQL IF:

    IF @ABC IS NOT NULL AND @ABC != -1
        UPDATE [TABLE_NAME] SET XYZ=@ABC
    

    Take a look at the MSDN docs.

    How to update MySql timestamp column to current timestamp on PHP?

    Another option:

    UPDATE `table` SET the_col = current_timestamp
    

    Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

    How to make a transparent HTML button?

    <div class="button_style">
    This is your button value
    </div>
    
    .button_style{   
    background-color: Transparent;
    border: none;             /* Your can add different style/properties of button Here*/
    cursor:pointer;    
    }
    

    How to get number of entries in a Lua table?

    The easiest way that I know of to get the number of entries in a table is with '#'. #tableName gets the number of entries as long as they are numbered:

    tbl={
        [1]
        [2]
        [3]
        [4]
        [5]
    }
    print(#tbl)--prints the highest number in the table: 5
    

    Sadly, if they are not numbered, it won't work.

    Javascript Get Values from Multiple Select Option Box

    Also, change this:

        SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
    

    to

        SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
    

    The reason is that for the first time the variable SelBranchVal will be empty

    using if else with eval in aspx page

    If you are trying to bind is a Model class, you can add a new readonly property to it like:

    public string FormattedPercentage
    {
        get
        {
            If(this.Percentage < 50)
                return "0 %";
            else 
                return string.Format("{0} %", this.Percentage)        
         }
    }
    

    Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself

    What is an OS kernel ? How does it differ from an operating system?

    The kernel is part of the operating system, while not being the operating system itself. Rather than going into all of what a kernel does, I will defer to the wikipedia page: http://en.wikipedia.org/wiki/Kernel_%28computing%29. Great, thorough overview.

    How to collapse blocks of code in Eclipse?

    For windows eclipse using java: Windows -> Preferences -> Java -> Editor -> Folding

    Unfortunately this will not allow for collapsing code, however if it turns off you can re-enable it to get rid of long comments and imports.

    $.widget is not a function

    Place your widget.js after core.js, but before any other jquery that calls the widget.js file. (Example: draggable.js) Precedence (order) matters in what javascript/jquery can 'see'. Always position helper code before the code that uses the helper code.

    How to access cookies in AngularJS?

    Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.

    app.html:

    <html ng-app="app">
    <head>
        <meta charset="utf-8" />
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-controller="appController as vm">
    
        <input type="text" ng-model="vm.food" placeholder="Enter food" />
    
        <p>My favorite food is {{vm.food}}.</p>
    
        <p>Open new window, then press Back button.</p>
        <button ng-click="vm.openUrl()">Open</button>
    </body>
    </html>
    

    app.js:

    (function () {
        "use strict";
    
        angular.module('app', ['ngCookies'])
        .controller('appController', ['$cookies', '$window', function ($cookies, $window) {
            var vm = this;
    
            //get cookie
            vm.food = $cookies.get('myFavorite');
    
            vm.openUrl = function () {
                //save cookie
                $cookies.put('myFavorite', vm.food);
                $window.open("http://www.google.com", "_self");
            };
        }]);
    
    })();
    

    What is the correct syntax for 'else if'?

    def function(a):
        if a == '1':
            print ('1a')
        else if a == '2'
            print ('2a')
        else print ('3a')
    

    Should be corrected to:

    def function(a):
        if a == '1':
            print('1a')
        elif a == '2':
            print('2a')
        else:
            print('3a')
    

    As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.

    How to verify static void method has been called with power mockito

    Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
    

    Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

    mockStatic(Internalutils.class);
    

    So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

    @PrepareForTest({InternalService.InternalUtils.class})
    @RunWith(PowerMockRunner.class)
    public class InternalServiceTest {
    
        @Mock
        private InternalService.Order order;
    
        private InternalService internalService;
    
        @Before
        public void setup() {
            MockitoAnnotations.initMocks(this);
            internalService = new InternalService();
        }
    
        @Test
        public void processOrder() throws Exception {
    
            Mockito.when(order.isSuccessful()).thenReturn(true);
            PowerMockito.mockStatic(InternalService.InternalUtils.class);
    
            internalService.processOrder(order);
    
            PowerMockito.verifyStatic(times(1));
            InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
        }
    
    }
    

    These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

    PowerMockito.verifyStatic(times(1));
    InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    

    This is code of my class, sendEmail api twice.

    public class InternalService {
    
        public void processOrder(Order order) {
            if (order.isSuccessful()) {
                InternalUtils.sendEmail("", new String[1], "", "");
                InternalUtils.sendEmail("", new String[1], "", "");
            }
        }
    
        public static class InternalUtils{
    
            public static void sendEmail(String from, String[]  to, String msg, String body){
    
            }
    
        }
    
        public class Order{
    
            public boolean isSuccessful(){
                return true;
            }
    
        }
    
    }
    

    As it is calling twice you just need to change the verify(times(2))... that's all.

    JQuery get all elements by class name

    One possible way is to use .map() method:

    var all = $(".mbox").map(function() {
        return this.innerHTML;
    }).get();
    
    console.log(all.join());
    

    DEMO: http://jsfiddle.net/Y4bHh/

    N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

    "Line contains NULL byte" in CSV reader (Python)

    This will tell you what line is the problem.

    import csv
    
    lines = []
    with open('output.txt','r') as f:
        for line in f.readlines():
            lines.append(line[:-1])
    
    with open('corrected.csv','w') as correct:
        writer = csv.writer(correct, dialect = 'excel')
        with open('input.csv', 'r') as mycsv:
            reader = csv.reader(mycsv)
            try:
                for i, row in enumerate(reader):
                    if row[0] not in lines:
                       writer.writerow(row)
            except csv.Error:
                print('csv choked on line %s' % (i+1))
                raise
    

    Perhaps this from daniweb would be helpful:

    I'm getting this error when reading from a csv file: "Runtime Error! line contains NULL byte". Any idea about the root cause of this error?

    ...

    Ok, I got it and thought I'd post the solution. Simply yet caused me grief... Used file was saved in a .xls format instead of a .csv Didn't catch this because the file name itself had the .csv extension while the type was still .xls

    remove objects from array by object property

    Loop in reverse by decrementing i to avoid the problem:

    for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
        var obj = arrayOfObjects[i];
    
        if (listToDelete.indexOf(obj.id) !== -1) {
            arrayOfObjects.splice(i, 1);
        }
    }
    

    Or use filter:

    var newArray = arrayOfObjects.filter(function(obj) {
        return listToDelete.indexOf(obj.id) === -1;
    });
    

    C++ IDE for Macs

    Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

    Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

    With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...

    Take a look at it's quickStart guide to see how to create an archetype based on this Framework.

    Foundational frameworks in AppFuse:

    • Bootstrap and jQuery
    • Maven, Hibernate, Spring and Spring Security
    • Java 7, Annotations, JSP 2.1, Servlet 3.0
    • Web Frameworks: JSF, Struts 2, Spring MVC, Tapestry 5, Wicket
    • JPA Support

    For example to create an appFuse light archetype :

    mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes 
    -DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1 
    -DgroupId=com.mycompany -DartifactId=myproject
    

    "No such file or directory" but it exists

    Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

    In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.

    In my case, this happened due to working on Windows and uploading to Unix server for execution.

    pod install -bash: pod: command not found

    If you used homebrew to install ruby, this answer worked for me.

    brew unlink ruby && brew link ruby

    OSX 10.9.4

    Get ID from URL with jQuery

    My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .

    var baseUrl = (window.location).href; // You can also use document.URL
    var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
    alert(koopId)//503
    

    If you use

    var v = window.location.pathname;
    console.log(v)
    

    You will get only "/";

    Read Variable from Web.Config

    If you want the basics, you can access the keys via:

    string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
    string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();
    

    To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

    using System.Configuration;
    
    public static class AppSettingsGet
    {    
        public static string myKey
        {
            get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
        }
    
        public static string imageFolder
        {
            get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
        }
    
        // I also get my connection string from here
        public static string ConnectionString
        {
           get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
        }
    }
    

    Pip Install not installing into correct directory?

    1 - Something that might work

    The pip executable is actually a Python script.

    By default it contains (on Linux):

    #!/usr/bin/python
    # EASY-INSTALL-ENTRY-SCRIPT: 'pip==1.5.6','console_scripts','pip'
    __requires__ = 'pip==1.5.6'
    import sys
    from pkg_resources import load_entry_point
    
    if __name__ == '__main__':
        sys.exit(
            load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
        )
    

    So if you got the same in MacOS, pip would always use /usr/bin/python.

    But this is a default. You can still provide the version of python you want either by editing the file or by using python explicitly.

    If which python returns /usr/bin/python then something went wrong when you installed your own version. If it is /Library/Frameworks/Python.framework/Versions/2.7/bin/python, you can directly call:

    sudo python `which pip` install scikit-learn --upgrade
    

    However, chances are high that it won't work. The reason is that sudo is resetting all your environment variables. To make it work, the easiest would be to use:

    sudo -E pip install scikit-learn --upgrade
    

    or

    sudo -E python `which pip` install scikit-learn --upgrade
    

    depending on your setup.

    2 - What you should do

    pip was not thought of as something that root should execute. The actual best way to use it is to install a local, non-root, python version. You just have to make sure that you use it by default by setting up the correct environment variables (such as PATH on Linux) and then install pip without sudo using that python version.

    An even better way would be to setup virtualenvs from your root install.

    This way, you can install/update whatever you want without root privileges and never bother again about why sudo pip is not working. You would also avoid to provide root privileges to whatever is on Pypi and that would warrant that you don't mix system libs with your own.

    How to filter files when using scp to copy dir recursively?

    There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

    rsync -av --exclude '*.svn' user@server:/my/dir .
    

    (this line copy rsync from distant folder to current one)

    Recent versions of rsync tunnel over an ssh connection automatically by default.

    How does Trello access the user's clipboard?

    Daniel LeCheminant's code didn't work for me after converting it from CoffeeScript to JavaScript (js2coffee). It kept bombing out on the _.defer() line.

    I assumed this was something to do with jQuery deferreds, so I changed it to $.Deferred() and it's working now. I tested it in Internet Explorer 11, Firefox 35, and Chrome 39 with jQuery 2.1.1. The usage is the same as described in Daniel's post.

    var TrelloClipboard;
    
    TrelloClipboard = new ((function () {
        function _Class() {
            this.value = "";
            $(document).keydown((function (_this) {
                return function (e) {
                    var _ref, _ref1;
                    if (!_this.value || !(e.ctrlKey || e.metaKey)) {
                        return;
                    }
                    if ($(e.target).is("input:visible,textarea:visible")) {
                        return;
                    }
                    if (typeof window.getSelection === "function" ? (_ref = window.getSelection()) != null ? _ref.toString() : void 0 : void 0) {
                        return;
                    }
                    if ((_ref1 = document.selection) != null ? _ref1.createRange().text : void 0) {
                        return;
                    }
                    return $.Deferred(function () {
                        var $clipboardContainer;
                        $clipboardContainer = $("#clipboard-container");
                        $clipboardContainer.empty().show();
                        return $("<textarea id='clipboard'></textarea>").val(_this.value).appendTo($clipboardContainer).focus().select();
                    });
                };
            })(this));
    
            $(document).keyup(function (e) {
                if ($(e.target).is("#clipboard")) {
                    return $("#clipboard-container").empty().hide();
                }
            });
        }
    
        _Class.prototype.set = function (value) {
            this.value = value;
        };
    
        return _Class;
    
    })());
    

    Python Request Post with param data

    Assign the response to a value and test the attributes of it. These should tell you something useful.

    response = requests.post(url,params=data,headers=headers)
    response.status_code
    response.text
    
    • status_code should just reconfirm the code you were given before, of course

    How do I pass data between Activities in Android application?

    Create new Intent inside your current activity

    String myData="Your string/data here";
    Intent intent = new Intent(this, SecondActivity.class);    
    intent.putExtra("your_key",myData);
    startActivity(intent);
    

    Inside your SecondActivity.java onCreate() Retrieve those value using key your_key

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String myData = extras.getString("your_key");
        }  
    }
    

    pandas DataFrame: replace nan values with average of columns

    If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.

    sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))
    

    angular.element vs document.getElementById or jQuery selector with spin (busy) control

    Maybe I am too late here but this will work :

    var target = angular.element(appBusyIndicator);
    

    Notice, there is no appBusyIndicator, it is plain ID value.

    What is happening behind the scenes: (assuming it's applied on a div) (taken from angular.js line no : 2769 onwards...)

    /////////////////////////////////////////////
    function JQLite(element) {     //element = div#appBusyIndicator
      if (element instanceof JQLite) {
        return element;
      }
    
      var argIsString;
    
      if (isString(element)) {
        element = trim(element);
        argIsString = true;
      }
      if (!(this instanceof JQLite)) {
        if (argIsString && element.charAt(0) != '<') {
          throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
        }
        return new JQLite(element);
      }
    

    By default if there is no jQuery on the page, jqLite will be used. The argument is internally understood as an id and corresponding jQuery object is returned.

    How to download a Nuget package without nuget.exe or Visual Studio extension?

    To obtain the current stable version of the NuGet package use:

    https://www.nuget.org/api/v2/package/{packageID}
    

    How can I select and upload multiple files with HTML and PHP, using HTTP POST?

    There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

    <form enctype="multipart/form-data" action="post_upload.php" method="POST">
    

    Then the key to success;

    <input type="file" name="file[]" multiple />

    do NOT forget those brackets! In the post_upload.php try the following:

    <?php print_r($_FILES['file']['tmp_name']); ?>
    

    Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

    $_FILES['file']['tmp_name'][0]
    

    You can use php count() to count the number of files that was selected. Goodluck widdit!

    Web.Config Debug/Release

    The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

    In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
    

    This will cause each connection string line to find the matching name and update the attributes accordingly.

    Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

    Here's an example from one of my apps. Here's the web.config file section:

    <connectionStrings>
          <add name="EAF" connectionString="[Test Connection String]" />
    </connectionString>
    

    And here's the web.config.release section doing the proper transform:

    <connectionStrings>
          <add name="EAF" connectionString="[Prod Connection String]"
               xdt:Transform="SetAttributes"
               xdt:Locator="Match(name)" />
    </connectionStrings>
    

    One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

    For more details you can see the MSDN documentation

    https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

    Android check permission for LocationManager

    The last part of the error message you quoted states: ...with ("checkPermission") or explicitly handle a potential "SecurityException"

    A much quicker/simpler way of checking if you have permissions is to surround your code with try { ... } catch (SecurityException e) { [insert error handling code here] }. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.

    Jackson - How to process (deserialize) nested JSON?

    I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    class Scratch {
        private final String aString;
        private final String bString;
        private final String cString;
        private final static String jsonString;
    
        static {
            jsonString = "{\n" +
                    "  \"wrap\" : {\n" +
                    "    \"A\": \"foo\",\n" +
                    "    \"B\": \"bar\",\n" +
                    "    \"C\": \"baz\"\n" +
                    "  }\n" +
                    "}";
        }
    
        @JsonCreator
        Scratch(@JsonProperty("A") String aString,
                @JsonProperty("B") String bString,
                @JsonProperty("C") String cString) {
            this.aString = aString;
            this.bString = bString;
            this.cString = cString;
        }
    
        @Override
        public String toString() {
            return "Scratch{" +
                    "aString='" + aString + '\'' +
                    ", bString='" + bString + '\'' +
                    ", cString='" + cString + '\'' +
                    '}';
        }
    
        public static class JsonDeserializer {
            private final Scratch scratch;
    
            @JsonCreator
            public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
                this.scratch = scratch;
            }
    
            public Scratch getScratch() {
                return scratch;
            }
        }
    
        public static void main(String[] args) throws JsonProcessingException {
            ObjectMapper objectMapper = new ObjectMapper();
            Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
            System.out.println(scratch.toString());
        }
    }
    

    However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

    warning: implicit declaration of function

    You need to declare the desired function before your main function:

    #include <stdio.h>
    int yourfunc(void);
    
    int main(void) {
    
       yourfunc();
     }
    

    Iterate over object in Angular

    In addition to @obscur's answer, here is an example of how you can access both the key and value from the @View.

    Pipe:

    @Pipe({
       name: 'keyValueFilter'
    })
    
    export class keyValueFilterPipe {
        transform(value: any, args: any[] = null): any {
    
            return Object.keys(value).map(function(key) {
                let pair = {};
                let k = 'key';
                let v = 'value'
    
    
                pair[k] = key;
                pair[v] = value[key];
    
                return pair;
            });
        }
    
    }
    

    View:

    <li *ngFor="let u of myObject | 
    keyValueFilter">First Name: {{u.key}} <br> Last Name: {{u.value}}</li>
    

    So if the object were to look like:

    myObject = {
        Daario: Naharis,
        Victarion: Greyjoy,
        Quentyn: Ball
    }
    

    The generated outcome would be:

    First name: Daario
    Last Name: Naharis

    First name: Victarion
    Last Name: Greyjoy

    First name: Quentyn
    Last Name: Ball

    How to handle the click event in Listview in android?

        //get main activity
        final Activity main_activity=getActivity();
    
        //list view click listener
        final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String stringText;
    
                //in normal case
                stringText= ((TextView)view).getText().toString();                
    
                //in case if listview has separate item layout
                TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
                stringText=textview.getText().toString();                
    
                //show selected
                Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
            }
        });
    
        //populate listview
    

    How to detect tableView cell touched or clicked in swift

     # Check delegate? first must be connected owner of view controller
    
        # Simple implementation of the didSelectRowAt function.
    
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
             print("row selection: \(indexPath.row)")
        }
    

    Finding first and last index of some value in a list in Python

    If you are searching for the index of the last occurrence of myvalue in mylist:

    len(mylist) - mylist[::-1].index(myvalue) - 1
    

    How to update record using Entity Framework 6?

    I found a way that works just fine.

     var Update = context.UpdateTables.Find(id);
            Update.Title = title;
    
            // Mark as Changed
            context.Entry(Update).State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
    

    Save classifier to disk in scikit-learn

    In many cases, particularly with text classification it is not enough just to store the classifier but you'll need to store the vectorizer as well so that you can vectorize your input in future.

    import pickle
    with open('model.pkl', 'wb') as fout:
      pickle.dump((vectorizer, clf), fout)
    

    future use case:

    with open('model.pkl', 'rb') as fin:
      vectorizer, clf = pickle.load(fin)
    
    X_new = vectorizer.transform(new_samples)
    X_new_preds = clf.predict(X_new)
    

    Before dumping the vectorizer, one can delete the stop_words_ property of vectorizer by:

    vectorizer.stop_words_ = None
    

    to make dumping more efficient. Also if your classifier parameters is sparse (as in most text classification examples) you can convert the parameters from dense to sparse which will make a huge difference in terms of memory consumption, loading and dumping. Sparsify the model by:

    clf.sparsify()
    

    Which will automatically work for SGDClassifier but in case you know your model is sparse (lots of zeros in clf.coef_) then you can manually convert clf.coef_ into a csr scipy sparse matrix by:

    clf.coef_ = scipy.sparse.csr_matrix(clf.coef_)
    

    and then you can store it more efficiently.

    Relation between CommonJS, AMD and RequireJS?

    CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.

    AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

    AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.

    Where is the visual studio HTML Designer?

    Another way of setting the default to the HTML web forms editor is:

    1. At the top menu in Visual Studio go to File > New > File
    2. Select HTML Page
    3. In the lower right corner of the New File dialog on the Open button there is a down arrow
    4. Click it and you should see an option Open With
    5. Select HTML (Web Forms) Editor
    6. Click Set as Default
    7. Press OK

    Screenshot showing how to get to the "Open With" dialog box when creating a new file.

    Try-catch speeding up my code?

    I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

    Access denied for root user in MySQL command-line

    Gain access to a MariaDB 10 database server

    After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.

    sudo mysqld_safe --skip-grant-tables --skip-networking &
    

    Reset MariaDB root Password

    Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below

    sudo mysql -u root
    

    Then run the commands below to use the mysql database.

    use mysql;
    

    Finally, run the commands below to reset the root password.

    update user set password=PASSWORD("new_password_here") where User='root';
    

    Replace new_password _here with the new password you want to create for the root account, then press Enter.

    After that, run the commands below to update the permissions and save your changes to disk.

    flush privileges;
    

    Exit (CTRL + D) and you’re done.

    Next start MariaDB normally and test the new password you just created.

    sudo systemctl stop mariadb.service
    sudo systemctl start mariadb.service
    

    Logon to the database by running the commands below.

    sudo mysql -u root -p
    

    source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/

    Skip first entry in for loop in python?

    Here's my preferred choice. It doesn't require adding on much to the loop, and uses nothing but built in tools.

    Go from:

    for item in my_items:
      do_something(item)
    

    to:

    for i, item in enumerate(my_items):
      if i == 0:
        continue
      do_something(item)
    

    Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

    mysqli_select_db() should have 2 parameters, the connection link and the database name -

    mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
    

    Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

    How do I find out which keystore was used to sign an app?

    You can use Java 7's Key and Certificate Management Tool keytool to check the signature of a keystore or an APK without extracting any files.

    Signature of an APK or AAB

    # APK file
    keytool -printcert -jarfile app.apk
    
    # AAB file
    keytool -printcert -jarfile app.aab
    

    The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk or AAB file app.aab.

    (Note that the -jarfile argument was introduced in Java 7; see the documentation for more details.)

    Signature of a keystore

    keytool -list -v -keystore release.jks
    

    The output will reveal the aliases (entries) in the keystore file release.jks, with the certificate fingerprints (MD5, SHA1 and SHA256).

    If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.

    Can RDP clients launch remote applications and not desktops

    At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

    In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

    How to sort a Collection<T>?

    A Collection does not have an ordering, so wanting to sort it does not make sense. You can sort List instances and arrays, and the methods to do that are Collections.sort() and Arrays.sort()

    How to check if a date is greater than another in Java?

    You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

    Try to implement the code yourself.

    How to invoke bash, run commands inside the new shell, and then give control back to user?

    With accordance with the answer by daveraja, here is a bash script which will solve the purpose.

    Consider a situation if you are using C-shell and you want to execute a command without leaving the C-shell context/window as follows,

    Command to be executed: Search exact word 'Testing' in current directory recursively only in *.h, *.c files

    grep -nrs --color -w --include="*.{h,c}" Testing ./
    

    Solution 1: Enter into bash from C-shell and execute the command

    bash
    grep -nrs --color -w --include="*.{h,c}" Testing ./
    exit
    

    Solution 2: Write the intended command into a text file and execute it using bash

    echo 'grep -nrs --color -w --include="*.{h,c}" Testing ./' > tmp_file.txt
    bash tmp_file.txt
    

    Solution 3: Run command on the same line using bash

    bash -c 'grep -nrs --color -w --include="*.{h,c}" Testing ./'
    

    Solution 4: Create a sciprt (one-time) and use it for all future commands

    alias ebash './execute_command_on_bash.sh'
    ebash grep -nrs --color -w --include="*.{h,c}" Testing ./
    

    The script is as follows,

    #!/bin/bash
    # =========================================================================
    # References:
    # https://stackoverflow.com/a/13343457/5409274
    # https://stackoverflow.com/a/26733366/5409274
    # https://stackoverflow.com/a/2853811/5409274
    # https://stackoverflow.com/a/2853811/5409274
    # https://www.linuxquestions.org/questions/other-%2Anix-55/how-can-i-run-a-command-on-another-shell-without-changing-the-current-shell-794580/
    # https://www.tldp.org/LDP/abs/html/internalvariables.html
    # https://stackoverflow.com/a/4277753/5409274
    # =========================================================================
    
    # Enable following line to see the script commands
    # getting printing along with their execution. This will help for debugging.
    #set -o verbose
    
    E_BADARGS=85
    
    if [ ! -n "$1" ]
    then
      echo "Usage: `basename $0` grep -nrs --color -w --include=\"*.{h,c}\" Testing ."
      echo "Usage: `basename $0` find . -name \"*.txt\""
      exit $E_BADARGS
    fi  
    
    # Create a temporary file
    TMPFILE=$(mktemp)
    
    # Add stuff to the temporary file
    #echo "echo Hello World...." >> $TMPFILE
    
    #initialize the variable that will contain the whole argument string
    argList=""
    #iterate on each argument
    for arg in "$@"
    do
      #if an argument contains a white space, enclose it in double quotes and append to the list
      #otherwise simply append the argument to the list
      if echo $arg | grep -q " "; then
       argList="$argList \"$arg\""
      else
       argList="$argList $arg"
      fi
    done
    
    #remove a possible trailing space at the beginning of the list
    argList=$(echo $argList | sed 's/^ *//')
    
    # Echoing the command to be executed to tmp file
    echo "$argList" >> $TMPFILE
    
    # Note: This should be your last command
    # Important last command which deletes the tmp file
    last_command="rm -f $TMPFILE"
    echo "$last_command" >> $TMPFILE
    
    #echo "---------------------------------------------"
    #echo "TMPFILE is $TMPFILE as follows"
    #cat $TMPFILE
    #echo "---------------------------------------------"
    
    check_for_last_line=$(tail -n 1 $TMPFILE | grep -o "$last_command")
    #echo $check_for_last_line
    
    #if tail -n 1 $TMPFILE | grep -o "$last_command"
    if [ "$check_for_last_line" == "$last_command" ]
    then
      #echo "Okay..."
      bash $TMPFILE
      exit 0
    else
      echo "Something is wrong"
      echo "Last command in your tmp file should be removing itself"
      echo "Aborting the process"
      exit 1
    fi
    

    R solve:system is exactly singular

    Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

    How can I escape square brackets in a LIKE clause?

    LIKE 'WC[[]R]S123456' 
    

    or

    LIKE 'WC\[R]S123456' ESCAPE '\'
    

    Should work.

    Apache Tomcat Not Showing in Eclipse Server Runtime Environments

    You need to go to Help>Eclipse Marketplace . Then type server in the search box it will display Eclipse JST Server Adapters (Apache Tomcat,...) .Select that one and install it .Then go back to Window>Preferences>Server>Runtime Environnement, click add choose Apache tomcat version then add the installation directory .

    How to find files recursively by file type and copy them to a directory while in ssh?

    Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

    find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
    

    Just to sum up!

    Load RSA public key from file

    Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

       import java.io.DataInputStream;
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.security.KeyFactory;
        import java.security.NoSuchAlgorithmException;
        import java.security.interfaces.RSAPrivateKey;
        import java.security.interfaces.RSAPublicKey;
        import java.security.spec.InvalidKeySpecException;
        import java.security.spec.PKCS8EncodedKeySpec;
        import java.security.spec.X509EncodedKeySpec;
    
        public class Demo {
    
            public static final String PRIVATE_KEY="/home/user/private.der";
            public static final String PUBLIC_KEY="/home/user/public.der";
    
            public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
                //get the private key
                File file = new File(PRIVATE_KEY);
                FileInputStream fis = new FileInputStream(file);
                DataInputStream dis = new DataInputStream(fis);
    
                byte[] keyBytes = new byte[(int) file.length()];
                dis.readFully(keyBytes);
                dis.close();
    
                PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
                KeyFactory kf = KeyFactory.getInstance("RSA");
                RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
                System.out.println("Exponent :" + privKey.getPrivateExponent());
                System.out.println("Modulus" + privKey.getModulus());
    
                //get the public key
                File file1 = new File(PUBLIC_KEY);
                FileInputStream fis1 = new FileInputStream(file1);
                DataInputStream dis1 = new DataInputStream(fis1);
                byte[] keyBytes1 = new byte[(int) file1.length()];
                dis1.readFully(keyBytes1);
                dis1.close();
    
                X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
                KeyFactory kf1 = KeyFactory.getInstance("RSA");
                RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
    
                System.out.println("Exponent :" + pubKey.getPublicExponent());
                System.out.println("Modulus" + pubKey.getModulus());
            }
        }
    

    Parse string to date with moment.js

    I always seem to find myself landing here only to realize that the title and question are not quite aligned.

    If you want a moment date from a string:

    const myMomentObject = moment(str, 'YYYY-MM-DD')
    

    From moment documentation:

    Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.

    If you instead want a javascript Date object from a string:

    const myDate = moment(str, 'YYYY-MM-DD').toDate();
    

    background-image: url("images/plaid.jpg") no-repeat; wont show up

    Try this:

    body
    { 
        background:url("images/plaid.jpg") no-repeat fixed center;
    }
    

    jsfiddle example: http://jsfiddle.net/Q9Zfa/

    How to concatenate two MP4 files using FFmpeg?

    I found the pipe operator did not work for me when using option 3 to concat several MP4s on a Mac in the accepted answer.

    The following one-liner works on a Mac (High Sierra) to concatenate mp4s, with no intermediary file creation required.

    ffmpeg -f concat -safe 0 -i <(for f in ./*.mp4; do echo "file '$PWD/$f'"; done) -c copy output.mp4

    How to Replace dot (.) in a string in Java

    If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

    replace replaces each matching substring but does not interpret its argument as a regular expression.

    str = xpath.replace(".", "/*/");