Programs & Examples On #Impersonation

Impersonation is a process whereby an application assumes another identity or security context during execution.

How do you do Impersonation in .NET?

"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently. I will describe them both, and then explain how to use my SimpleImpersonation library, which uses them internally.

Impersonation

The APIs for impersonation are provided in .NET via the System.Security.Principal namespace:

  • Newer code (.NET 4.6+, .NET Core, etc.) should generally use WindowsIdentity.RunImpersonated, which accepts a handle to the token of the user account, and then either an Action or Func<T> for the code to execute.

    WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    or

    var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • Older code used the WindowsIdentity.Impersonate method to retrieve a WindowsImpersonationContext object. This object implements IDisposable, so generally should be called from a using block.

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
    {
        // do whatever you want as this user.
    }
    

    While this API still exists in .NET Framework, it should generally be avoided, and is not available in .NET Core or .NET Standard.

Accessing the User Account

The API for using a username and password to gain access to a user account in Windows is LogonUser - which is a Win32 native API. There is not currently a built-in .NET API for calling it, so one must resort to P/Invoke.

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

This is the basic call definition, however there is a lot more to consider to actually using it in production:

  • Obtaining a handle with the "safe" access pattern.
  • Closing the native handles appropriately
  • Code access security (CAS) trust levels (in .NET Framework only)
  • Passing SecureString when you can collect one safely via user keystrokes.

The amount of code to write to illustrate all of this is beyond what should be in a StackOverflow answer, IMHO.

A Combined and Easier Approach

Instead of writing all of this yourself, consider using my SimpleImpersonation library, which combines impersonation and user access into a single API. It works well in both modern and older code bases, with the same simple API:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
}); 

or

var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
    return something;
});

Note that it is very similar to the WindowsIdentity.RunImpersonated API, but doesn't require you know anything about token handles.

This is the API as of version 3.0.0. See the project readme for more details. Also note that a previous version of the library used an API with the IDisposable pattern, similar to WindowsIdentity.Impersonate. The newer version is much safer, and both are still used internally.

Impersonate tag in Web.Config

You had the identity node as a child of authentication node. That was the issue. As in the example above, authentication and identity nodes must be children of the system.web node

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

javascript multiple OR conditions in IF statement

This is an example:

false && true || true   // returns true
false && (true || true) // returns false
(true || true || true)  // returns true
false || true           // returns true
true || false           // returns true

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.

    <div class="featured-image" style="height:300px">
     <img id="thumbnail" src="01.jpg"/>
    </div>

    <div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
    <img src='01.jpg'>
    <img src='02.jpg'>
    <img src='03.jpg'>
    <img src='04.jpg'>
    </div>

    <script type="text/javascript">
            function changeThumbnail()
            {
            $("#thumbnail").fadeOut(200);
            var path=$("#thumbnail").attr('src');
            var arr= new Array(); var i=0;
            $("#thumblist img").each(function(index, element) {
               arr[i]=$(this).attr('src');
               i++;
            });
            var index= arr.indexOf(path);
            if(index==(arr.length-1))
            path=arr[0];
            else
            path=arr[index+1];
            $("#thumbnail").attr('src',path).fadeIn(200);
            setTimeout(changeThumbnail, 5000);  
            }
            setTimeout(changeThumbnail, 5000);
    </script>

Getter and Setter declaration in .NET

With this, you can perform some code in the get or set scope.

private string _myProperty;
public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

You also can use automatic properties:

public string myProperty
{
    get;
    set;
}

And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.

You also can control the visibility of these scopes, for sample:

public string myProperty
{
    get;
    private set;
}

public string myProperty2
{
    get;
    protected set;
}

public string myProperty3
{
    get; 
}

Update

Now in C# you can initialize the value of a property. For sample:

public int Property { get; set; } = 1;

If also can define it and make it readonly, without a set.

public int Property { get; } = 1;

And finally, you can define an arrow function.

public int Property => GetValue();

Default string initialization: NULL or Empty?

For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:

if (s == "value")

I get a bad feeling. Why is there a string literal in this method? What's setting s? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare? Should I be creating an Enum and parsing into it?

From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.

Knowing this, I don't blink when I see something like this in our code base:

string msg = Validate(item);
if (msg != null)
{
   DisplayErrorMessage(msg);
   return;
}

I know that Validate would never return String.Empty, because we write better code than that.

Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty and when it should mean null.

(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)

pip install: Please check the permissions and owner of that directory

I also saw this change on my Mac when I went from running pip to sudo pip. Adding -H to sudo causes the message to go away for me. E.g.

sudo -H pip install foo

man sudo tells me that -H causes sudo to set $HOME to the target users (root in this case).

So it appears pip is looking into $HOME/Library/Log and sudo by default isn't setting $HOME to /root/. Not surprisingly ~/Library/Log is owned by you as a user rather than root.

I suspect this is some recent change in pip. I'll run it with sudo -H for now to work around.

Component is part of the declaration of 2 modules

Simple fix,

Go to your app.module.ts file and remove/comment everything that binds with add_event. There is no need of adding components to the App.module.ts which are generated by the ionic cli because it creates a separate module for components called components.module.ts.

It has the needed module component imports

ngFor with index as value in attribute

I think its already been answered before, but just a correction if you are populating an unordered list, the *ngFor will come in the element which you want to repeat. So it should be insdide <li>. Also, Angular2 now uses let to declare a variable.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">     
               {{item}}
    </li>
</ul>

How to convert minutes to Hours and minutes (hh:mm) in java

You can also use the TimeUnit class. You could define

private static final String FORMAT = "%02d:%02d:%02d";
can have a method like:

public static String parseTime(long milliseconds) {
      return String.format(FORMAT,
              TimeUnit.MILLISECONDS.toHours(milliseconds),
              TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(
              TimeUnit.MILLISECONDS.toHours(milliseconds)),
              TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(
              TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
   }

MetadataException when using Entity Framework Entity Connection

There are several possible catches. I think that the most common error is in this part of the connection string:

res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;

This is no magic. Once you understand what is stands for you'll get the connection string right.

First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.

Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.

Your final EF connection string may look like this:

res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;

How can I consume a WSDL (SOAP) web service in Python?

There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: python zeep.

See also this answer for an example.

Print an integer in binary format in Java

I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

So here's what I wrote:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

Invoke it like this:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

C compile : collect2: error: ld returned 1 exit status

Your problem is the typo in the function CreateDectionary().You should change it to CreateDictionary(). collect2: error: ld returned 1 exit status is the same problem in both C and C++, usually it means that you have unresolved symbols. In your case is the typo that i mentioned before.

Converting a string to an integer on Android

Kotlin

There are available Extension methods to parse them into other primitive types.

Java

String num = "10";
Integer.parseInt(num );

Should I test private methods or only public ones?

You should not. If your private methods have enough complexity that must be tested, you should put them on another class. Keep high cohesion, a class should have only one purpose. The class public interface should be enough.

Adding image inside table cell in HTML

You have referenced the image as a path on your computer (C:\etc\etc)......is it located there? You didn't answer what others have asked. I have taken your code, placed it in dreamweaver and it works apart from the image as I don't have that stored.

Check the location and then let us know.

Querying a linked sql server

You need to remove the quote marks from around the name of the linked server. It should be like this:

Select * from openquery(aa-db-dev01,'Select * from TestDB.dbo.users')

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

Most efficient conversion of ResultSet to JSON?

package com.idal.cib;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class DBJsonConverter {

    static ArrayList<String> data = new ArrayList<String>();
    static Connection conn = null;
    static PreparedStatement ps = null;
    static ResultSet rs = null;
    static String path = "";
    static String driver="";
    static String url="";
    static String username="";
    static String password="";
    static String query="";

    @SuppressWarnings({ "unchecked" })
    public static void dataLoad(String path) {
        JSONObject obj1 = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        conn = DatabaseConnector.getDbConnection(driver, url, username,
                password);
        try {
            ps = conn.prepareStatement(query);
            rs = ps.executeQuery();
            ArrayList<String> columnNames = new ArrayList<String>();
            if (rs != null) {
                ResultSetMetaData columns = rs.getMetaData();
                int i = 0;
                while (i < columns.getColumnCount()) {
                    i++;
                    columnNames.add(columns.getColumnName(i));
                }
                while (rs.next()) {
                    JSONObject obj = new JSONObject();
                    for (i = 0; i < columnNames.size(); i++) {
                        data.add(rs.getString(columnNames.get(i)));
                        {
                            for (int j = 0; j < data.size(); j++) {
                                if (data.get(j) != null) {
                                    obj.put(columnNames.get(i), data.get(j));
                                }else {
                                    obj.put(columnNames.get(i), "");
                                }
                            }
                        }
                    }

                    jsonArray.add(obj);
                    obj1.put("header", jsonArray);
                    FileWriter file = new FileWriter(path);
                    file.write(obj1.toJSONString());
                    file.flush();
                    file.close();
                }
                ps.close();
            } else {
                JSONObject obj2 = new JSONObject();
                obj2.put(null, null);
                jsonArray.add(obj2);
                obj1.put("header", jsonArray);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:database";
        username = "user";
        password = "password";
        path = "path of file";
        query = "select * from temp_employee";

        DatabaseConnector dc = new DatabaseConnector();
        dc.getDbConnection(driver,url,username,password);
        DBJsonConverter formatter = new DBJsonConverter();
        formatter.dataLoad(path);

    }

}




package com.idal.cib;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnector {

    static Connection conn1 = null;

    public static Connection getDbConnection(String driver, String url,
            String username, String password) {
        // TODO Auto-generated constructor stub
        try {

            Class.forName(driver);

            conn1 = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn1;
    }

}

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

How to shut down the computer from C#

Different methods:

A. System.Diagnostics.Process.Start("Shutdown", "-s -t 10");

B. Windows Management Instrumentation (WMI)

C. System.Runtime.InteropServices Pinvoke

D. System Management

After I submit, I have seen so many others also have posted...

What is bootstrapping?

IMHO there is not a better explanation than the fact about How was the first compiler written?

These days the Operating System loading is the most common process referred as Bootstrapping

git push rejected

Is your repository at "upstream" a bare repository? I got the same error, but when I change to bare they no longer happen.

Using sed to split a string with a delimiter

This should do it:

cat ~/Desktop/myfile.txt | sed s/:/\\n/g

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

How do I obtain the frequencies of each value in an FFT?

The FFT output coefficients (for complex input of size N) are from 0 to N - 1 grouped as [LOW,MID,HI,HI,MID,LOW] frequency.

I would consider that the element at k has the same frequency as the element at N-k since for real data, FFT[N-k] = complex conjugate of FFT[k].

The order of scanning from LOW to HIGH frequency is

0,

 1,
 N-1,

 2,
 N-2

 ...

 [N/2] - 1,
 N - ([N/2] - 1) = [N/2]+1,

 [N/2]

There are [N/2]+1 groups of frequency from index i = 0 to [N/2], each having the frequency = i * SamplingFrequency / N

So the frequency at bin FFT[k] is:

if k <= [N/2] then k * SamplingFrequency / N
if k >= [N/2] then (N-k) * SamplingFrequency / N

How do I get the current time zone of MySQL?

It may be

select timediff(current_time(),utc_time())

You won't get the timezone value directly this way.

@@global.time_zone cannot be used as it is a variable, and it returns the value 'SYSTEM'.

If you need to use your query in a session with a changed timezone by using session SET TIME_ZONE =, then you will get that with @@session.time_zone. If you query @@global.time_zone, then you get 'SYSTEM'.

If you try datediff, date_sub, or timediff with now() and utc_time(), then you'll probably run into conversion issues.

But the things suggested above will probably work at least with some server versions. My version is 5.5.43-37 and is a hosted solution.

Making a UITableView scroll when text field is selected

Use UITextField's delegate method :

Swift

func textFieldShouldBeginEditing(textField: UITextField) -> bool {
  let txtFieldPosition = textField.convertPoint(textField.bounds.origin, toView: yourTableViewHere)
  let indexPath = yourTablViewHere.indexPathForRowAtPoint(txtFieldPosition)
  if indexPath != nil {
     yourTablViewHere.scrollToRowAtIndexPath(indexPath!, atScrollPosition: .Top, animated: true)
  }
  return true
}

Objective-C

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
  CGPoint txtFieldPosition = [textField convertPoint:CGPointZero toView: yourTablViewHere];
  NSLog(@"Begin txtFieldPosition : %@",NSStringFromCGPoint(txtFieldPosition));
  NSIndexPath *indexPath = [yourTablViewHere indexPathForRowAtPoint:txtFieldPosition];

  if (indexPath != nil) {
     [yourTablViewHere scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  }
  return YES;
}

Disable browser cache for entire ASP.NET website

Instead of rolling your own, simply use what's provided for you.

As mentioned previously, do not disable caching for everything. For instance, jQuery scripts used heavily in ASP.NET MVC should be cached. Actually ideally you should be using a CDN for those anyway, but my point is some content should be cached.

What I find works best here rather than sprinkling the [OutputCache] everywhere is to use a class:

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class NoCacheController  : Controller
{
}

All of your controllers you want to disable caching for then inherit from this controller.

If you need to override the defaults in the NoCacheController class, simply specify the cache settings on your action method and the settings on your Action method will take precedence.

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ViewResult Index()
{
  ...
}

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Have had the same problem happen to me twice now, the only fix sofa has been to restart the tomcat server and restart the build.

Underscore prefix for property and method names in JavaScript

Welcome to 2019!

It appears a proposal to extend class syntax to allow for # prefixed variable to be private was accepted. Chrome 74 ships with this support.

_ prefixed variable names are considered private by convention but are still public.

This syntax tries to be both terse and intuitive, although it's rather different from other programming languages.

Why was the sigil # chosen, among all the Unicode code points?

  • @ was the initial favorite, but it was taken by decorators. TC39 considered swapping decorators and private state sigils, but the committee decided to defer to the existing usage of transpiler users.
  • _ would cause compatibility issues with existing JavaScript code, which has allowed _ at the start of an identifier or (public) property name for a long time.

This proposal reached Stage 3 in July 2017. Since that time, there has been extensive thought and lengthy discussion about various alternatives. In the end, this thought process and continued community engagement led to renewed consensus on the proposal in this repository. Based on that consensus, implementations are moving forward on this proposal.

See https://caniuse.com/#feat=mdn-javascript_classes_private_class_fields

How to install a python library manually

Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html

There are some tips which might help you.

jQuery remove special characters from string and more

Remove/Replace all special chars in Jquery :

If

str = My name is "Ghanshyam" and from "java" background

and want to remove all special chars (") then use this

str=str.replace(/"/g,' ')

result:

My name is Ghanshyam and from java background

Where g means Global

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

What does the CSS rule "clear: both" do?

CSS float and clear

Sample Fiddle

Just try to remove clear:both property from the div with class sample and see how it follows floating divs.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

String Fpath = getPath(this, uri) ;
File file = new File(Fpath);
String filename = file.getName();

get url content PHP

original answer moved to this topic .

replace NULL with Blank value or Zero in sql server

Replace Null Values as Empty: ISNULL('Value','')

Replace Null Values as 0: ISNULL('Value',0)

How to add http:// if it doesn't exist in the URL

Try this. It is not watertight1, but it might be good enough:

function addhttp($url) {
    if (!preg_match("@^[hf]tt?ps?://@", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

1. That is, prefixes like "fttps://" are treated as valid.

angularjs make a simple countdown

$scope.countDown = 30;
var timer;
$scope.countTimer = function () {
    var time = $timeout(function () {
         timer = setInterval(function () {
             if ($scope.countDown > 0) {
                 $scope.countDown--;
            } else {
                clearInterval(timer);
                $window.location.href = '/Logoff';
            }
            $scope.$apply();
        }, 1000);
    }, 0);
}

$scope.stop= function () {
    clearInterval(timer);
    
}

IN HTML:

<button type="submit" ng-click="countTimer()">Start</button>
<button type="submit" ng-click="stop()">Clear</button>
                 
                
              

Lodash - difference between .extend() / .assign() and .merge()

Lodash version 3.10.1

Methods compared

  • _.merge(object, [sources], [customizer], [thisArg])
  • _.assign(object, [sources], [customizer], [thisArg])
  • _.extend(object, [sources], [customizer], [thisArg])
  • _.defaults(object, [sources])
  • _.defaultsDeep(object, [sources])

Similarities

  • None of them work on arrays as you might expect
  • _.extend is an alias for _.assign, so they are identical
  • All of them seem to modify the target object (first argument)
  • All of them handle null the same

Differences

  • _.defaults and _.defaultsDeep processes the arguments in reverse order compared to the others (though the first argument is still the target object)
  • _.merge and _.defaultsDeep will merge child objects and the others will overwrite at the root level
  • Only _.assign and _.extend will overwrite a value with undefined

Tests

They all handle members at the root in similar ways.

_.assign      ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge       ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults    ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }

_.assign handles undefined but the others will skip it

_.assign      ({}, { a: 'a'  }, { a: undefined }) // => { a: undefined }
_.merge       ({}, { a: 'a'  }, { a: undefined }) // => { a: "a" }
_.defaults    ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }

They all handle null the same

_.assign      ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.merge       ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.defaults    ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }

But only _.merge and _.defaultsDeep will merge child objects

_.assign      ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge       ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults    ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}

And none of them will merge arrays it seems

_.assign      ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge       ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults    ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }

All modify the target object

a={a:'a'}; _.assign      (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge       (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults    (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }

None really work as expected on arrays

Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.

_.assign      ([], ['a'], ['bb']) // => [ "bb" ]
_.merge       ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults    ([], ['a'], ['bb']) // => [ "a"  ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a"  ]

_.assign      ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge       ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults    ([], ['a','b'], ['bb']) // => [ "a", "b"  ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b"  ]

How to set shape's opacity?

Use this one, I've written this to my app,

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#882C383E"/>
    <corners
        android:bottomRightRadius="5dp"
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp"/>
</shape>

How to convert a PNG image to a SVG?

I just found this question and answers as I am trying to do the same thing! I did not want to use some of the other tools mentioned. (Don't want to give my email away, and don't want to pay). I found that Inkscape (v0.91) can do a pretty good job. This tutorial is quick to and easy to understand.

Its as simple as selecting your bitmap in Inkskape and Shift+Alt+B.

Edge Detection with Inksape Trace bitmap tool based on potrace

Markdown and including multiple files

Just recently I wrote something like this in Node called markdown-include that allows you to include markdown files with C style syntax, like so:

#include "my-file.md"

I believe this aligns nicely with the question you're asking. I know this an old one, but I wanted to update it at least.

You can include this in any markdown file you wish. That file can also have more includes and markdown-include will make an internal link and do all of the work for you.

You can download it via npm

npm install -g markdown-include

How do I perform HTML decoding/encoding using Python/Django?

Below is a python function that uses module htmlentitydefs. It is not perfect. The version of htmlentitydefs that I have is incomplete and it assumes that all entities decode to one codepoint which is wrong for entities like &NotEqualTilde;:

http://www.w3.org/TR/html5/named-character-references.html

NotEqualTilde;     U+02242 U+00338    ??

With those caveats though, here's the code.

def decodeHtmlText(html):
    """
    Given a string of HTML that would parse to a single text node,
    return the text value of that node.
    """
    # Fast path for common case.
    if html.find("&") < 0: return html
    return re.sub(
        '&(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));',
        _decode_html_entity,
        html)

def _decode_html_entity(match):
    """
    Regex replacer that expects hex digits in group 1, or
    decimal digits in group 2, or a named entity in group 3.
    """
    hex_digits = match.group(1)  # '&#10;' -> unichr(10)
    if hex_digits: return unichr(int(hex_digits, 16))
    decimal_digits = match.group(2)  # '&#x10;' -> unichr(0x10)
    if decimal_digits: return unichr(int(decimal_digits, 10))
    name = match.group(3)  # name is 'lt' when '&lt;' was matched.
    if name:
        decoding = (htmlentitydefs.name2codepoint.get(name)
            # Treat &GT; like &gt;.
            # This is wrong for &Gt; and &Lt; which HTML5 adopted from MathML.
            # If htmlentitydefs included mappings for those entities,
            # then this code will magically work.
            or htmlentitydefs.name2codepoint.get(name.lower()))
        if decoding is not None: return unichr(decoding)
    return match.group(0)  # Treat "&noSuchEntity;" as "&noSuchEntity;"

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

How to catch a specific SqlException error?

The SqlException has a Number property that you can check. For duplicate error the number is 2601.

catch (SqlException e)
{
   switch (e.Number)
   {
      case 2601:
         // Do something.
         break;
      default:
         throw;
   }
 }

To get a list of all SQL errors from you server, try this:

 SELECT * FROM sysmessages

Update

This can now be simplified in C# 6.0

catch (SqlException e) when (e.Number == 2601)
{
   // Do something.
}

How do I add a Font Awesome icon to input field?

simple way for new font awesome

  <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search" name="txtSearch"  >
                    <div class="input-group-btn">
                        <button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Updated

For MS SQL Server 2012 and above

USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);

For MS SQL Server 2000, 2005, 2008

USE master;

DECLARE @kill varchar(8000); SET @kill = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('MyDB')

EXEC(@kill); 

How can I multiply all items in a list together with Python?

Starting Python 3.8, a .prod function has been included to the math module in the standard library:

math.prod(iterable, *, start=1)

The method returns the product of a start value (default: 1) times an iterable of numbers:

import math
math.prod([1, 2, 3, 4, 5, 6])

>>> 720

If the iterable is empty, this will produce 1 (or the start value, if provided).

Tools for creating Class Diagrams

Just discovered GenMyModel, an awesome UML modeler to design class diagram online

How to debug Spring Boot application with Eclipse?

With eclipse or any other IDE, just right click on your main spring boot application and click "debug as java application"

How to set image for bar button with swift?

Initialize barbuttonItem like following:

let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
                                  style: .plain,
                                  target: self,
                                  action: #selector(PlaybackViewController.pause))

Is there a "do ... until" in Python?

There is no do-while loop in Python.

This is a similar construct, taken from the link above.

 while True:
     do_something()
     if condition():
        break

Set Colorbar Range in matplotlib

Use the CLIM function (equivalent to CAXIS function in MATLAB):

plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4)  # identical to caxis([-4,4]) in MATLAB
plt.show()

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

Installing Google Protocol Buffers on mac

I used macports

sudo port install protobuf-cpp

Git - Won't add files?

In such cases, please check for rules in global .gitignore file and make sure that your folder does not fit into those.

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

How to delete shared preferences data from App in Android

My solution:

SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("text").commit();

Error: Generic Array Creation

Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.

This is the way methods like ArrayList.toArray(T[]) are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

How do I use raw_input in Python 3

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

Vuex - Computed property "name" was assigned to but it has no setter

For me it was changing.

this.name = response.data;

To what computed returns so;

this.$store.state.name = response.data;

Pretty printing XML with javascript

You can get pretty formatted xml with xml-beautify

var prettyXmlText = new XmlBeautify().beautify(xmlText, 
                    {indent: "  ",useSelfClosingElement: true});

indent:indent pattern like white spaces

useSelfClosingElement: true=>use self-closing element when empty element.

JSFiddle

Original(Before)

<?xml version="1.0" encoding="utf-8"?><example version="2.0">
  <head><title>Original aTitle</title></head>
  <body info="none" ></body>
</example>

Beautified(After)

<?xml version="1.0" encoding="utf-8"?>
<example version="2.0">
  <head>
    <title>Original aTitle</title>
  </head>
  <body info="none" />
</example>

Add click event on div tag using javascript

Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.

try if you really want to use class:

 document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};

or you may assign function in html itself:

<div class="drill_cursor" onclick='alert("1");'>
</div>

Align image to left of text on same line - Twitter Bootstrap3

You can use floating:

<div class="paragraphs">
  <div class="row">
    <div class="span4">
      <img style="float:left" src="../site/img/success32.png"/>
      <div class="content-heading"><h3>Experience &nbsp </h3></div>
      <p style="clear:both">Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

If you want the following <p> to stay at the same line too, remove its

style="clear:both"

but then you should add

<div style="clear:both"></div>

after it.

Recursion or Iteration?

I believe tail recursion in java is not currently optimized. The details are sprinkled throughout this discussion on LtU and the associated links. It may be a feature in the upcoming version 7, but apparently it presents certain difficulties when combined with Stack Inspection since certain frames would be missing. Stack Inspection has been used to implement their fine-grained security model since Java 2.

http://lambda-the-ultimate.org/node/1333

How to remove item from list in C#?

Short answer:
Remove (from list results)

results.RemoveAll(r => r.ID == 2); will remove the item with ID 2 in results (in place).

Filter (without removing from original list results):

var filtered = result.Where(f => f.ID != 2); returns all items except the one with ID 2

Detailed answer:

I think .RemoveAll() is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.

If you have:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

and assigned some values to results as follows:

var results = new List<myClass> {
    new myClass { ID=1, FirstName="Bill", LastName="Smith" },   // results[0]
    new myClass { ID=2, FirstName="John", LastName="Wilson" },  // results[1]
    new myClass { ID=3, FirstName="Doug", LastName="Berg" },    // results[2]
    new myClass { ID=4, FirstName="Bill", LastName="Wilson" }   // results[3]
};

Then you can define a list of IDs to remove:

var removeList = new List<int>() { 2, 3 };

And simply use this to remove them:

results.RemoveAll(r => removeList.Any(a => a==r.ID));

It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList. Note that this happens in place, so there is no additional assigment required.

Of course, you can also use it on single items like:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.

A last thing to mention is that lists have an indexer, that is, they can also be accessed like a dynamic array, i.e. results[3] will give you the 4th element in the results list (because the first element has the index 0, the 2nd has index 1 etc).

So if you want to remove all entries where the first name is the same as in the 4th element of the results list, you can simply do it this way:

results.RemoveAll(r => results[3].FirstName == r.FirstName);

Note that afterwards, only John and Doug will remain in the list, Bill is removed (the first and last element in the example). Important is that the list will shrink automatically, so it has only 2 elements left - and hence the largest allowed index after executing RemoveAll in this example is 1
(which is results.Count() - 1).

Some Trivia: You can use this knowledge and create a local function

void myRemove()  { var last = results.Count() - 1; 
                   results.RemoveAll(r => results[last].FirstName == r.FirstName); }

What do you think will happen, if you call this function twice? Like

myRemove(); myRemove(); 

The first call will remove Bill at the first and last position, the second call will remove Doug and only John Wilson remains in the list.


DotNetFiddle: Run the demo

Note: Since C# Version 8, you can as well write results[^1] instead of var last = results.Count() - 1; and results[last]:

void myRemove() { results.RemoveAll(r => results[^1].FirstName == r.FirstName); }

So you would not need the local variable last anymore (see indices and ranges. For a list of all the new features in C#, look here).

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

#include <stdio.h>
#include <stdint.h>

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

How can I create and style a div using JavaScript?

This will be inside a function or script tag with custom CSS with classname as Custom

 var board = document.createElement('div');
 board.className = "Custom";
 board.innerHTML = "your data";
 console.log(count);
 document.getElementById('notification').appendChild(board);

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

Yahoo Finance All Currencies quote API Documentation

From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.

EDIT:

There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):

The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.

At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.

How to determine a user's IP address in node

In your request object there is a property called connection, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

request.connection.remoteAddress

See documentation for http and net

EDIT

As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']

Largest and smallest number in an array

You (normally) cannot modify the collection you are iterating over when using foreach.

Although for and foreach seem to be similar from a developer perspective they are quite different from an implementation perspective.

Foreach uses an Iterator to access the individual objects while for doesn't know (or care) about the underlying object sequence.

How do I update all my CPAN modules to their latest versions?

An alternative method to using upgrade from the default CPAN shell is to use cpanminus and cpan-outdated.

These are so easy and nimble to use that I hardly ever go back to CPAN shell. To upgrade all of your modules in one go, the command is:

cpan-outdated -p | cpanm

I recommend you install cpanminus like the docs describe:

curl -L https://cpanmin.us | perl - App::cpanminus

And then install cpan-outdated along with all other CPAN modules using cpanm:

cpanm App::cpanoutdated

BTW: If you are using perlbrew then you will need to repeat this for every Perl you have installed under it.

You can find out more about cpanminus and cpan-outdated at the Github repos here:

Adding Permissions in AndroidManifest.xml in Android Studio?

Go to Android Manifest.xml and be sure to add the <uses-permission tag > inside the manifest tag but Outside of all other tags..

<manifest xlmns:android...>

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

This is an example of the permission of using Internet.

C++ class forward declaration

To perform *new tile_tree_apple the constructor of tile_tree_apple should be called, but in this place compiler knows nothing about tile_tree_apple, so it can't use the constructor.

If you put

tile tile_tree::tick() {if (rand()%20==0) return *new tile_tree_apple;};

in separate cpp file which has the definition of class tile_tree_apple or includes the header file which has the definition everything will work fine.

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

What is the official name for a credit card's 3 digit code?

You can't find a consistent reference because it seems to go by at least six different names!

  • Card Security Code
  • Card Verification Value (CVV or CV2)
  • Card Verification Value Code (CVVC)
  • Card Verification Code (CVC)
  • Verification Code (V-Code or V Code)
  • Card Code Verification (CCV)

Java Enum return Int

First you should ask yourself the following question: Do you really need an int?

The purpose of enums is to have a collection of items (constants), that have a meaning in the code without relying on an external value (like an int). Enums in Java can be used as an argument on switch statments and they can safely be compared using "==" equality operator (among others).

Proposal 1 (no int needed) :

Often there is no need for an integer behind it, then simply use this:

private enum DownloadType{
    AUDIO, VIDEO, AUDIO_AND_VIDEO
}

Usage:

DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
    //...
}
//or
switch (downloadType) {
  case AUDIO:  //...
          break;
  case VIDEO: //...
          break;
  case AUDIO_AND_VIDEO: //...
          break;
}

Proposal 2 (int needed) :

Nevertheless, sometimes it may be useful to convert an enum to an int (for instance if an external API expects int values). In this case I would advise to mark the methods as conversion methods using the toXxx()-Style. For printing override toString().

private enum DownloadType {
    AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
    private final int code;

    private DownloadType(int code) {
        this.code = code;
    }

    public int toInt() {
        return code;
    }

    public String toString() {
        //only override toString, if the returned value has a meaning for the
        //human viewing this value 
        return String.valueOf(code);
    }
}

System.out.println(DownloadType.AUDIO.toInt());           //returns 2
System.out.println(DownloadType.AUDIO);                   //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal());         //returns 0
System.out.println(DownloadType.AUDIO.name());            //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt());           //returns 5
System.out.println(DownloadType.VIDEO.ordinal());         //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11

Summary

  • Don't use an Integer together with an enum if you don't have to.
  • Don't rely on using ordinal() for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal() it might be better to use proposal 1.
  • Normally don't use int constants instead of enums (like in the accepted answer), because you will loose type-safety.

jQuery: Handle fallback for failed AJAX Request

You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    fail: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

EDIT I added a timeout to the $.ajax call and set it to five seconds.

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

How to ignore SSL certificate errors in Apache HttpClient 4.0

All of the other answers were either deprecated or didn't work for HttpClient 4.3.

Here is a way to allow all hostnames when building an http client.

CloseableHttpClient httpClient = HttpClients
    .custom()
    .setHostnameVerifier(new AllowAllHostnameVerifier())
    .build();

Or if you are using version 4.4 or later, the updated call looks like this:

CloseableHttpClient httpClient = HttpClients
    .custom()
    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
    .build();

How to log SQL statements in Spring Boot?

Log in to standard output

Add to application.properties

### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.

Using Logging Framework

Add to application.properties

### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.

How to unpack and pack pkg file?

@shrx I've succeeded to unpack the BSD.pkg (part of the Yosemite installer) by using "pbzx" command.

pbzx <pkg> | cpio -idmu

The "pbzx" command can be downloaded from the following link:

How to find largest objects in a SQL Server database?

@marc_s's answer is very great and I've been using it for few years. However, I noticed that the script misses data in some columnstore indexes and doesn't show complete picture. E.g. when you do SUM(TotalSpace) against the script and compare it with total space database property in Management Studio the numbers don't match in my case (Management Studio shows larger numbers). I modified the script to overcome this issue and extended it a little bit:

select
    tables.[name] as table_name,
    schemas.[name] as schema_name,
    isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown') as database_name,
    sum(allocation_units.total_pages) * 8 as total_space_kb,
    cast(round(((sum(allocation_units.total_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as total_space_mb,
    sum(allocation_units.used_pages) * 8 as used_space_kb,
    cast(round(((sum(allocation_units.used_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as used_space_mb,
    (sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8 as unused_space_kb,
    cast(round(((sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8) / 1024.00, 2) as numeric(36, 2)) as unused_space_mb,
    count(distinct indexes.index_id) as indexes_count,
    max(dm_db_partition_stats.row_count) as row_count,
    iif(max(isnull(user_seeks, 0)) = 0 and max(isnull(user_scans, 0)) = 0 and max(isnull(user_lookups, 0)) = 0, 1, 0) as no_reads,
    iif(max(isnull(user_updates, 0)) = 0, 1, 0) as no_writes,
    max(isnull(user_seeks, 0)) as user_seeks,
    max(isnull(user_scans, 0)) as user_scans,
    max(isnull(user_lookups, 0)) as user_lookups,
    max(isnull(user_updates, 0)) as user_updates,
    max(last_user_seek) as last_user_seek,
    max(last_user_scan) as last_user_scan,
    max(last_user_lookup) as last_user_lookup,
    max(last_user_update) as last_user_update,
    max(tables.create_date) as create_date,
    max(tables.modify_date) as modify_date
from 
    sys.tables
    left join sys.schemas on schemas.schema_id = tables.schema_id
    left join sys.indexes on tables.object_id = indexes.object_id
    left join sys.partitions on indexes.object_id = partitions.object_id and indexes.index_id = partitions.index_id
    left join sys.allocation_units on partitions.partition_id = allocation_units.container_id
    left join sys.dm_db_index_usage_stats on tables.object_id = dm_db_index_usage_stats.object_id and indexes.index_id = dm_db_index_usage_stats.index_id
    left join sys.dm_db_partition_stats on tables.object_id = dm_db_partition_stats.object_id and indexes.index_id = dm_db_partition_stats.index_id
group by schemas.[name], tables.[name], isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown')
order by 5 desc

Hope it will be helpful for someone. This script was tested against large TB-wide databases with hundreds of different tables, indexes and schemas.

raw vs. html_safe vs. h to unescape html

I think it bears repeating: html_safe does not HTML-escape your string. In fact, it will prevent your string from being escaped.

<%= "<script>alert('Hello!')</script>" %>

will put:

&lt;script&gt;alert(&#x27;Hello!&#x27;)&lt;/script&gt;

into your HTML source (yay, so safe!), while:

<%= "<script>alert('Hello!')</script>".html_safe %>

will pop up the alert dialog (are you sure that's what you want?). So you probably don't want to call html_safe on any user-entered strings.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

height: calc(100%) not working correctly in CSS

You don't need to calculate anything, and probably shouldn't:

<!DOCTYPE html>
<head>
<style type="text/css">
    body {background: blue; height:100%;}
    header {background: red; height: 20px; width:100%}
    h1 {font-size:1.2em; margin:0; padding:0; 
        height: 30px; font-weight: bold; background:yellow}
    .theCalcDiv {background-color:green; padding-bottom: 100%}
</style>
</head>
<body>
<header>Some nav stuff here</header>
<h1>This is the heading</h1>
<div class="theCalcDiv">This blocks needs to have a CSS calc() height of 100% - the height of the other elements.
</div>

I stuck it all together for brevity.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

How to set border's thickness in percentages?

You can use em for percentage instead of pixels,

Example:

border:10PX dotted #c1a9ff; /* In Pixels */
border:0.75em dotted #c1a9ff; /* Exact same as above in Percentage */

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

SQL: How to to SUM two values from different tables

SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result

'And so on and so forth.

"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source

Int division: Why is the result of 1/3 == 0?

Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.

To get the result you are looking for, explicitly tell java that the numbers are doubles like so:

double g = 1.0/3.0;

How to catch curl errors in PHP

    $responseInfo = curl_getinfo($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($response, $header_size);
    $result=array();
    $result['httpCode']=$httpCode;
    $result['body']=json_decode($body);
    $result['responseInfo']=$responseInfo;
    print_r($httpCode); 
     print_r($result['body']); exit;
    curl_close($ch);
    if($httpCode == 403)
    {
        print_r("Access denied");
        exit;
    }   
    else
     {
         //catch more errors 
     }

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

this worked for me

// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = new PathString("/auth/login");
            options.AccessDeniedPath = new PathString("/auth/denied");
        });

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

How do I tell if a regular file does not exist in Bash?

You should be careful about running test for an unquoted variable, because it might produce unexpected results:

$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1

The recommendation is usually to have the tested variable surrounded by double quotation marks:

#!/bin/sh
FILE=$1

if [ ! -f "$FILE" ]
then
   echo "File $FILE does not exist."
fi

CardView background color always white

You can do it either in XML or programmatically:

In XML:

card_view:cardBackgroundColor="@android:color/red"

Programmatically:

cardView.setCardBackgroundColor(Color.RED);

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

How can I read comma separated values from a text file in Java?

You can also use the java.util.Scanner class.

private static void readFileWithScanner() {
    File file = new File("path/to/your/file/file.txt");

    Scanner scan = null;

    try {
        scan = new Scanner(file);

        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            String[] lineArray = line.split(",");
            // do something with lineArray, such as instantiate an object
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        scan.close();
    }
}

How to perform a sum of an int[] array

int sum=0;
for(int i:A)
  sum+=i;

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I just encountered this and my problem was caused by having two entities both with the System.ComponentModel.DataAnnotations.Schema.TableAttribute referring to the same table.

for example:

[Table("foo")]
public class foo
{
    // some stuff here
}

[Table("foo")]
public class fooExtended
{
    // more stuff here
}

changing the second one from foo to foo_extended fixed this for me and I'm now using Table Per Type (TPT)

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

Local Variable

Another possible, but less eloquent and less encouraged, way is to bind this to a var outside of setTimeout:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Declare self, which is accessible inside setTimeout func
        var self = this;
        setTimeout(function() {
             self.basketAddSuccess = false;
        }, 2000);
    }

Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.

403 Forbidden vs 401 Unauthorized HTTP responses

This is simpler in my head than anywhere here, so:

401: You need HTTP basic auth to see this.

403: You can't see this, and HTTP basic auth won't help.

If the user just needs to log in using you site's standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.

I don't recommend using 403 to deny access to things like /includes, because as far as the web is concerned, those resources don't exist at all and should therefore 404.

This leaves 403 as "you need to be logged in".

In other words, 403 means "this resource requires some form of auth other than HTTP basic auth".

https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2

Email Address Validation in Android on EditText

Try this:

if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+\.[a-z]+")) {
 editTextEmail.setError("Invalid Email Address");
}

join list of lists in python

Sadly, Python doesn't have a simple way to flatten lists. Try this:

def flatten(some_list):
    for element in some_list:
        if type(element) in (tuple, list):
            for item in flatten(element):
                yield item
        else:
            yield element

Which will recursively flatten a list; you can then do

result = []
[ result.extend(el) for el in x] 

for el in flatten(result):
      print el

How to set the current working directory?

people using pandas package

import os
import pandas as pd

tar = os.chdir('<dir path only>') # do not mention file name here
print os.getcwd()# to print the path name in CLI

the following syntax to be used to import the file in python CLI

dataset(*just a variable) = pd.read_csv('new.csv')

In c# is there a method to find the max of 3 numbers?

Linq has a Max function.

If you have an IEnumerable<int> you can call this directly, but if you require these in separate parameters you could create a function like this:

using System.Linq;

...

static int Max(params int[] numbers)
{
    return numbers.Max();
}

Then you could call it like this: max(1, 6, 2), it allows for an arbitrary number of parameters.

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I had the same issue. In the Google APIs Console, you should check that there is only one key generated for that app. I had a stretch where I migrated my code from one PC to the next and so on (it got messy), and had multiple keys for my one project. The older keys are all listed as inactive on the API console page, but for some reason caused a conflict. After deleting them completely, I ran it again and it worked.

Converting stream of int's to char's in java

It depends on what you mean by "convert an int to char".

If you simply want to cast the value in the int, you can cast it using Java's typecast notation:

int i = 97; // 97 is 'a' in ASCII
char c = (char) i; // c is now 'a'

If you mean transforming the integer 1 into the character '1', you can do it like this:

if (i >= 0 && i <= 9) {
char c = Character.forDigit(i, 10);
....
}

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Difference between jQuery .hide() and .css("display", "none")

see http://api.jquery.com/show/

With no parameters, the .show() method is the simplest way to display an element:

$('.target').show();

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

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

I encountered the same problem while trying to install rvm for ruby. found the solution: after extracting curl (tar) in downloads folder of root.

cd /root/Downloads/curl # step-1
./configure --with-ssl # step-2
make # step-3
make install # step-4 (if not root, use sudo before command)

source

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

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

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

How I could add dir to $PATH in Makefile?

What I usually do is supply the path to the executable explicitly:

EXE=./bin/
...
test all:
    $(EXE)x

I also use this technique to run non-native binaries under an emulator like QEMU if I'm cross compiling:

EXE = qemu-mips ./bin/

If make is using the sh shell, this should work:

test all:
    PATH=bin:$PATH x

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I tried the following:

aws s3 ls s3.console.aws.amazon.com/s3/buckets/{bucket name}

This gave me the error:

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Using this form worked:

aws s3 ls {bucket name}

WPF Datagrid set selected row

If anyone stumblng here has problems with internal grid selection happening after OnSelectionChanged - after unsuccessfully trying out all the selection setters for a dozen hours the only thing that worked for me was reloading and repopulating DataGrid along with selected item. Not elegant at all, but at this point I'm not sure if a better solution exists in my situation.

datagrid.ItemsSource = null
datagrid.ItemsSource = items;
datagrid.SelectedItem = selectedItem;

How do I create a simple 'Hello World' module in Magento?

I've been wrestling with Magento for the last month or so and I'm still trying to figure it out. So this is a case of the blind leading the blind. There's little in the way of documentation and the forum/wiki is chaotic at best. Not only that, but there are several solutions that are either outdated or far from optimal. I'm not sure if you have a project or just trying to figure it out, but it's probably easier if you started with modifying existing functionality as opposed to creating something completely new. For that I'd definately go with the "Recommended articles for developers" in the wiki. The new payment method one was a real eye-opener.

For debugging I'd definitely recommend using FirePHP and looking at your HTML source when something goes wrong. The ole echo debug method doesn't really work all that well.

The general architecture is so mind-numbingly complex, that even if I completely understood it, I'd need to write a book to cover it. The best I can do is give you advice I wish someone had given me when I first started...

Stay away from core files. Don't modify them, instead write your own module and override what you need.

Magento uses config files consisting of XML to decide what it needs to do. In order to get it to run your own stuff as opposed to core functionality you need the correct xml. Unfortunately there is no guide on how to build you XML; you need to look at examples and do some serious testing. To complicate things the content of these files is largely case-sensitive. However if you master these you can override any part of the basic functionality which makes for a very powerful system.

Magento uses methods like Mage::getModel('mymodel'), Mage::getSingleton('mysingleton'), Mage::helper('myhelper') to return objects of certain classes. It finds these by default in its core namespace. If you want it to use your own, you need to override these in your config.xml file.

The name of your classes must correspond to the folder they're in.

A lot of the objects in Magento ultimately extend something called a Varien_Object. This is a general purpose class (kind of like a swiss army knife) and its purpose in life is to allow you to define your own methods/variables on the fly. For example you'll see it used as a glorified array to pass data from one method to another.

During development make sure you caching is disabled. It'll make magento excruciatingly slow, but it'll save you a lot of head trauma (from banging it on your desk).

You'll see $this being used a lot. It means a different class depending on what file you see it. get_class($this) is your friend, especially in conjunction with FirePHP.

Jot things down on paper. A lot. There are countless little factoids that you're gonna need 1-2 days after you encounter them.

Magento loves OO. Don't be surprised if tracing a method takes you through 5-10 different classes.

Read the designer's guide here. It's meant mostly for graphics designers, but you need it to understand where and why the output from your module will end up. For that don't forget to turn on "Template path hints" in the developer section of the admin panel.

There's more, but I'll stop here before this turns into a dissertation.

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

ASP.NET: Session.SessionID changes between requests

I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)] were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)

It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.

How do I get my C# program to sleep for 50 msec?

System.Threading.Thread.Sleep(50);

Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")

Just remove the ; to make it work for VB.net as well.

OPTION (RECOMPILE) is Always Faster; Why?

Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.

  1. STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.

  2. PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.

  3. INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.

  4. ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.

  5. THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.

In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

Show whitespace characters in Visual Studio Code

UPDATE (June 2019)

For those willing to toggle whitespace characters using a keyboard shortcut, you can easily add a keybinding for that.

In the latest versions of Visual Studio Code there is now a user-friendly graphical interface (i.e. no need to type JSON data etc) for viewing and editing all the available keyboard shortcuts. It is still under

File > Preferences > Keyboard Shortcuts (or use Ctrl+K Ctrl+S)

There is also a search field to help quickly find (and filter) the desired keybindings. So now both adding new and editing the existing keybindings is much easier:

enter image description here


Toggling whitespace characters has no default keybinding so feel free to add one. Just press the + sign on the left side of the related line (or press Enter, or double click anywhere on that line) and enter the desired combination in the pop-up window.

And if the keybinding you have chosen is already used for some other action(s) there will be a convenient warning which you can click and observe what action(s) already use your chosen keybinding:

enter image description here

As you can see, everything is very intuitive and convenient.
Good job, Microsoft!


Original (old) answer

For those willing to toggle whitespace characters using a keyboard shortcut, you can add a custom binding to the keybindings.json file (File > Preferences > Keyboard Shortcuts).

Example:

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key": "ctrl+shift+i",
        "command": "editor.action.toggleRenderWhitespace"
    }
]

Here I have assigned a combination of Ctrl+Shift+i to toggle invisible characters, you may of course choose another combination.

Google maps Places API V3 autocomplete - select first option on enter

I just want to write an small enhancement for the answer of amirnissim
The script posted doesn't support IE8, because "event.which" seems to be always empty in IE8.
To solve this problem you just need to additionally check for "event.keyCode":

listener = function (event) {
  if (event.which == 13 || event.keyCode == 13) {
    var suggestion_selected = $(".pac-item.pac-selected").length > 0;
    if(!suggestion_selected){
      var simulated_downarrow = $.Event("keydown", {keyCode:40, which:40})
      orig_listener.apply(input, [simulated_downarrow]);
    }
  }
  orig_listener.apply(input, [event]);
};

JS-Fiddle: http://jsfiddle.net/QW59W/107/

Google Play Services Library update and missing symbol @integer/google_play_services_version

after the update to the last versión i had this problem with all my projects, but it was solved just adding again the library reference:

if you don´t have the library into your workspace in Eclipse you can add it with: File -> Import -> Existing Android Code Into Workspace -> browse and navigate to google-play-services_lib project lib, (android-sdk/extras/google/google_play_services/libproject).

enter image description here

then deleting /bin and /gen folders of my project (something similar to the clean option) and building my project again.

Undoing a git rebase

git reset --hard origin/{branchName}

is the correct solution to reset all your local changes done by rebase.

PHP CURL Enable Linux

add this line end of php.ini

openssl.cafile=/opt/lampp/share/curl/curl-ca-bundle.crt

may be curl path cannot be identified by PHP

With ng-bind-html-unsafe removed, how do I inject HTML?

I've had a similar problem. Still couldn't get content from my markdown files hosted on github.

After setting up a whitelist (with added github domain) to the $sceDelegateProvider in app.js it worked like a charm.

Description: Using a whitelist instead of wrapping as trusted if you load content from a different urls.

Docs: $sceDelegateProvider and ngInclude (for fetching, compiling and including external HTML fragment)

receiver type *** for instance message is a forward declaration

That basically means that you need to import the .h file containing the declaration of States.

However, there is a lot of other stuff wrong with your code.

  • You're -init'ing an object without +alloc'ing it. That won't work
  • You're declaring an object as a non-pointer type, that won't work either
  • You're not calling [super init] in -init.
  • You've declared the class using @class in the header, but never imported the class.

Equivalent of typedef in C#

I think there is no typedef. You could only define a specific delegate type instead of the generic one in the GenericClass, i.e.

public delegate GenericHandler EventHandler<EventData>

This would make it shorter. But what about the following suggestion:

Use Visual Studio. This way, when you typed

gcInt.MyEvent += 

it already provides the complete event handler signature from Intellisense. Press TAB and it's there. Accept the generated handler name or change it, and then press TAB again to auto-generate the handler stub.

Python Hexadecimal

I think this is what you want:

>>> def twoDigitHex( number ):
...     return '%02x' % number
... 
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'

Getting query parameters from react-router hash fragment

OLD (pre v4):

Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:

this.props.location.query

It creates a hash of all available query params in the url.

UPDATE (React Router v4+):

this.props.location.query in React Router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/ReactTraining/react-router/issues/4410

Looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string

Running multiple async tasks and waiting for them all to complete

Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

var cats = new List<Cat>();
var dog = new Dog();

var loadDataTasks = new Task[]
{
    Task.Run(async () => cats = await LoadCatsAsync()),
    Task.Run(async () => dog = await LoadDogAsync())
};

try
{
    await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
    // handle exception
}

How to Correctly Check if a Process is running and Stop it

Thanks @Joey. It's what I am looking for.

I just bring some improvements:

  • to take into account multiple processes
  • to avoid reaching the timeout when all processes have terminated
  • to package the whole in a function

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    $processList = Get-Process $processName -ErrorAction SilentlyContinue
    if ($processList) {
        # Try gracefully first
        $processList.CloseMainWindow() | Out-Null

        # Wait until all processes have terminated or until timeout
        for ($i = 0 ; $i -le $timeout; $i ++){
            $AllHaveExited = $True
            $processList | % {
                $process = $_
                If (!$process.HasExited){
                    $AllHaveExited = $False
                }                    
            }
            If ($AllHaveExited){
                Return
            }
            sleep 1
        }
        # Else: kill
        $processList | Stop-Process -Force        
    }
}

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

Worked for me in VS2003 and VS2017 on Windows 8

  1. Run the command in CMD with admin rights

    netsh http add iplisten ipaddress=::

  2. Then go to regedit path [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters] and check if the value has been added. enter image description here

For more details check https://www.c-sharpcorner.com/blogs/iis-express-failed-to-register-url-access-is-denied

How do I make CMake output into a 'bin' dir?

$ cat CMakeLists.txt
project (hello)
set(EXECUTABLE_OUTPUT_PATH "bin")
add_executable (hello hello.c)

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

How to change text transparency in HTML/CSS?

What about the css opacity attribute? 0 to 1 values.

But then you probably need to use a more explicit dom element than "font". For instance:

<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>

As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.

For cross browser css3 styles generator, have a look at http://css3please.com/

Pipenv: Command Not Found

Installing pipenv globally can have an adverse effect by overwriting the global/system-managed pip installation, thus resulting in import errors when trying to run pip.

You can install pipenv at the user level:

pip install --user pipenv

This should install pipenv at a user-level in /home/username/.local so that it does not conflict with the global version of pip. In my case, that still did not work after running the '--user' switch, so I ran the longer 'fix what I screwed up' command once to restore the system managed environment:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

^ found here: Error after upgrading pip: cannot import name 'main'

and then did the following:

mkdir /home/username/.local ... if it doesn't already exist

export PYTHONUSERBASE=/home/username/.local

Make sure the export took effect (bit me once during this process):

echo $PYTHONUSERBASE

Then, I ran the pip install --user pipenv and all was well. I could then run pipenv from the CLI and it did not overwrite the global/system-managed pip module. Of course, this is specific to the user so you want to make sure you install pipenv this way while working as the user you wish to use pipenv.

References:

https://pipenv.readthedocs.io/en/latest/diagnose/#no-module-named-module-name https://pipenv.readthedocs.io/en/latest/install/#pragmatic-installation-of-pipenv https://pip.pypa.io/en/stable/user_guide/#user-installs

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

Connecting to Postgresql in a docker container from outside

I know this is late, if you used docker-compose like @Martin

These are the snippets that helped me connect to psql inside the container

docker-compose run db bash

root@de96f9358b70:/# psql -h db -U root -d postgres_db

I cannot comment because I don't have 50 reputation. So hope this helps.

Writing image to local server

I suggest you use http-request, so that even redirects are managed.

var http = require('http-request');
var options = {url: 'http://localhost/foo.pdf'};
http.get(options, '/path/to/foo.pdf', function (error, result) {
    if (error) {
        console.error(error);
    } else {
        console.log('File downloaded at: ' + result.file);
    }
});

How to get a random value from dictionary?

Since the original post wanted the pair:

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))

(python 3 style)

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

How to insert multiple rows from array using CodeIgniter framework?

Assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

That said, it sounds like you might be running into string-handling problems in PHP, which is really an algorithm problem, not a language one. Basically, when working with large strings, you want to minimize unnecessary copying. Primarily, this means you want to avoid concatenation. The fastest and most memory efficient way to build a large string, such as for inserting hundreds of rows at one, is to take advantage of the implode() function and array assignment.

$sql = array(); 
foreach( $data as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));

The advantage of this approach is that you don't copy and re-copy the SQL statement you've so far assembled with each concatenation; instead, PHP does this once in the implode() statement. This is a big win.

If you have lots of columns to put together, and one or more are very long, you could also build an inner loop to do the same thing and use implode() to assign the values clause to the outer array.

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

If you are using Visual Studio. The reason you might be recieving this error may be because you originally created a new header file.h and then renamed it to file.cpp where you placed your main() function.

To fix the issue right click file.cpp -> click Properties go to
Configuration Properties -> General ->Item Type and change its value to C/C++ compiler instead of C/C++ header.

Best Practices: working with long, multiline strings in PHP?

In regards to your question about newlines and carriage returns:

I would recommend using the predefined global constant PHP_EOL as it will solve any cross-platform compatibility issues.

This question has been raised on SO beforehand and you can find out more information by reading "When do I use the PHP constant PHP_EOL"

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

2021 Xcode 12.3 update

To solve this problem one would need to disable the standard section footer. The following snippet does the job:

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    return nil
}

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 0
}

Usage of

tableView.contentInsetAdjustmentBehavior = .never

is completely unrelated here

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

I do not want to inherit the child opacity from the parent in CSS

Assign opacity 1.0 to the child recursively with:

div > div { opacity: 1.0 }

Example:

_x000D_
_x000D_
div.x { opacity: 0.5 }_x000D_
div.x > div.x { opacity: 1.0 }
_x000D_
<div style="background-color: #f00; padding:20px;">_x000D_
  <div style="background-color: #0f0; padding:20px;">_x000D_
    <div style="background-color: #00f; padding:20px;">_x000D_
      <div style="background-color: #000; padding:20px; color:#fff">_x000D_
         Example Text - No opacity definition_x000D_
      </div>_x000D_
    </div>  _x000D_
  </div>_x000D_
</div>_x000D_
<div style="opacity:0.5; background-color: #f00; padding:20px;">_x000D_
  <div style="opacity:0.5; background-color: #0f0; padding:20px;">_x000D_
    <div style="opacity:0.5; background-color: #00f; padding:20px;">_x000D_
      <div style="opacity:0.5; background-color: #000; padding:20px; color:#fff">_x000D_
        Example Text - 50% opacity inherited_x000D_
      </div>_x000D_
    </div>  _x000D_
  </div>_x000D_
</div>_x000D_
<div class="x" style="background-color: #f00; padding:20px;">_x000D_
  <div class="x" style="background-color: #0f0; padding:20px;">_x000D_
    <div class="x" style="background-color: #00f; padding:20px;">_x000D_
      <div class="x" style="background-color: #000; padding:20px; color:#fff">_x000D_
         Example Text - 50% opacity not inherited_x000D_
      </div>_x000D_
    </div>  _x000D_
  </div>_x000D_
</div>_x000D_
<div style="opacity: 0.5; background-color: #000; padding:20px; color:#fff">_x000D_
  Example Text - 50% opacity_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using a bitmask in C#

if ( ( param & karen ) == karen )
{
  // Do stuff
}

The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:

if ( ( param & karen ) == karen )
{
  // Do Karen's stuff
}
if ( ( param & bob ) == bob )
  // Do Bob's stuff
}

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

tmux set -g mouse-mode on doesn't work

So this option has been renamed in version 2.1 (18 October 2015)

From the changelog:

 Mouse-mode has been rewritten.  There's now no longer options for:
    - mouse-resize-pane
    - mouse-select-pane
    - mouse-select-window
    - mode-mouse

  Instead there is just one option:  'mouse' which turns on mouse support

So this is what I'm using now in my .tmux.conf file

set -g mouse on

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Today I ran into this issue, on Xcode 11.2.1 I solved it by going to Xcode -> Preferences -> Accounts -> Tapped on the '-' next to my Apple ID, then signed in again. This fixed it for me!

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

How to add a border to a widget in Flutter?

Here is an expanded answer. A DecoratedBox is what you need to add a border, but I am using a Container for the convenience of adding margin and padding.

Here is the general setup.

enter image description here

Widget myWidget() {
  return Container(
    margin: const EdgeInsets.all(30.0),
    padding: const EdgeInsets.all(10.0),
    decoration: myBoxDecoration(), //             <--- BoxDecoration here
    child: Text(
      "text",
      style: TextStyle(fontSize: 30.0),
    ),
  );
}

where the BoxDecoration is

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(),
  );
}

Border width

enter image description here

These have a border width of 1, 3, and 10 respectively.

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(
      width: 1, //                   <--- border width here
    ),
  );
}

Border color

enter image description here

These have a border color of

  • Colors.red
  • Colors.blue
  • Colors.green

Code

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(
      color: Colors.red, //                   <--- border color
      width: 5.0,
    ),
  );
}

Border side

enter image description here

These have a border side of

  • left (3.0), top (3.0)
  • bottom (13.0)
  • left (blue[100], 15.0), top (blue[300], 10.0), right (blue[500], 5.0), bottom (blue[800], 3.0)

Code

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border(
      left: BorderSide( //                   <--- left side
        color: Colors.black,
        width: 3.0,
      ),
      top: BorderSide( //                    <--- top side
        color: Colors.black,
        width: 3.0,
      ),
    ),
  );
}

Border radius

enter image description here

These have border radii of 5, 10, and 30 respectively.

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(
      width: 3.0
    ),
    borderRadius: BorderRadius.all(
        Radius.circular(5.0) //                 <--- border radius here
    ),
  );
}

Going on

DecoratedBox/BoxDecoration are very flexible. Read Flutter — BoxDecoration Cheat Sheet for many more ideas.

Maximum length for MySQL type text

TINYTEXT 256 bytes
TEXT 65,535 bytes ~64kb
MEDIUMTEXT 16,777,215 bytes ~16MB
LONGTEXT 4,294,967,295 bytes ~4GB

TINYTEXT is a string data type that can store up to to 255 characters.

TEXT is a string data type that can store up to 65,535 characters. TEXT is commonly used for brief articles.

LONGTEXT is a string data type with a maximum length of 4,294,967,295 characters. Use LONGTEXT if you need to store large text, such as a chapter of a novel.

Loop through all nested dictionary values?

A alternative solution to work with lists based on Scharron's solution

def myprint(d):
    my_list = d.iteritems() if isinstance(d, dict) else enumerate(d)

    for k, v in my_list:
        if isinstance(v, dict) or isinstance(v, list):
            myprint(v)
        else:
            print u"{0} : {1}".format(k, v)

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).

Thus, it was failing as "Not allowed", since there was no method with POST type on my end.

Changing @GET to @POST above my WS method fixed the issue.

Select SQL Server database size

Try this one -

Query:

SELECT 
      database_name = DB_NAME(database_id)
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID() -- for current db 
GROUP BY database_id

Output:

-- my query
name           log_size_mb  row_size_mb   total_size_mb
-------------- ------------ ------------- -------------
xxxxxxxxxxx    512.00       302.81        814.81

-- sp_spaceused
database_name    database_size      unallocated space
---------------- ------------------ ------------------
xxxxxxxxxxx      814.81 MB          13.04 MB

Function:

ALTER FUNCTION [dbo].[GetDBSize] 
(
    @db_name NVARCHAR(100)
)
RETURNS TABLE
AS
RETURN

  SELECT 
        database_name = DB_NAME(database_id)
      , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
      , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
      , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
  FROM sys.master_files WITH(NOWAIT)
  WHERE database_id = DB_ID(@db_name)
      OR @db_name IS NULL
  GROUP BY database_id

UPDATE 2016/01/22:

Show information about size, free space, last database backups

IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
    , bu.full_last_date
    , bu.full_size
    , bu.log_last_date
    , bu.log_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
    SELECT
          database_name
        , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
        , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
        , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
        , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
    FROM (
        SELECT
              s.database_name
            , s.[type]
            , s.backup_finish_date
            , backup_size =
                        CAST(CASE WHEN s.backup_size = s.compressed_backup_size
                                    THEN s.backup_size
                                    ELSE s.compressed_backup_size
                        END / 1048576.0 AS DECIMAL(18,2))
            , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
        FROM msdb.dbo.backupset s
        WHERE s.[type] IN ('D', 'L')
    ) f
    WHERE f.RowNum = 1
    GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC

Output:

database_id name                             state_desc   recovery_model_desc total_size   data_size   data_used_size  log_size    log_used_size  full_last_date          full_size    log_last_date           log_size
----------- -------------------------------- ------------ ------------------- ------------ ----------- --------------- ----------- -------------- ----------------------- ------------ ----------------------- ---------
24          StackOverflow                    ONLINE       SIMPLE              66339.88     65840.00    65102.06        499.88      5.05           NULL                    NULL         NULL                    NULL
11          AdventureWorks2012               ONLINE       SIMPLE              16404.13     15213.00    192.69          1191.13     15.55          2015-11-10 10:51:02.000 44.59        NULL                    NULL
10          locateme                         ONLINE       SIMPLE              1050.13      591.00      2.94            459.13      6.91           2015-11-06 15:08:34.000 17.25        NULL                    NULL
8           CL_Documents                     ONLINE       FULL                793.13       334.00      333.69          459.13      12.95          2015-11-06 15:08:31.000 309.22       2015-11-06 13:15:39.000 0.01
1           master                           ONLINE       SIMPLE              554.00       492.06      4.31            61.94       5.20           2015-11-06 15:08:12.000 0.65         NULL                    NULL
9           Refactoring                      ONLINE       SIMPLE              494.32       366.44      308.88          127.88      34.96          2016-01-05 18:59:10.000 37.53        NULL                    NULL
3           model                            ONLINE       SIMPLE              349.06       4.06        2.56            345.00      0.97           2015-11-06 15:08:12.000 0.45         NULL                    NULL
13          sql-format.com                   ONLINE       SIMPLE              216.81       181.38      149.00          35.44       3.06           2015-11-06 15:08:39.000 23.64        NULL                    NULL
23          users                            ONLINE       FULL                173.25       73.25       3.25            100.00      5.66           2015-11-23 13:15:45.000 0.72         NULL                    NULL
4           msdb                             ONLINE       SIMPLE              46.44        20.25       19.31           26.19       4.09           2015-11-06 15:08:12.000 2.96         NULL                    NULL
21          SSISDB                           ONLINE       FULL                45.06        40.00       4.06            5.06        4.84           2014-05-14 18:27:11.000 3.08         NULL                    NULL
27          tSQLt                            ONLINE       SIMPLE              9.00         5.00        3.06            4.00        0.75           NULL                    NULL         NULL                    NULL
2           tempdb                           ONLINE       SIMPLE              8.50         8.00        4.50            0.50        1.78           NULL                    NULL         NULL                    NULL

How to save a Seaborn plot into a file

Some of the above solutions did not work for me. The .fig attribute was not found when I tried that and I was unable to use .savefig() directly. However, what did work was:

sns_plot.figure.savefig("output.png")

I am a newer Python user, so I do not know if this is due to an update. I wanted to mention it in case anybody else runs into the same issues as I did.

How to remove/ignore :hover css style on touch devices

Try this (i use background and background-color in this example):

var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');

if (ClickEventType == 'touchstart') {
            $('a').each(function() { // save original..
                var back_color = $(this).css('background-color');
                var background = $(this).css('background');
                $(this).attr('data-back_color', back_color);
                $(this).attr('data-background', background);
            });

            $('a').on('touchend', function(e) { // overwrite with original style..
                var background = $(this).attr('data-background');
                var back_color = $(this).attr('data-back_color');
                if (back_color != undefined) {
                    $(this).css({'background-color': back_color});
                }
                if (background != undefined) {
                    $(this).css({'background': background});
                }
            }).on('touchstart', function(e) { // clear added stlye="" elements..
                $(this).css({'background': '', 'background-color': ''});
            });
}

css:

a {
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

What characters are allowed in an email address?

Gmail will only allow + sign as special character and in some cases (.) but any other special characters are not allowed at Gmail. RFC's says that you can use special characters but you should avoid sending mail to Gmail with special characters.

CSS: Fix row height

HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.

Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp

.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

A simple way to enable polymorphic serialization / deserialization via Jackson library is to globally configure the Jackson object mapper (jackson.databind.ObjectMapper) to add information, such as the concrete class type, for certain kinds of classes, such as abstract classes.

To do that, just make sure your mapper is configured correctly. For example:

Option 1: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes)

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 

Option 2: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes), and arrays of those types.

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS); 

Reference: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Where Is Machine.Config?

In your asp.net app use this

using System.Configuration;
Response.Write(ConfigurationManager.OpenMachineConfiguration().FilePath);

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

Change status bar color with AppCompat ActionBarActivity

[Kotlin version] I created this extension that also checks if the desired color has enough contrast to hide the System UI, like Battery Status Icon, Clock, etc, so we set the System UI white or black according to this.

fun Activity.coloredStatusBarMode(@ColorInt color: Int = Color.WHITE, lightSystemUI: Boolean? = null) {
    var flags: Int = window.decorView.systemUiVisibility // get current flags
    var systemLightUIFlag = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    var setSystemUILight = lightSystemUI

    if (setSystemUILight == null) {
        // Automatically check if the desired status bar is dark or light
        setSystemUILight = ColorUtils.calculateLuminance(color) < 0.5
    }

    flags = if (setSystemUILight) {
        // Set System UI Light (Battery Status Icon, Clock, etc)
        removeFlag(flags, systemLightUIFlag)
    } else {
        // Set System UI Dark (Battery Status Icon, Clock, etc)
        addFlag(flags, systemLightUIFlag)
    }

    window.decorView.systemUiVisibility = flags
    window.statusBarColor = color
}

private fun containsFlag(flags: Int, flagToCheck: Int) = (flags and flagToCheck) != 0

private fun addFlag(flags: Int, flagToAdd: Int): Int {
    return if (!containsFlag(flags, flagToAdd)) {
        flags or flagToAdd
    } else {
        flags
    }
}

private fun removeFlag(flags: Int, flagToRemove: Int): Int {
    return if (containsFlag(flags, flagToRemove)) {
        flags and flagToRemove.inv()
    } else {
        flags
    }
}

How to use sed to remove all double quotes within a file

For replacing in place you can also do:

sed -i '' 's/\"//g' file.txt

or in Linux

sed -i 's/\"//g' file.txt

adb shell su works but adb root does not

You need to replace the adbd binary in the boot.img/sbin/ folder to one that is su capable. You will also have to make some default.prop edits too.

Samsung seems to make this more difficult than other vendors. I have some adbd binaries you can try but it will require the knowledge of de-compiling and re-compiling the boot.img with the new binary. Also, if you have a locked bootloader... this is not gonna happen.

Also Chainfire has an app that will grant adbd root permission in the play store: https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Lastly, if you are trying to write a windows script with SU permissions you can do this buy using the following command style... However, you will at least need to grant (on the phone) SU permissions the frist time its ran...

adb shell "su -c ls" <-list working directory with su rights. adb shell "su -c echo anytext > /data/test.file"

These are just some examples. If you state specifically what you are trying to accomplish I may be able to give more specific advice

-scosler

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

How do I change selected value of select2 dropdown with JqGrid?

This should be even easier.

$("#e1").select2("val", ["View" ,"Modify"]);

But make sure the values which you pass are already present in the HTMl

How to include a class in PHP

Include a class example with the use keyword from Command Line Interface:

PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.

  1. Create a new directory /home/el/bin

  2. Make a new file called namespace_example.php and put this code in there:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. Make another file called mylib.php and put this code in there:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. Run it from commandline like this:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. Which prints:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    

See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php

What is difference between png8 and png24

There is only one PNG format, but it supports 5 color types.

PNG-8 refers to palette variant, which supports only 256 colors, but is usually smaller in size. PNG-8 can be a GIF substitute.

PNG-24 refers to true color variant, which supports more colors, but might be bigger. PNG-24 can be used instead of JPEG, if lossless image format is needed.

Any modern web browser will support both variants.

How to convert from int to string in objective c: example code

You can use literals, it's more compact.

NSString* myString = [@(17) stringValue];

(Boxes as a NSNumber and uses its stringValue method)

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

What is the difference between MVC and MVVM?

I made a Medium article for this.

MVVM

  1. View ? ViewModel ? Model

    • The view has a reference to the ViewModel but not vice versa.
    • The ViewModel has a reference to the Model but not vice versa.
    • The View has no reference to the Model and vice versa.
  2. If you are using a controller, it can have a reference to Views and ViewModels, though a Controller is not always necessary as demonstrated in SwiftUI.

  3. Data Binding: we create listeners for ViewModel Properties.
class CustomView: UIView {
  var viewModel = MyViewModel {
    didSet {
      self.color = viewModel.color
    }
  }

  convenience init(viewModel: MyViewModel) {
    self.viewModel = viewModel
  }
}


struct MyViewModel {
   var viewColor: UIColor {
      didSet {
         colorChanged?() // This is where the binding magic happens.
      }
   }

   var colorChanged: ((UIColor) -> Void)?
}


class MyViewController: UIViewController {

   let myViewModel = MyViewModel(viewColor: .green)
   let customView: CustomView!

   override func viewDidLoad() {
      super.viewDidLoad()

      // This is where the binder is assigned.
      myViewModel.colorChanged = { [weak self] color in 
        print("wow the color changed")
      }
      customView = CustomView(viewModel: myViewModel)
      self.view = customView
   }
}

differences in setup

  1. Business logic is held in the controller for MVC and the ViewModels for MVVM.
  2. Events are passed directly from the View to the controller in MVC while events are passed from the View to the ViewModel to the Controller (if there is one) for MVVM.

Common features

  1. Both MVVM and MVC do not allow the View to send messages directly to the Model/s.
  2. Both have models.
  3. Both have views.

Advantages of MVVM

  1. Because the ViewModels hold business logic, they are smaller concrete objects making them easy to unit tests. On the other hand, in MVC, the business logic is in the ViewController. How can you trust that a unit test of a view controller is comprehensively safe without testing all the methods and listeners simultaneously? You can't wholly trust the unit test results.
  2. In MVVM, because business logic is siphoned out of the Controller into atomic ViewModel units, the size of the ViewController shrinks and this makes the ViewController code more legible.

Advantages of MVC

  1. Providing business logic within the controller reduces the need for branching and therefore statements are more likely to run on the cache which is more performant over encapsulating business logic into ViewModels.
  2. Providing business logic in one place can accelerate the development process for simple applications, where tests are not required. I don't know when tests are not required.
  3. Providing business logic in the ViewController is easier to think about for new developers.

How to use basic authorization in PHP curl

$headers = array(
    'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

Make an image responsive - the simplest way

Images should be set like this

img { max-width: 100%; }

Angularjs autocomplete from $http

You need to write a controller with ng-change function in scope. In ng-change callback you do a call to server and update completions. Here is a stub (without $http as this is a plunk):

HTML

<!doctype html>
<html ng-app="plunker">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
        <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.4.0.js"></script>
        <script src="example.js"></script>
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
    </head>
    <body>
        <div class='container-fluid' ng-controller="TypeaheadCtrl">
            <pre>Model: {{selected| json}}</pre>
            <pre>{{states}}</pre>
            <input type="text" ng-change="onedit()" ng-model="selected" typeahead="state for state in states | filter:$viewValue">
        </div>
    </body>
</html>

JS

angular.module('plunker', ['ui.bootstrap']);

function TypeaheadCtrl($scope) {
  $scope.selected = undefined;
  $scope.states = [];

  $scope.onedit = function(){
    $scope.states = [];

    for(var i = 0; i < Math.floor((Math.random()*10)+1); i++){
      var value = "";

      for(var j = 0; j < i; j++){
        value += j;
      }
      $scope.states.push(value);
    }
  }
}

Does Android support near real time push notification?

If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).

If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.

You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.

includes() not working in all browsers

IE11 does implement String.prototype.includes so why not using the official Polyfill?

Source: polyfill source

  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      if (typeof start !== 'number') {
        start = 0;
      }

      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }