Programs & Examples On #Mms

Multimedia Message Service(MMS) is an extension of the Short Message Service(SMS) protocol which allows for multimedia to be passed in messages. Microsoft Media Server(MMS) is Microsoft's proprietary network streaming protocol for Windows Media.

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

SmsListenerClass

public class SmsListener extends BroadcastReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {

    Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");

    // TODO Auto-generated method stub
    if (intent.getAction().equals(ACTION)) {

        Log.e("RECEIVED", ":-" + "SMS_ARRIVED");

        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            SmsMessage message = null;

            for (int i = 0; i < messages.length; i++) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }

                message = messages[i];
                buf.append("Received SMS from  ");
                buf.append(message.getDisplayOriginatingAddress());
                buf.append(" - ");
                buf.append(message.getDisplayMessageBody());
            }

            MainActivity inst = MainActivity.instance();
            inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());

        }

        Log.e("RECEIVED:", ":" + buf.toString());

        Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();

    }
}

Activity

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

public static MainActivity instance() {
    return inst;
}

public void updateList(final String msg_from, String msg_body) {

    tvMessage.setText(msg_from + " :- " + msg_body);

    sendSMSMessage(msg_from, msg_body);

}

protected void sendSMSMessage(String phoneNo, String message) {

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<receiver android:name=".SmsListener">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

font awesome icon in select option

You can't add i tag in option tag because tags are stripped.

But you can add it after the select like this

Best practices for Storyboard login screen, handling clearing of data upon logout

Here is what I ended up doing to accomplish everything. The only thing you need to consider in addition to this is (a) the login process and (b) where you are storing your app data (in this case, I used a singleton).

Storyboard showing login view controller and main tab controller

As you can see, the root view controller is my Main Tab Controller. I did this because after the user has logged in, I want the app to launch directly to the first tab. (This avoids any "flicker" where the login view shows temporarily.)

AppDelegate.m

In this file, I check whether the user is already logged in. If not, I push the login view controller. I also handle the logout process, where I clear data and show the login view.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Show login view if not logged in already
    if(![AppData isLoggedIn]) {
        [self showLoginScreen:NO];
    }

    return YES;
}

-(void) showLoginScreen:(BOOL)animated
{

    // Get login screen from storyboard and present it
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginViewController *viewController = (LoginViewController *)[storyboard instantiateViewControllerWithIdentifier:@"loginScreen"];
    [self.window makeKeyAndVisible];
    [self.window.rootViewController presentViewController:viewController
                                             animated:animated
                                           completion:nil];
}

-(void) logout
{
    // Remove data from singleton (where all my app data is stored)
    [AppData clearData];

   // Reset view controller (this will quickly clear all the views)
   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
   MainTabControllerViewController *viewController = (MainTabControllerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"mainView"];
   [self.window setRootViewController:viewController];

   // Show login screen
   [self showLoginScreen:NO];

}

LoginViewController.m

Here, if the login is successful, I simply dismiss the view and send a notification.

-(void) loginWasSuccessful
{

     // Send notification
     [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessful" object:self];

     // Dismiss login screen
     [self dismissViewControllerAnimated:YES completion:nil];

}

Notepad++ Setting for Disabling Auto-open Previous Files

My problem was that Notepad++ was crashing on a file I had previously opened; I was unable to open the application at all. This blog post discusses how to delete the data from the "Sessions" file so that Notepad++ will open without having any prior files open:

From the blog post:

Method 1 - edit session.xml

  1. Open file session.xml in C:\Users\Username\AppData\Roaming\Notepad++ or %APPDATA%\Notepad++
  2. Delete its contents and save it
  3. Run Notepad++ , session.xml will get new content automatically

Method 2 - add the -nosession parameter to Notepad++ shortcut

  1. Create a desktop shortcut referring to your Notepad++ program, e.g. C:\Program Files\Notepad++\notepad++.exe
  2. Right click on this shortcut
  3. In the "Target" field add the -nosession parameter so the target field looks exaxtly like (apostrophes included too): "C:\Program Files\Notepad++\notepad++.exe" -nosession
  4. Save and run Notepad++ from this shortcut icon with no recent files

Note: This is not a permanent setting, this simply deletes the prior session's information / opened files and starts over.

Alternatively, if you know the file which is causing notepad++ to hang, you can simply rename the file and open notepad++. This will solve the problem.

I hadn't seen this solution listed when I was googling my problem so I wanted to add it here!

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

How to trigger an event after using event.preventDefault()

Nope. Once the event has been canceled, it is canceled.

You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):

var lots_of_stuff_already_done = false;

$('.button').on('click', function(e) {
    if (lots_of_stuff_already_done) {
        lots_of_stuff_already_done = false; // reset flag
        return; // let the event bubble away
    }

    e.preventDefault();

    // do lots of stuff

    lots_of_stuff_already_done = true; // set flag
    $(this).trigger('click');
});

A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:

function onWithPrecondition(callback) {
    var isDone = false;

    return function(e) {
        if (isDone === true)
        {
            isDone = false;
            return;
        }

        e.preventDefault();

        callback.apply(this, arguments);

        isDone = true;
        $(this).trigger(e.type);
    }
}

Usage:

var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));

Bonus super-minimalistic jQuery plugin with Promise support:

(function( $ ) {
    $.fn.onButFirst = function(eventName,         /* the name of the event to bind to, e.g. 'click' */
                               workToBeDoneFirst, /* callback that must complete before the event is re-fired */
                               workDoneCallback   /* optional callback to execute before the event is left to bubble away */) {
        var isDone = false;

        this.on(eventName, function(e) {
            if (isDone === true) {
                isDone = false;
                workDoneCallback && workDoneCallback.apply(this, arguments);
                return;
            }

            e.preventDefault();

            // capture target to re-fire event at
            var $target = $(this);

            // set up callback for when workToBeDoneFirst has completed
            var successfullyCompleted = function() {
                isDone = true;
                $target.trigger(e.type);
            };

            // execute workToBeDoneFirst callback
            var workResult = workToBeDoneFirst.apply(this, arguments);

            // check if workToBeDoneFirst returned a promise
            if (workResult && $.isFunction(workResult.then))
            {
                workResult.then(successfullyCompleted);
            }
            else
            {
                successfullyCompleted();
            }
        });

        return this;
    };
}(jQuery));

Usage:

$('.button').onButFirst('click',
    function(){
        console.log('doing lots of work!');
    },
    function(){
        console.log('done lots of work!');
    });

How to implement DrawerArrowToggle from Android appcompat v7 21 library

To answer the updated part of your question: to style the drawer icon/arrow, you have two options:

Style the arrow itself

To do this, override drawerArrowStyle in your theme like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/holo_purple</item>
    <!-- ^ this will make the icon purple -->
</style>

This is probably not what you want, because the ActionBar itself should have consistent styling with the arrow, so, most probably, you want the option two:

Theme the ActionBar/Toolbar

Override the android:actionBarTheme (actionBarTheme for appcompat) attribute of the global application theme with your own theme (which you probably should derive from ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar) like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@android:color/white</item>
    <!-- ^ this will make text and arrow white -->
    <!-- you can also override drawerArrowStyle here -->
</style>

An important note here is that when using a custom layout with a Toolbar instead of stock ActionBar implementation (e.g. if you're using the DrawerLayout-NavigationView-Toolbar combo to achieve the Material-style drawer effect where it's visible under translucent statusbar), the actionBarTheme attribute is obviosly not picked up automatically (because it's meant to be taken care of by the AppCompatActivity for the default ActionBar), so for your custom Toolbar don't forget to apply your theme manually:

<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme">

-- this will resolve to either AppCompat's default ThemeOverlay.AppCompat.ActionBar or your override if you set the attribute in your derived theme.

PS a little comment about the drawerArrowStyle override and the spinBars attribute -- which a lot of sources suggest should be set to true to get the drawer/arrow animation. Thing is, spinBars it is true by default in AppCompat (check out the Base.Widget.AppCompat.DrawerArrowToggle.Common style), you don't have to override actionBarTheme at all to get the animation working. You get the animation even if you do override it and set the attribute to false, it's just a different, less twirly animation. The important thing here is to use ActionBarDrawerToggle, it's what pulls in the fancy animated drawable.

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

Java Security: Illegal key size or default parameters?

The JRE/JDK/Java 8 jurisdiction files can be found here:

Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8 Download

Like James said above:
Install the files in ${java.home}/jre/lib/security/.

How to remove all event handlers from an event

This is not an answer to the OP, but I thought I'd post this here in case it can help others.

  /// <summary>
  /// Method to remove a (single) SocketAsyncEventArgs.Completed event handler. This is 
  /// partially based on information found here: http://stackoverflow.com/a/91853/253938
  /// 
  /// But note that this may not be a good idea, being very .Net implementation-dependent. Note 
  /// in particular use of "m_Completed" instead of "Completed".
  /// </summary>
  private static void RemoveCompletedEventHandler(SocketAsyncEventArgs eventArgs)
  {
     FieldInfo fieldInfo = typeof(SocketAsyncEventArgs).GetField("m_Completed", 
                                                BindingFlags.Instance | BindingFlags.NonPublic);
     eventArgs.Completed -= (EventHandler<SocketAsyncEventArgs>)fieldInfo.GetValue(eventArgs);
  }

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Using custom std::set comparator

You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

struct lex_compare {
    bool operator() (const int64_t& lhs, const int64_t& rhs) const {
        stringstream s1, s2;
        s1 << lhs;
        s2 << rhs;
        return s1.str() < s2.str();
    }
};

You then use the class name as the type parameter

set<int64_t, lex_compare> s;

If you want to avoid the functor boilerplate code you can also use a function pointer (assuming lex_compare is a function).

set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

How to simulate a real mouse click using java?

Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).

public static void click(int x, int y) throws AWTException{
    Robot bot = new Robot();
    bot.mouseMove(x, y);    
    bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}

May be you could share the name of the program that is rejecting your click?

pandas: filter rows of DataFrame with operator chaining

The answer from @lodagro is great. I would extend it by generalizing the mask function as:

def mask(df, f):
  return df[f(df)]

Then you can do stuff like:

df.mask(lambda x: x[0] < 0).mask(lambda x: x[1] > 0)

Checking images for similarity with OpenCV

If for matching identical images ( same size/orientation )

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Source

Java: Identifier expected

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then "run" the class from your IDE

Declare multiple module.exports in Node.js

Two types module import and export.

type 1 (module.js):

// module like a webpack config
const development = {
  // ...
};
const production = {
  // ...
};

// export multi
module.exports = [development, production];
// export single
// module.exports = development;

type 1 (main.js):

// import module like a webpack config
const { development, production } = require("./path/to/module");

type 2 (module.js):

// module function no param
const module1 = () => {
  // ...
};
// module function with param
const module2 = (param1, param2) => {
  // ...
};

// export module
module.exports = {
  module1,
  module2
}

type 2 (main.js):

// import module function
const { module1, module2 } = require("./path/to/module");

How to use import module?

const importModule = {
  ...development,
  // ...production,
  // ...module1,
  ...module2("param1", "param2"),
};

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Error

ORA-04031: unable to allocate 4064 bytes of shared memory ("shared pool","select increment$,minvalue,m...","sga heap(3,0)","kglsim heap")

Solution: by nepasoft nepal

  • 1.-

    ps -ef|grep oracle
    
  • 2.- Find the smon and kill the pid for it

  • 3.-

    SQL> startup mount
    ORACLE instance started.
    
    Total System Global Area 4831838208 bytes
    Fixed Size                  2027320 bytes
    Variable Size            4764729544 bytes
    Database Buffers           50331648 bytes
    Redo Buffers               14749696 bytes
    Database mounted.
    
  • 4.-

    SQL> alter system set shared_pool_size=100M scope=spfile;
    
    System altered.
    
  • 5.-

    SQL> shutdown immediate
    
    ORA-01109: database not open
    Database dismounted.
    ORACLE instance shut down.
    
  • 6.-

    SQL> startup
    ORACLE instance started.
    
    Total System Global Area 4831838208 bytes
    Fixed Size                  2027320 bytes
    Variable Size            4764729544 bytes
    Database Buffers           50331648 bytes
    Redo Buffers               14749696 bytes
    Database mounted.
    Database opened.
    
  • 7.-

    SQL> create pfile from spfile;
    
    File created.
    

SOLVED

Looping each row in datagridview

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

How to use JavaScript source maps (.map files)?

  • How can a developer use it?

I didn't find answer for this in the comments, here is how can be used:

  1. Don't link your js.map file in your index.html file (no need for that)
  2. Minifiacation tools (good ones) add a comment to your .min.js file:

    //# sourceMappingURL=yourFileName.min.js.map

which will connect your .map file.

When the min.js and js.map files are ready...

  1. Chrome: Open dev-tools, navigate to Sources tab, You will see sources folder, where un-minified applications files are kept.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Cast the result as TIME and the result will be in time format for duration of the interval.

select CAST(job_end - job_start) AS TIME(0)) from tableA

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

Bash script plugin for Eclipse?

The free EclipseColorer Editor can do syntax highlighting for bash scripts.

However, It does not use Eclipse's "Outline view", i.e it does not fill it with a list of function definitions. Sometimes syntax highlighting just stops in the middle of the script. Then reopening the script helps.

CSS3 Transition - Fade out effect

Since display is not one of the animatable CSS properties. One display:none fadeOut animation replacement with pure CSS3 animations, just set width:0 and height:0 at last frame, and use animation-fill-mode: forwards to keep width:0 and height:0 properties.

@-webkit-keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}  
@keyframes fadeOut {
    0% { opacity: 1;}
    99% { opacity: 0.01;width: 100%; height: 100%;}
    100% { opacity: 0;width: 0; height: 0;}
}

.display-none.on{
    display: block;
    -webkit-animation: fadeOut 1s;
    animation: fadeOut 1s;
    animation-fill-mode: forwards;
}

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

For my case, I deleted the mappedBy and joined tables like this:

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_group", joinColumns = {
        @JoinColumn(name = "user", referencedColumnName = "user_id")
}, inverseJoinColumns = {
        @JoinColumn(name = "group", referencedColumnName = "group_id")
})
private List<User> users;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<Group> groups;

Initialization of an ArrayList in one line

In Java 9 we can easily initialize an ArrayList in a single line:

List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

or

List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

This new approach of Java 9 has many advantages over the previous ones:

  1. Space Efficiency
  2. Immutability
  3. Thread Safe

See this post for more details -> What is the difference between List.of and Arrays.asList?

How can I export data to an Excel file

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.

For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.

Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.

http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html

How to export the Html Tables data into PDF using Jspdf

Try to put

doc.fromHTML($('#target').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

instead of

doc.fromHTML($('#target').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Format SQL in SQL Server Management Studio

Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.

It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE statements, OUTPUT clauses, and other finicky stuff.

The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.

In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).

Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!

Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)

How to set the value for Radio Buttons When edit?

This is easier to read for me:

<input type="radio" name="rWF" id="rWF" value=1  <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>

How to fix a locale setting warning from Perl

Adding the correct locale to ~/.bashrc, ~/.bash_profile, /etc/environment and the like will solve the problem, however it is not recommended, as it overrides the settings from /etc/default/locale, which is confusing at best and may lead to the locales not being applied consistently at worst.

Instead, one should edit /etc/default/locale directly, which may look something like this:

LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_CTYPE=en_US

The change will take effect the next time you log in. You can get the new locale in an existing shell by sourcing /etc/default/locale like this:

$ . /etc/default/locale

How to make a checkbox checked with jQuery?

$('#checkbox').prop('checked', true);

When you want it unchecked:

$('#checkbox').prop('checked', false);

Calling a function within a Class method?

You need to call newTest to make the functions declared inside that method “visible” (see Functions within functions). But that are then just normal functions and no methods.

How can I move a tag on a git branch to a different commit?

One other way:

Move tag in remote repo.(Replace HEAD with any other if needed.)

$ git push --force origin HEAD:refs/tags/v0.0.1.2

Fetch changes back.

$ git fetch --tags

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

How to set Linux environment variables with Ansible

This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.

- hosts: all
  roles:
     - php
     - nginx
  environment:
    MY_ENV_VARIABLE: whatever_value

Using mysql concat() in WHERE clause?

SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'

...is probably what you want.

Jenkins, specifying JAVA_HOME

Your JAVA_HOME variable must be set to /usr/lib/jvm/java-6-openjdk and it must be available for the user that starts Jenkins.

From Kyle Strand comment:

As of April 2015 (I think), Jenkins requires Java7. Also note that the java binary path (JAVA) must be set to the correct version if the system default is still Java 6. Finally, for anyone wondering where these variables are set, it's in a config file listed with the installation instructions on the Jenkins webpage (e.g. for Debian it's /etc/default/jenkins).

Creating a singleton in Python

Method 3 seems to be very neat, but if you want your program to run in both Python 2 and Python 3, it doesn't work. Even protecting the separate variants with tests for the Python version fails, because the Python 3 version gives a syntax error in Python 2.

Thanks to Mike Watkins: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/. If you want the program to work in both Python 2 and Python 3, you need to do something like:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

MC = Singleton('MC', (object), {})

class MyClass(MC):
    pass    # Code for the class implementation

I presume that 'object' in the assignment needs to be replaced with the 'BaseClass', but I haven't tried that (I have tried code as illustrated).

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

hello to everyone just wanted to share my experience with phpMailer , that was working locally (XAMPP) but wasn't working on my hosting provider.

I turned on phpMailer error reporting

 $mail->SMTPDebug=2

i got 'Connection refused Error'

I email my host provider for the issue , and he said that he would open the SMTP PORTS and he opened the ports 25,465,587 .

Then i got the following error response "SMTP ERROR: Password command failed:"...."Please log in via your web browser and then try again"...."SMTP Error: Could not authenticate."

So google checks if your are logged in to your account (i was when i ran the script locally through my browser) and then allows you to send mail through the phpMailer script.

To fix that 1:go to your google account -> security 2:Scroll to the Key Icon and choose "2 way verification" and follow the procedure 3:When done go back to the key icon from google account -> security and choose the second option "create app passwords" and follow the procedure to get the password.

Now go to your phpMailer object and change your google password with the password given from the above procedure

you are done .

The code

require_once('class.phpmailer.php');

$phpMailerObj= new PHPMailer();

                $phpMailerObj->isSMTP();                    
                $phpMailerObj->SMTPDebug = 0;
                $phpMailerObj->Debugoutput = 'html';                    
                $phpMailerObj->Host = 'smtp.gmail.com';                     
                $phpMailerObj->Port = 587;
                $phpMailerObj->SMTPSecure = 'tls';
                $phpMailerObj->SMTPAuth = true;                 
                $phpMailerObj->Username = "YOUR EMAIL";                 
                $phpMailerObj->Password = "THE NEW PASSWORD FROM GOOGLE ";
                $phpMailerObj->setFrom('YOUR EMAIL ADDRESS', 'THE NAME OF THE SENDER',0);
                $phpMailerObj->addAddress('RECEIVER EMAIL ADDRESS', 'RECEIVER NAME');

                $phpMailerObj->Subject = 'SUBJECT';
                $phpMailerObj->Body ='MESSAGE';

                if (!phpMailerObj->send()) {
                    echo "phpMailerObjer Error: " . $phpMailerObj->ErrorInfo;
                    return 0;
                } else {
                    echo "Message sent!";
                    return 1;
                } 

When should I use double or single quotes in JavaScript?

The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!

Writing a list to a file with Python

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Count length of array and return 1 if it only contains one element

declare you array as:

$car = array("bmw")

EDIT

now with powershell syntax:)

$car = [array]"bmw"

.autocomplete is not a function Error

Note that if you're not using the full jquery UI library, this can be triggered if you're missing Widget, Menu, Position, or Core. There might be different dependencies depending on your version of jQuery UI

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

pandas three-way joining multiple dataframes on columns

This can also be done as follows for a list of dataframes df_list:

df = df_list[0]
for df_ in df_list[1:]:
    df = df.merge(df_, on='join_col_name')

or if the dataframes are in a generator object (e.g. to reduce memory consumption):

df = next(df_list)
for df_ in df_list:
    df = df.merge(df_, on='join_col_name')

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

In IDEA 13 this seems to no longer be an issue, you just have to have the Lombok plugin installed.

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

angularjs ng-style: background-image isn't working

For those who are struggling to get this working with IE11

HTML

<div ng-style="getBackgroundStyle(imagepath)"></div>

JS

$scope.getBackgroundStyle = function(imagepath){
    return {
        'background-image':'url(' + imagepath + ')'
    }
}

Changing color of Twitter bootstrap Nav-Pills

I use this snipped to change the active class for all pills in the same ul (applied at document ready):

$('ul.nav.nav-pills li a').click(function() {           
    $(this).parent().addClass('active').siblings().removeClass('active');           
});

Difference between F5, Ctrl + F5 and click on refresh button?

F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.

So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

String length in bytes in JavaScript

There is no way to do it in JavaScript natively. (See Riccardo Galli's answer for a modern approach.)


For historical reference or where TextEncoder APIs are still unavailable.

If you know the character encoding, you can calculate it yourself though.

encodeURIComponent assumes UTF-8 as the character encoding, so if you need that encoding, you can do,

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

This should work because of the way UTF-8 encodes multi-byte sequences. The first encoded byte always starts with either a high bit of zero for a single byte sequence, or a byte whose first hex digit is C, D, E, or F. The second and subsequent bytes are the ones whose first two bits are 10. Those are the extra bytes you want to count in UTF-8.

The table in wikipedia makes it clearer

Bits        Last code point Byte 1          Byte 2          Byte 3
  7         U+007F          0xxxxxxx
 11         U+07FF          110xxxxx        10xxxxxx
 16         U+FFFF          1110xxxx        10xxxxxx        10xxxxxx
...

If instead you need to understand the page encoding, you can use this trick:

function lengthInPageEncoding(s) {
  var a = document.createElement('A');
  a.href = '#' + s;
  var sEncoded = a.href;
  sEncoded = sEncoded.substring(sEncoded.indexOf('#') + 1);
  var m = sEncoded.match(/%[0-9a-f]{2}/g);
  return sEncoded.length - (m ? m.length * 2 : 0);
}

Node.js check if file exists

There are a lot of inaccurate comments about fs.existsSync() being deprecated; it is not.

https://nodejs.org/api/fs.html#fs_fs_existssync_path

Note that fs.exists() is deprecated, but fs.existsSync() is not.

Can I automatically increment the file build version when using Visual Studio?

Another option for changing version numbers in each build is to use the Version task of MSBuild.Community.Tasks. Just download their installer, install it, then adapt the following code and paste it after <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> in your .csproj file:

<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="BeforeBuild">
    <Version VersionFile="Properties\version.txt" Major="1" Minor="0" BuildType="Automatic" StartDate="12/31/2009" RevisionType="BuildIncrement">
      <Output TaskParameter="Major" PropertyName="Major" />
      <Output TaskParameter="Minor" PropertyName="Minor" />
      <Output TaskParameter="Build" PropertyName="Build" />
      <Output TaskParameter="Revision" PropertyName="Revision" />
    </Version>
    <AssemblyInfo CodeLanguage="CS"
                  OutputFile="Properties\VersionInfo.cs"
                  AssemblyVersion="$(Major).$(Minor)"
                  AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" />
</Target>

Note: Adapt the StartDate property to your locale. It currently does not use the invariant culture.

For the third build on January 14th, 2010, this creates a VersionInfo.cs with this content:

[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.14.2")]

This file then has to be added to the project (via Add existing item), and the AssemblyVersion and AssemblyFileVersion lines have to be removed from AssemblyInfo.cs.

The different algorithms for changing the version components are described in $(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.chm and Version Properties.

HTML5 and frameborder

As per the other posting here, the best solution is to use the CSS entry of

style="border:0;"

How to use setArguments() and getArguments() methods in Fragments?

Just call getArguments() in your Frag2's onCreateView() method:

public class Frag2 extends Fragment {

     public View onCreateView(LayoutInflater inflater,
         ViewGroup containerObject,
         Bundle savedInstanceState){
         //here is your arguments
         Bundle bundle=getArguments(); 

        //here is your list array 
        String[] myStrings=bundle.getStringArray("elist");   
     }
}

Releasing memory in Python

Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList(). This can be called indirectly by doing a full gc.collect.

Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.

import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

Output:

Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%

Edit:

I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.

The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free.

In 3.x range doesn't create a list, so the test above won't create 10 million int objects. Even if it did, the int type in 3.x is basically a 2.x long, which doesn't implement a freelist.

How to present UIActionSheet iOS Swift?

SWIFT 4

WORKS ON IPHONE AND IPAD BOTH. ALSO ALLOWS ROTATION

LANDSCAPE LANDSCAPE

PORTRAIT

PORTRAIT

Code (tested)

let alert = UIAlertController()

        let width: Int = Int(UIScreen.main.bounds.width - 100)

        let viewAction    =     UIAlertAction(title: "View", style: .default , handler:{ (UIAlertAction)in
                                    let storyboard      =   UIStoryboard(name: "Main", bundle: nil)
                                    let orderDetailVC   =   storyboard.instantiateViewController(withIdentifier: "orderDetail") as! OrderDetailTableViewController

                                    orderDetailVC.orderId     =   self.myDraftOrders[indexPath.row]["id"].intValue

                                    self.navigationController?.pushViewController(orderDetailVC, animated: true)
                                })

        viewAction.setValue(appGreenColor, forKey: "titleTextColor")

        alert.addAction(viewAction)

        let modifyAction    =   UIAlertAction(title: "Modify", style: .default, handler:{ (UIAlertAction)in
                                    showAlert("Coming soon...")
                                })

        modifyAction.setValue(appCyanColor, forKey: "titleTextColor")

        alert.addAction(modifyAction)

        let copyAction      =   UIAlertAction(title: "Copy", style: .default, handler:{ (UIAlertAction)in

                                    self.copyOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue)

                                })

        copyAction.setValue(appBlueColor, forKey: "titleTextColor")

        alert.addAction(copyAction)

        alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in

            self.deleteOrder(orderId: self.myDraftOrders[indexPath.row]["id"].intValue, indexPath: indexPath)

        }))

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
            print("User click Dismiss button")

        }))

        let popover = alert.popoverPresentationController

        popover?.delegate = self

        let cellT = tableView.cellForRow(at: indexPath)

        popover?.sourceView =   cellT
        popover?.sourceRect =   CGRect(x: width, y: 25, width: 100, height: 50)
        present(alert, animated: true)

How can I add or update a query string parameter?

Here's my approach: The location.params() function (shown below) can be used as a getter or setter. Examples:

Given the URL is http://example.com/?foo=bar&baz#some-hash,

  1. location.params() will return an object with all the query parameters: {foo: 'bar', baz: true}.
  2. location.params('foo') will return 'bar'.
  3. location.params({foo: undefined, hello: 'world', test: true}) will change the URL to http://example.com/?baz&hello=world&test#some-hash.

Here is the params() function, which can optionally be assigned to the window.location object.

location.params = function(params) {
  var obj = {}, i, parts, len, key, value;

  if (typeof params === 'string') {
    value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
    return value ? value[1] : undefined;
  }

  var _params = location.search.substr(1).split('&');

  for (i = 0, len = _params.length; i < len; i++) {
    parts = _params[i].split('=');
    if (! parts[0]) {continue;}
    obj[parts[0]] = parts[1] || true;
  }

  if (typeof params !== 'object') {return obj;}

  for (key in params) {
    value = params[key];
    if (typeof value === 'undefined') {
      delete obj[key];
    } else {
      obj[key] = value;
    }
  }

  parts = [];
  for (key in obj) {
    parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
  }

  location.search = parts.join('&');
};

how to convert 2d list to 2d numpy array?

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

How can I make a float top with CSS?

Here is a solution which works (almost perfect) in FF, Opera, Chrome:

    <style>
        html {
            height:100%;
        }

        p {
            page-break-inside: avoid;
            text-align: center;
            width: 128px;display:inline-block; 
            padding: 2px;
            margin: 2px;
            border: 1px solid red; 
            border-radius: 8px;
        }

        a {
            display: block;
            text-decoration: none;
        }

        b {
            display: block;
            color: red;
        }

        body {
            margin: 0px;
            padding: 1%;
            height: 97%; /* less than 98 b/c scroolbar */
            -webkit-column-width: 138px;
            -moz-column-width: 138px;
            column-width: 138px;
       }
    </style>

    <body>
        <p>
            <b>title 1</b>
            <a>link 1</a>
            <a>link 2</a>
            <a>link 3</a>
            <a>link 4</a>
        </p>

        <p>
            <b>title 2</b>
            <a>link 1</a>
            <a>link 2</a>
            <a>link 3</a>
            <a>link 4</a>
            <a>link 5</a>
        </p>
    </body>

The trick is page-break-inside: avoid; on p and column-width on body. It comes with dynamic column count. Text in a may be multi-line and blocks may have different heights.

Maybe someone has something for Edge and IE

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

In Html5, you can now use

<form>
<input type="number" min="1" max="100">
</form>

How to close form

You need the actual instance of the WindowSettings that's open, not a new one.

Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.

Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

Something like this:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel();
    dialogSettingsCancel.OwningWindowSettings = this;
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

public WindowSettings OwningWindowSettings { get; set; }

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    if(OwningWindowSettings != null)
        OwningWindowSettings.Close();
}

This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

If the two are always connected, you should instead use a constructor parameter:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel(this);
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

WindowSettings _owningWindowSettings;

public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
    if(owningWindowSettings == null)
        throw new ArgumentNullException("owningWindowSettings");

    _owningWindowSettings = owningWindowSettings;
}

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    _owningWindowSettings.Close();
}

Can I Set "android:layout_below" at Runtime Programmatically?

Kotlin version with infix function

infix fun View.below(view: View) {
      (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

Then you can write:

view1 below view2

Or you can call it as a normal function:

view1.below(view2)

File input 'accept' attribute - is it useful?

If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000"> tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE (2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.

How to open google chrome from terminal?

On Linux, just use this command in a terminal:

google-chrome

How to parse a CSV file in Bash?

If you want to read CSV file with some lines, so this the solution.

while IFS=, read -ra line
do 
    test $i -eq 1 && ((i=i+1)) && continue
    for col_val in ${line[@]}
    do
        echo -n "$col_val|"                 
    done
    echo        
done < "$csvFile"

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

HTML/Javascript change div content

Get the id of the div whose content you want to change then assign the text as below:

  var myDiv = document.getElementById("divId");
  myDiv.innerHTML = "Content To Show";

Overflow:hidden dots at the end

Most of solutions use static width here. But it can be sometimes wrong for some reasons.

Example: I had table with many columns. Most of them are narrow (static width). But the main column should be as wide as possible (depends on screen size).

HTML:

<table style="width: 100%">
  <tr>
    <td style="width: 60px;">narrow</td>
    <td>
      <span class="cutwrap" data-cutwrap="dynamic column can have really long text which can be wrapped on two rows, but we just need not wrapped texts using as much space as possible">
        dynamic column can have really long text which can be wrapped on two rows
        but we just need not wrapped texts using as much space as possible
      </span>
    </td>
  </tr>
</table>

CSS:

.cutwrap {
  position: relative;
  overflow: hidden;
  display: block;
  width: 100%;
  height: 18px;
  white-space: normal;
  color: transparent !important;
}
.cutwrap::selection {
  color: transparent !important;
}
.cutwrap:before {
  content: attr(data-cutwrap);
  position: absolute;
  left: 0;
  right: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}
/* different styles for links */
a.cutwrap:before {
  text-decoration: underline;
  color: #05c;
}

Warning: Failed propType: Invalid prop `component` supplied to `Route`

Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.

module.exports = Component should become export default Component.

CommonJS uses module.exports as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports, exoprts or exprots). There are no runtime or compile-time checks to tell you that you've messed up.

If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component then it will give you a compile error to let you know.

In your case, you can simplify the Speaker component.

import React from 'react';

export default React.createClass({
  render() {
    return (
      <h1>Speaker</h1>
    )
  }
});

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

I think your issue may be in the url pattern. Changing

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

and

<form action="/Register" method="post">

may fix your problem

Can I access constants in settings.py from templates in Django?

If someone finds this question like I did, then I'll post my solution which works on Django 2.0:

This tag assigns some settings.py variable value to template's variable:

Usage: {% get_settings_value template_var "SETTINGS_VAR" %}

app/templatetags/my_custom_tags.py:

from django import template
from django.conf import settings

register = template.Library()

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = getattr(settings, self.value.resolve(context, True), "")
        return ''

@register.tag('get_settings_value')
def do_assign(parser, token):
    bits = token.split_contents()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

Your template:

{% load my_custom_tags %}

# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}

# Output settings_debug variable:
{{ settings_debug }}

# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}

See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

ValueError : I/O operation on closed file

Same error can raise by mixing: tabs + spaces.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail

How to convert CSV to JSON in Node.js

You can try to use underscore.js

First convert the lines in arrays using the toArray function :

var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);

Then object the arrays together using the object function :

var json = _.object(letters, numbers);

By then, the json var should contain something like :

{"a": 1,"b": 2,"c": 3,"d": 4}

Keep background image fixed during scroll using css

Just add background-attachment to your code

body {
    background-position: center;
    background-image: url(../images/images5.jpg);
    background-attachment: fixed;
}

Is there a way to programmatically minimize a window

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.Hide()

End Sub

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

It seems you have changed some permissions of the directory. I did the following steps to restore it.

$  git diff > backup-diff.txt                ### in case you have some other code changes 

$  git checkout .

A fast way to delete all rows of a datatable at once

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}

How can I install Python's pip3 on my Mac?

I also encountered the same problem but brew install python3 does not work properly to install pip3.

brre will throw the warning The post-install step did not complete successfully.

It has to do with homebrew does not have permission to /usr/local

Create the directory if not exist

sudo mkdir lib 
sudo mkdir Frameworks

Give the permissions inside /usr/local to homebrew so it can access them:

sudo chown -R $(whoami) $(brew --prefix)/*

Now ostinstall python3

brew postinstall python3

This will give you a successful installation

How do I wrap text in a pre tag?

I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.

 <div style="white-space: pre-wrap;">content</div>

External resource not being loaded by AngularJs

Another simple solution is to create a filter:

app.filter('trusted', ['$sce', function ($sce) {
    return function(url) {
        return $sce.trustAsResourceUrl(url);
    };
}]);

Then specify the filter in ng-src:

<video controls poster="img/poster.png">
       <source ng-src="{{object.src | trusted}}" type="video/mp4"/>
</video>

jquery: how to get the value of id attribute?

You can also try this way

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>

jquery

$('.select_continent').click(function () {
alert($(this).data('value'));
});

Good luck !!!!

Line Break in HTML Select Option?

You can use a library called select2

You also can look at this Stackoverflow Question & Answer

<select id="selectBox" style="width: 500px">
  <option value="1" data-desc="this is my <br> multiple line 1">option 1</option>
  <option value="2" data-desc="this is my <br> multiple line 2">option 2</option>
</select>

In javascript

$(function(){
  $("#selectBox").select2({
    templateResult: formatDesc
  });

  function formatDesc (opt) {
   var optdesc = $(opt.element).attr('data-desc'); 
    var $opt = $(
      '<div><strong>' + opt.text + '</strong></div><div>' + optdesc + '</div>'
    );
    return $opt;
  };
});

How to get the current URL within a Django template?

Django 1.9 and above:

## template
{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

Old:

## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

## views.py
from django.template import *

def home(request):
    return render_to_response('home.html', {}, context_instance=RequestContext(request))

## template
{{ request.path }}

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

TypeError: 'int' object is not subscriptable

You can't do something like that: (int(sumall[0])+int(sumall[1]))

That's because sumall is an int and not a list or dict.

So, summ + sumd will be you're lucky number

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the

 xhr.getResponseHeader('Set-Cookie');

method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

Is it a bad practice to use an if-statement without curly braces?

Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

Looks much nicer like this:

someVar= someFlag ? 'someVal1' : 'someVal2';

But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!

Spark - Error "A master URL must be set in your configuration" when submitting an app

just add .setMaster("local") to your code as shown below:

val conf = new SparkConf().setAppName("Second").setMaster("local") 

It worked for me ! Happy coding !

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

How to send cookies in a post request with the Python Requests library?

If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:

import requests
...


def application(environ, start_response):
    cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
    response_headers = [('Content-type', 'text/plain')]
    response_headers.append(('Set-Cookie',cookie))
...

    return [bytes(post_env),response_headers]

I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

How to convert a datetime to string in T-SQL

There are many different ways to convert a datetime to a string. Here is one way:

SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm

See Demo

Here is a website that has a list of all of the conversions:

How to Format datetime & date in SQL Server

How do I pipe or redirect the output of curl -v?

The following worked for me:

Put your curl statement in a script named abc.sh

Now run:

sh abc.sh 1>stdout_output 2>stderr_output

You will get your curl's results in stdout_output and the progress info in stderr_output.

How to check if a variable is a dictionary in Python?

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(k_inner, v_inner)
            else:
                print(k_outer, v_outer)

parse_dict(dict)

Facebook API "This app is in development mode"

for testing purposes only you could Go to your facebook developer dashboard. create your app then in the top left corner open the apps dropdown menu and click create test app take the app ID and use instead.

image

Most efficient way to append arrays in C#?

I believe if you have 2 arrays of the same type that you want to combine into a third array, there's a very simple way to do that.

here's the code:

String[] theHTMLFiles = Directory.GetFiles(basePath, "*.html");
String[] thexmlFiles = Directory.GetFiles(basePath, "*.xml");
List<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));
String[] finalArray = finalList.ToArray();

Given two directory trees, how can I find out which files differ by content?

Diffoscope is a great command line based directory diff tool.

I especially like about it that it can diff into files:

It will recursively unpack archives of many kinds and transform various binary formats into more human readable form to compare them. It can compare two tarballs, ISO images, or PDF just as easily.

It will not only tell you which files differ, but also how they differ.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

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

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Playing HTML5 video on fullscreen in android webview

Thank you so much for that class, Cristian.

I made a minor tweak to it so that the custom loading view is optional, like so:

  @Override
    public View getVideoLoadingProgressView() // Video will start loading, only called in the case of VideoView (typically API level 10-)
    {
        if (loadingView == null)
        {
            return super.getVideoLoadingProgressView();
        }
        else
        {
            loadingView.setVisibility(View.VISIBLE);
            return loadingView;
        }
    }

I also added a new constructor that just takes two parameters. Anyway, just a minor simplification if you don't need the loading view. Thanks again for providing this.

Read HttpContent in WebApi controller

Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.

If you still want to have the model as a parameter in the method, you can create a DelegatingHandler to buffer the content.

internal sealed class BufferizingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        await request.Content.LoadIntoBufferAsync();
        var result = await base.SendAsync(request, cancellationToken);
        return result;
    }
}

And add it to the global message handlers:

configuration.MessageHandlers.Add(new BufferizingHandler());

This solution is based on the answer by Darrel Miller.

This way all the requests will be buffered.

How to find the Number of CPU Cores via .NET/C#?

Environment.ProcessorCount should give you the number of cores on the local machine.

What does the Excel range.Rows property really do?

There is another way, take this as example

Dim sr As String    
sr = "6:10"
Rows(sr).Select

All you need to do is to convert your variables iStartRow, iEndRow to a string.

How to round up a number in Javascript?

I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

Here is what I now use to have round up behave correctly:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

How to wait for async method to complete?

The most important thing to know about async and await is that await doesn't wait for the associated call to complete. What await does is to return the result of the operation immediately and synchronously if the operation has already completed or, if it hasn't, to schedule a continuation to execute the remainder of the async method and then to return control to the caller. When the asynchronous operation completes, the scheduled completion will then execute.

The answer to the specific question in your question's title is to block on an async method's return value (which should be of type Task or Task<T>) by calling an appropriate Wait method:

public static async Task<Foo> GetFooAsync()
{
    // Start asynchronous operation(s) and return associated task.
    ...
}

public static Foo CallGetFooAsyncAndWaitOnResult()
{
    var task = GetFooAsync();
    task.Wait(); // Blocks current thread until GetFooAsync task completes
                 // For pedagogical use only: in general, don't do this!
    var result = task.Result;
    return result;
}

In this code snippet, CallGetFooAsyncAndWaitOnResult is a synchronous wrapper around asynchronous method GetFooAsync. However, this pattern is to be avoided for the most part since it will block a whole thread pool thread for the duration of the asynchronous operation. This an inefficient use of the various asynchronous mechanisms exposed by APIs that go to great efforts to provide them.

The answer at "await" doesn't wait for the completion of call has several, more detailed, explanations of these keywords.

Meanwhile, @Stephen Cleary's guidance about async void holds. Other nice explanations for why can be found at http://www.tonicodes.net/blog/why-you-should-almost-never-write-void-asynchronous-methods/ and https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Remove a symlink to a directory

Assuming your setup is something like: ln -s /mnt/bar ~/foo, then you should be able to do a rm foo with no problem. If you can't, make sure you are the owner of the foo and have permission to write/execute the file. Removing foo will not touch bar, unless you do it recursively.

What happened to console.log in IE8?

This is my take on the various answers. I wanted to actually see the logged messages, even if I did not have the IE console open when they were fired, so I push them into a console.messages array that I create. I also added a function console.dump() to facilitate viewing the whole log. console.clear() will empty the message queue.

This solutions also "handles" the other Console methods (which I believe all originate from the Firebug Console API)

Finally, this solution is in the form of an IIFE, so it does not pollute the global scope. The fallback function argument is defined at the bottom of the code.

I just drop it in my master JS file which is included on every page, and forget about it.

(function (fallback) {    

    fallback = fallback || function () { };

    // function to trap most of the console functions from the FireBug Console API. 
    var trap = function () {
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var message = args.join(' ');
        console.messages.push(message);
        fallback(message);
    };

    // redefine console
    if (typeof console === 'undefined') {
        console = {
            messages: [],
            raw: [],
            dump: function() { return console.messages.join('\n'); },
            log: trap,
            debug: trap,
            info: trap,
            warn: trap,
            error: trap,
            assert: trap,
            clear: function() { 
                  console.messages.length = 0; 
                  console.raw.length = 0 ;
            },
            dir: trap,
            dirxml: trap,
            trace: trap,
            group: trap,
            groupCollapsed: trap,
            groupEnd: trap,
            time: trap,
            timeEnd: trap,
            timeStamp: trap,
            profile: trap,
            profileEnd: trap,
            count: trap,
            exception: trap,
            table: trap
        };
    }

})(null); // to define a fallback function, replace null with the name of the function (ex: alert)

Some extra info

The line var args = Array.prototype.slice.call(arguments); creates an Array from the arguments Object. This is required because arguments is not really an Array.

trap() is a default handler for any of the API functions. I pass the arguments to message so that you get a log of the arguments that were passed to any API call (not just console.log).

Edit

I added an extra array console.raw that captures the arguments exactly as passed to trap(). I realized that args.join(' ') was converting objects to the string "[object Object]" which may sometimes be undesirable. Thanks bfontaine for the suggestion.

Inject service in app.config

Well, I struggled a little with this one, but I actually did it.

I don't know if the answers are outdated because of some change in angular, but you can do it this way:

This is your service:

.factory('beerRetrievalService', function ($http, $q, $log) {
  return {
    getRandomBeer: function() {
      var deferred = $q.defer();
      var beer = {};

      $http.post('beer-detail', {})
      .then(function(response) {
        beer.beerDetail = response.data;
      },
      function(err) {
        $log.error('Error getting random beer', err);
        deferred.reject({});
      });

      return deferred.promise;
    }
  };
 });

And this is the config

.when('/beer-detail', {
  templateUrl : '/beer-detail',
  controller  : 'productDetailController',

  resolve: {
    beer: function(beerRetrievalService) {
      return beerRetrievalService.getRandomBeer();
    }
  }
})

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

Get url parameters from a string in .NET

Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString().

This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty= becomes a parameter with an empty value. The caller can verify the parameters if needed.

public static class UriHelper
{
    public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
    {
        if (uri == null)
            throw new ArgumentNullException("uri");

        if (uri.Query.Length == 0)
            return new Dictionary<string, string>();

        return uri.Query.TrimStart('?')
                        .Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                        .GroupBy(parts => parts[0],
                                 parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
                        .ToDictionary(grouping => grouping.Key,
                                      grouping => string.Join(",", grouping));
    }
}

Test

[TestClass]
public class UriHelperTest
{
    [TestMethod]
    public void DecodeQueryParameters()
    {
        DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
        DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
        DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
        DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
        DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
        DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
            new Dictionary<string, string>
            {
                { "q", "energy+edge" },
                { "rls", "com.microsoft:en-au" },
                { "ie", "UTF-8" },
                { "oe", "UTF-8" },
                { "startIndex", "" },
                { "startPage", "1%22" },
            });
        DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
    }

    private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
    {
        Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
        Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
        foreach (var key in expected.Keys)
        {
            Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
            Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
        }
    }
}

Reversing an Array in Java

If you don't want to use Collections then you can do this:

for (i = 0; i < array.length / 2; i++) {
  int temp = array[i];
  array[i] = array[array.length - 1 - i];
  array[array.length - 1 - i] = temp;
}

How to disable a particular checkstyle rule for a particular line of code?

What also works well is the SuppressWithNearbyCommentFilter which uses individual comments to suppress audit events.

For example

// CHECKSTYLE IGNORE check FOR NEXT 1 LINES
public void onClick(View view) { ... }

To configure a filter so that CHECKSTYLE IGNORE check FOR NEXT var LINES avoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):

<module name="SuppressWithNearbyCommentFilter">
    <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/>
    <property name="checkFormat" value="$1"/>
    <property name="influenceFormat" value="$2"/>
</module>

http://checkstyle.sourceforge.net/config.html

Generate a random letter in Python

def randchar(a, b):
    return chr(random.randint(ord(a), ord(b)))

Passing an array as a function parameter in JavaScript

Note this

function FollowMouse() {
    for(var i=0; i< arguments.length; i++) {
        arguments[i].style.top = event.clientY+"px";
        arguments[i].style.left = event.clientX+"px";
    }

};

//---------------------------

html page

<body onmousemove="FollowMouse(d1,d2,d3)">

<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>


</body>

can call function with any Args

<body onmousemove="FollowMouse(d1,d2)">

or

<body onmousemove="FollowMouse(d1)">

What's the algorithm to calculate aspect ratio?

I think this does what you are asking for:

webdeveloper.com - decimal to fraction

Width/height gets you a decimal, converted to a fraction with ":" in place of '/' gives you a "ratio".

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

Fastest Way to Find Distance Between Two Lat/Long Points

  • Create your points using Point values of Geometry data types in MyISAM table. As of Mysql 5.7.5, InnoDB tables now also support SPATIAL indices.

  • Create a SPATIAL index on these points

  • Use MBRContains() to find the values:

    SELECT  *
    FROM    table
    WHERE   MBRContains(LineFromText(CONCAT(
            '('
            , @lon + 10 / ( 111.1 / cos(RADIANS(@lon)))
            , ' '
            , @lat + 10 / 111.1
            , ','
            , @lon - 10 / ( 111.1 / cos(RADIANS(@lat)))
            , ' '
            , @lat - 10 / 111.1 
            , ')' )
            ,mypoint)
    

, or, in MySQL 5.1 and above:

    SELECT  *
    FROM    table
    WHERE   MBRContains
                    (
                    LineString
                            (
                            Point (
                                    @lon + 10 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat + 10 / 111.1
                                  ),
                            Point (
                                    @lon - 10 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat - 10 / 111.1
                                  ) 
                            ),
                    mypoint
                    )

This will select all points approximately within the box (@lat +/- 10 km, @lon +/- 10km).

This actually is not a box, but a spherical rectangle: latitude and longitude bound segment of the sphere. This may differ from a plain rectangle on the Franz Joseph Land, but quite close to it on most inhabited places.

  • Apply additional filtering to select everything inside the circle (not the square)

  • Possibly apply additional fine filtering to account for the big circle distance (for large distances)

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=8080
DB_DATABASE=flap_safety
DB_USERNAME=root
DB_PASSWORD=mysql

the above given is my .env

    'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', 'mysql'),
       // 'port' => env('DB_PORT', '8080'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', 'mysql'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

the above given is my database.php file. i just commented out port from database.php and it worked for me.

Redirect parent window from an iframe action

window.top.location.href = "http://example.com";

window.top refers to the window object of the page at the top of the frames hierarchy.

Spring Boot Rest Controller how to return different HTTP status codes?

Try this code:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

Git push error: Unable to unlink old (Permission denied)

After checking the permission of the folder, it is okay with 744. I had the problem with a plugin that is installed on my WordPress site. The plugin has hooked that are in the corn job I suspected.

With a simple sudo it can fix the issue

sudo git pull origin master

You have it working.

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

Write a file in external storage in Android

Supplemental Answer

After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.

MediaScannerConnection.scanFile(
        context,
        new String[]{myFile.getAbsolutePath()},
        null,
        null);

See the documentation and this answer for more.

How to unlock a file from someone else in Team Foundation Server

Here's what I do in Visual Studio 2012

(Note: I have the TFS Power Tools installed so if you don't see the described options you may need to install them. http://visualstudiogallery.msdn.microsoft.com/b1ef7eb2-e084-4cb8-9bc7-06c3bad9148f )

If you are accessing the Source Control Explorer as a team project administrator (or at least someone with the "Undo other users' changes" access right) you can do the following in Visual Studio 2012 to clear a lock and checkout.

  1. From the Source Control Explorer find the folder containing the locked file(s).
  2. Right-click and select Find then Find by Status...
  3. The "Find in Source Control" window appears
  4. Click the Find button
  5. A "Find in Source Control" tab should appear showing the file(s) that are checked out
  6. Right click the file you want to unlock
  7. Select Undo... from the context menu
  8. A confirmation dialog appears. Click the Yes button.
  9. The file should disappear from the "Find in Source Control" window.

The file is now unlocked.

What causes a TCP/IP reset (RST) flag to be sent?

Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.

presenting ViewController with NavigationViewController swift

SWIFT 3

let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

Find value in an array

I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

If you mean something else, check the Ruby Array API

Chrome:The website uses HSTS. Network errors...this page will probably work later

I see there are so many useful answers here but still, I come across a handy and useful article out there. https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/

I ran into the same issue and that article helped me to what exactly it is and how to deal with that HTH :-)

UITextField border color

If you use a TextField with rounded corners use this code:

    self.TextField.layer.cornerRadius=8.0f;
    self.TextField.layer.masksToBounds=YES;
    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;

To remove the border:

self.TextField.layer.masksToBounds=NO;
self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];

How to use enums as flags in C++?

Note if you are working in Windows environment, there is a DEFINE_ENUM_FLAG_OPERATORS macro defined in winnt.h that does the job for you. So in this case, you can do this:

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};
DEFINE_ENUM_FLAG_OPERATORS(AnimalFlags)

seahawk.flags = CanFly | EatsFish | Endangered;

Jquery resizing image

imgLiquid (a jQuery Plugin) seems to do what you ask.

Demo:
http://goo.gl/Wk8bU

JsFiddle example:
http://jsfiddle.net/karacas/3CRx7/#base

Javascript

$(function() {

    $(".imgLiquidFill").imgLiquid({
        fill: true,
        horizontalAlign: "center",
        verticalAlign: "top"
    });

    $(".imgLiquidNoFill").imgLiquid({
        fill: false,
        horizontalAlign: "center",
        verticalAlign: "50%"
    });
     });

Html

<div class="boxSep" >
    <div class="imgLiquidNoFill imgLiquid" style="width:250px; height:250px;">
        <img alt="" src="http://www.juegostoystory.net/files/image/2010_Toy_Story_3_USLC12_Woody.jpg"/>
    </div>
</div>

how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

Certificate is trusted by PC but not by Android

I had the same error because I didn't issued a Let's Encrypt cert for the www.my-domain.com, only for my-domain.com

Issuing also for the www. and configuring the vhost to load certificates for www.my-domain.com before redirecting to https://my-domain.com did the trick.

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

How do I check the difference, in seconds, between two dates?

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()

How to Set Opacity (Alpha) for View in Android

I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.

Gingerbread vs. ICS+:

Gingerbread ICS

Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:

Your XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              style="@style/Content">
  <RelativeLayout style="@style/ButtonHolder">
      <Button android:id="@+id/myButton"
              style="@style/Button"
              android:text="@string/proceed"/>
    </RelativeLayout>
</LinearLayout>

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
    </shape>
  </item>

</layer-list>

styles.xml

.
.
.      
  <style name="ButtonHolder">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:background">@drawable/buttonholder</item>
  </style>

  <style name="Button" parent="@android:style/Widget.Button">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textStyle">bold</item>
  </style>
.
.
.

However, this results in a white border because the Holo button images include margins to account for the pressed space:

Too much white Too much white pressed

So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item>
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>
    </shape>
  </item>

  <item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
      <corners android:radius="2dp" />
    </shape>
  </item>

</layer-list>

The final result looks like this:

No white No white pressed

You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).

how to move elasticsearch data from one server to another

There is also the _reindex option

From documentation:

Through the Elasticsearch reindex API, available in version 5.x and later, you can connect your new Elasticsearch Service deployment remotely to your old Elasticsearch cluster. This pulls the data from your old cluster and indexes it into your new one. Reindexing essentially rebuilds the index from scratch and it can be more resource intensive to run.

POST _reindex
{
  "source": {
    "remote": {
      "host": "https://REMOTE_ELASTICSEARCH_ENDPOINT:PORT",
      "username": "USER",
      "password": "PASSWORD"
    },
    "index": "INDEX_NAME",
    "query": {
      "match_all": {}
    }
  },
  "dest": {
    "index": "INDEX_NAME"
  }
}

Object of class stdClass could not be converted to string - laravel

This is easy all you need to do is something like this Grab your contents like this

  $result->get(filed1) = 'some modification';
  $result->get(filed2) = 'some modification2';

How to get $(this) selected option in jQuery?

Best guess:

var cur_value = $('#select-id').children('option:selected').text();

I like children better in this case because you know you're only going one branch down the DOM tree...

How to check for a JSON response using RSpec?

Simple and easy to way to do this.

# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success

spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true

How to force input to only allow Alpha Letters?

On newer browsers, you can use:

<input type="text" name="country_code" 
    pattern="[A-Za-z]" title="Three letter country code">

You can use regular expressions to restrict the input fields.

How to make a <div> always full screen?

Change the body element into a flex container and the div into a flex item:

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  height: 100vh;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;_x000D_
  background: tan;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

How to represent matrices in python

Python doesn't have matrices. You can use a list of lists or NumPy

HTTP Basic Authentication - what's the expected web browser experience?

WWW-Authenticate header

You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.

How do I extract the contents of an rpm?

7-Zip is able to extract the contents. It works the same way that a tar.gz file works. A compressed file inside a compressed file.

On Windows 7 Pro with 7-Zip installed:

Right click the rpm file. Mouse over 7-Zip in the context menu. Select extract to "filename".

Enter into the filename folder.

Right click the cpio file. Mouse over 7-Zip in the context menu. Select extract to "filename".

You are done. The folder with "filename" contains the extracted contents for inspecting.

I know you Linux guys despise things being made easy, but in the long run, if you have to spend time hunting down a solution to a simple problem like this; that inefficiency is costing you money.

Given the fact that you Linux guys despise efficient simplicity, I highly doubt that the Linux version of 7-Zip will do the same thing in the exact same way.

Why make it easy when you can make downright stupid hard and claim to be a genius at the same time?

Just to be clear; I'm not a Windows fanboy. I'm actually looking into moving over to Linux. I just couldn't resist the opportunity to rub what Windows developers would see as common sense, best developer practices into your faces.

Just be glad it's me posting this and you don't have Mark Harmon standing next to you cause; Special agent Leroy Jethro Gibbs would have done given you a head slap for not using your head.

I don't know which Gibbs rule it is but the rule is: Don't make things harder for yourself than they have to be.

Now we get to see who needs to take a vacation. Take care!

Replace a newline in TSQL

If your column data type is 'text' then you will get an error message as

Msg 8116, Level 16, State 1, Line 2 Argument data type text is invalid for argument 1 of replace function.

In this case you need to cast the text as nvarchar and then replace

SELECT REPLACE(REPLACE(cast(@str as nvarchar(max)), CHAR(13), ''), CHAR(10), '')

Does reading an entire file leave the file handle open?

The answer to that question depends somewhat on the particular Python implementation.

To understand what this is all about, pay particular attention to the actual file object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read() call returns.

This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".

in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.

A better solution, to make sure that the file is closed, is this pattern:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

which will always close the file immediately after the block ends; even if an exception occurs.

Edit: To put a finer point on it:

Other than file.__exit__(), which is "automatically" called in a with context manager setting, the only other way that file.close() is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__(). This leads us to the question of when does __del__() get called?

A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.

-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203

In particular:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

[...]

CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.

-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types

(Emphasis mine)

but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!

JQuery datepicker language

Maybe you don't have a language file:

Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n

A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:

http://api.jqueryui.com/datepicker/

String.contains in Java

Similarly:

"".contains("");     // Returns true.

Therefore, it appears that an empty string is contained in any String.

Renew Provisioning Profile

Update March 2013

The expiry date of the provisioning profile is linked to the expiry date of the developer certificate. And I didn't want to wait for it to expire so here is what I did -

  • Go to the iOS Provisioning portal
  • Revoke the current certificate
  • In Xcode > Organizer go to the Provisioning profiles page (under Library)
  • Press refresh and it will prompt you to create a new developer certificate since the current one has been revoked
  • Follow the steps to create one
  • Go back to the iOS provisioning portal for your distribution profiles and change something about it so it will enable the submit button.
  • Submit it and the date of the new certificate will get applied to it

How to use @Nullable and @Nonnull annotations more effectively?

I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link:

Java 8's new Type Annotations

In the above blog, it is recommended that:

Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.

getActionBar() returns null

You have to define window type as actionbar before activity render its view.

use

requestWindowFeature(Window.FEATURE_ACTION_BAR);

before calling setContentView() method.

Converting bytes to megabytes

Divide by 2 to the power of 20, (1024*1024) bytes = 1 megabyte

1024*1024 = 1,048,576   
2^20 = 1,048,576
1,048,576/1,048,576 = 1  

It is the same thing.

An error has occured. Please see log file - eclipse juno

Deleting metadata folder might not work in this case. Or eclipse -clean command. Or reinstall eclipse might not solve this.

Instead try deleting other java versions you might have in your machine.

Check what you have right now using this:

/usr/libexec/java_home -V

Delete other java versions which you don't want, following below command:

sudo rm -rf /System/Library/Java/JavaVirtualMachines/java-version.jdk

This should resolve your issue.

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

SQL Row_Number() function in Where Clause

WITH MyCte AS 
(
    select 
       employee_id,
       RowNum = row_number() OVER (order by employee_id)
    from V_EMPLOYEE 
)
SELECT  employee_id
FROM    MyCte
WHERE   RowNum > 0
ORDER BY employee_id

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

Try changing the Web Client request authentication part to:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

Then make your call, seems to work fine for me.

how to use Spring Boot profiles

Alternatively, the profile can be directly specified in the application.properties file by adding the line:

spring.profiles.active=prod

Profiles work in conjunction with Spring Boot properties files. By default, Spring Boot parses a file called application.properties – located in the src/main/resources directory – to identify configuration information.

Our first task will be to add a parameter in that file which will tell Spring to use a different environment-specific property file corresponding to the active profile (i.e. the profile that the app is currently being run with). We can do this by adding the following to the application.properties file:

spring.profiles.active=@activatedProperties@

Now we need to create the two new environment-specific property files (in the same path as the existing application.properties file), one to be used by the DEV profile and one to be used by the PROD profile. These files need to be named the following:

application-dev.properties

application-prod.properties

In each case, we specify prod as the active profile, which causes the application-prod.properties file to be chosen for configuration purposes.

How to make bootstrap 3 fluid layout without horizontal scrollbar

You can fix this problem without disturbing the bootstrap css and wait for a fix in the next version, so you can simply wrap your row by defining you own class .container-fluid with padding.

//Add this class to your global css file
<style>
   .container-fluid {
       padding: 0 15px;  
   }
</style>

   //Wrap your rows in within this .container-fluid 
   <div class="container-fluid">
      <div class="row">
          <div class="col-md-3">content</div>
          <div class="col-md-9">content</div>
          <div class="col-md-3">content</div>
      </div>
   </div> 

How do I read a specified line in a text file?

If your file contains lines with different lengths and you need to read lines often and you need to read it quickly you can make an index of the file by reading it once, saving position of each new line and then when you need to read a line, you just lookup the position of the line in your index, seek there and then you read the line.

If you add new lines to the file you can just add index of new lines and you don't need to reindex it all. Though if your file changes somewhere in a line you have already indexed then you have to reindex.

SQL, How to Concatenate results?

With MSSQL you can do something like this:

declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', ' 
from TableX where ModuleId = @ModuleId

Downloading and unzipping a .zip file without writing to disk

It wasn't obvious in Vishal's answer what the file name was supposed to be in cases where there is no file on disk. I've modified his answer to work without modification for most needs.

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen

def unzip_string(zipped_string):
    unzipped_string = ''
    zipfile = ZipFile(StringIO(zipped_string))
    for name in zipfile.namelist():
        unzipped_string += zipfile.open(name).read()
    return unzipped_string

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

How can I expand and collapse a <div> using javascript?

You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.

<script language="javascript"> 
function toggle(elementId) {
    var ele = document.getElementById(elementId);
    if(ele.style.display == "block") {
            ele.style.display = "none";
    }
    else {
        ele.style.display = "block";
    }
} 
</script>

You can pass the div ID and it will toggle between display 'none' or 'block'.

Original source on snip2code - How to collapse a div in html

Center an item with position: relative

You can use calc to position element relative to center. For example if you want to position element 200px right from the center .. you can do this :

#your_element{
    position:absolute;
    left: calc(50% + 200px);
}

Dont forget this

When you use signs + and - you must have one blank space between sign and number, but when you use signs * and / there is no need for blank space.

How to convert a PNG image to a SVG?

If you're on some Linux system, imagemagick is perfect. I.e

convert somefile.png somefile.svg

This works with heaps of different formats.

For other media such as videos and audio use (ffmpeg) I know you clearly stated png to svg, however; It's still media related.

ffmpeg -i somefile.mp3 somefile.ogg

Just a tip for if you wish to go through lots of files; a loop using basic shell tricks..

for f in *.jpg; do convert $f ${f%jpg}png; done

That removes the jpg and adds png which tells convert what you want.

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

ProgressDialog in AsyncTask

It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.

RegEx: How can I match all numbers greater than 49?

Next matches all greater or equal to 11100:

^([1-9][1-9][1-9]\d{2}\d*|[1-9][2-9]\d{3}\d*|[2-9]\d{4}\d*|\d{6}\d*)$

For greater or equal 50:

^([5-9]\d{1}\d*|\d{3}\d*)$

See pattern and modify to any number. Also it would be great to find some recursive forward/backward operators for large numbers.

change PATH permanently on Ubuntu

Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh (and possibly play.csh, etc):

PATH=$PATH:/home/me/play
export PATH

How can I get the session object if I have the entity-manager?

To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.

JPA 1.0

With JPA 1.0, you'd have to use EntityManager#getDelegate(). But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:

org.hibernate.Session session = (Session) manager.getDelegate();

But with GlassFish, you'd have to do:

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); 

I agree, that's horrible, and the spec is to blame here (not clear enough).

JPA 2.0

With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>) method that is to be preferred over EntityManager#getDelegate() for new applications.

So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:

Session session = entityManager.unwrap(Session.class);

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)