Programs & Examples On #Mappoint

Microsoft MapPoint is both a technology ("MapPoint Web Service," previously known as MapPoint .NET) and a specific software program created by Microsoft that allows users to view, edit and integrate maps.

No Title Bar Android Theme

if you want the original style of your Ui to remain and the title bar to be removed with no effect on that, you have to remove the title bar in your activity rather than the manifest. leave the original theme style that you had in the manifest and in each activity that you want no title bar use this.requestWindowFeature(Window.FEATURE_NO_TITLE); in the oncreate() method before setcontentview() like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_signup);
    ...
}

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Image style height and width not taken in outlook mails

The px needs to be left off, for some odd reason.

Automatically enter SSH password with script

This is how I login to my servers.

ssp <server_ip>
  • alias ssp='/home/myuser/Documents/ssh_script.sh'
  • cat /home/myuser/Documents/ssh_script.sh

#!/bin/bash

sshpass -p mypassword ssh root@$1

And therefore...

ssp server_ip

How can you get the build/version number of your Android application?

As I had to get only the version code and check whether app was updated or not, if yes, I had to launch the playstore to get updated one. I did it this way.

public class CheckForUpdate {

    public static final String ACTION_APP_VERSION_CHECK = "app-version-check";

    public static void launchPlayStoreApp(Context context)
    {
        // getPackageName() from Context or Activity object
        final String appPackageName = context.getPackageName();
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("market://details?id=" + appPackageName)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("https://play.google.com/store/apps/details?id=" +
                                             appPackageName)));
        }
    }

    public static int getRemoteVersionNumber(Context context)
    {
        int versionCode = 0;
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String version = pInfo.versionName;
            versionCode = pInfo.versionCode;
        }
        catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

}

Then I saved version code using shared preference by creating an util class.

public class PreferenceUtils {

    // This is for version code
    private  final String APP_VERSION_CODE = "APP_VERSION_CODE";
    private  SharedPreferences sharedPreferencesAppVersionCode;
    private SharedPreferences.Editor editorAppVersionCode;
    private static Context mContext;

    public PreferenceUtils(Context context)
    {
        this.mContext = context;
        // This is for the app versioncode
        sharedPreferencesAppVersionCode = mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
        editorAppVersionCode = sharedPreferencesAppVersionCode.edit();
    }

    public void createAppVersionCode(int versionCode) {

        editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
        editorAppVersionCode.apply();
    }

    public int getAppVersionCode()
    {
        return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // As the default version code is 0
    }
}

How to convert a String to CharSequence?

Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

Problems with a PHP shell script: "Could not open input file"

When you use php CLI argument -q doesn't exist.

I had the same problem when I wrote script in the Windows (eclipse) and I tried run them on Linux. Every line in file from Windows is ended by \r\n. I had to delete \r in first line that contained parser path:

When \r was deleted from first line (mcedit shown \r as ^M) script ran correctly.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

If you are getting this issue with opencart try editing

catalog/controller/extension/feed/google_sitemap.php For More info and How to do it refer this: xmlparseentityref-no-name-error

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

How to parse a month name (string) to an integer for comparison in C#?

One simply solution would be create a Dictionary with names and values. Then using Contains() you can find the right value.

Dictionary<string, string> months = new Dictionary<string, string>()
{
                { "january", "01"},
                { "february", "02"},
                { "march", "03"},
                { "april", "04"},
                { "may", "05"},
                { "june", "06"},
                { "july", "07"},
                { "august", "08"},
                { "september", "09"},
                { "october", "10"},
                { "november", "11"},
                { "december", "12"},
};
foreach (var month in months)
{
    if (StringThatContainsMonth.ToLower().Contains(month.Key))
    {
        string thisMonth = month.Value;
    }
}

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

What is difference between INNER join and OUTER join

This is the best and simplest way to understand joins:

enter image description here

Credits go to the writer of this article HERE

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Console logging for react?

If you're just after console logging here's what I'd do:

export default class App extends Component {
  componentDidMount() {
    console.log('I was triggered during componentDidMount')
  }

  render() {
    console.log('I was triggered during render')
    return ( 
      <div> I am the App component </div>
    )
  }
}

Shouldn't be any need for those packages just to do console logging.

Android/Eclipse: how can I add an image in the res/drawable folder?

Just copy the image and paste into Eclipse in the res/drawable directory. Note that the image name should be in lowercase, otherwise it will end up with an error.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

This is absolutely doable with some flexbox magic. Have a look at this pen.

You need css like this:

aside {
  background-color: cyan;
  position: fixed;
  max-height: 100vh;
  width: 25%;
  display: flex;
  flex-direction: column;
}

ul {
  overflow-y: scroll;
}

section {
  width: 75%;
  float: right;
  background: orange;
}

This will work in IE10+

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset the selected options

$('select option:selected').removeAttr('selected');

If you actually want to remove the options (although I don't think you mean this).

$('select').empty();

Substitute select for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select> elements on the page

Open local folder from link

you can use

<a href="\\computername\folder">Open folder</a>

in Internet Explorer

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Solving this problem is very easy:

  1. Go to control panel.
  2. search for services.
  3. Open Local services window from your search results
  4. Restart your MSSQLSERVER service.

Screenshot of the steps:

Screenshot of the steps

ValueError: could not convert string to float: id

I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It's pretty simple

data=pd.read_excel('link to the file')

Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.

 data = data.set_index("ID")

Then delete all the rows with "id" as the value instead of number using following command.

  data = data.drop("id", axis=0). 

Hope, this will help you.

Python functions call by reference

You can not change an immutable object, like str or tuple, inside a function in Python, but you can do things like:

def foo(y):
  y[0] = y[0]**2

x = [5]
foo(x)
print x[0]  # prints 25

That is a weird way to go about it, however, unless you need to always square certain elements in an array.

Note that in Python, you can also return more than one value, making some of the use cases for pass by reference less important:

def foo(x, y):
   return x**2, y**2

a = 2
b = 3
a, b = foo(a, b)  # a == 4; b == 9

When you return values like that, they are being returned as a Tuple which is in turn unpacked.

edit: Another way to think about this is that, while you can't explicitly pass variables by reference in Python, you can modify the properties of objects that were passed in. In my example (and others) you can modify members of the list that was passed in. You would not, however, be able to reassign the passed in variable entirely. For instance, see the following two pieces of code look like they might do something similar, but end up with different results:

def clear_a(x):
  x = []

def clear_b(x):
  while x: x.pop()

z = [1,2,3]
clear_a(z) # z will not be changed
clear_b(z) # z will be emptied

How to disable clicking inside div

If using function onclick DIV and then want to disable click it again you can use this :

for (var i=0;i<document.getElementsByClassName('ads').length;i++){
    document.getElementsByClassName('ads')[i].onclick = false;
}

Example :
HTML

<div id='mybutton'>Click Me</div>

Javascript

document.getElementById('mybutton').onclick = function () {
    alert('You clicked');
    this.onclick = false;
}

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

Redirecting Output from within Batch file

Add these two lines near the top of your batch file, all stdout and stderr after will be redirected to log.txt:

if not "%1"=="STDOUT_TO_FILE"  %0 STDOUT_TO_FILE %*  >log.txt 2>&1
shift /1

Property 'map' does not exist on type 'Observable<Response>'

just install rxjs-compat by typing in terminal:

npm install --save rxjs-compat

then import :

import 'rxjs/Rx';

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

Date format in the json output using spring boot

You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.

You should do two things

  • add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here

Getting multiple selected checkbox values in a string in javascript and PHP

var fav = [];
$.each($("input[name='name']:checked"), function(){            
    fav.push($(this).val());
});

It will give you the value separeted by commas

Cannot open backup device. Operating System error 5

Yeah I just scored this one.

Look in Windows Services. Start > Administration > Services

Find the Service in the list called: SQL Server (MSSQLSERVER) look for the "Log On As" column (need to add it if it doesn't exist in the list).

This is the account you need to give permissions to the directory, right click in explorer > properties > Shares (And Security)

NOTE: Remember to give permissions to the actual directory AND to the share if you are going across the network.

Apply and wait for the permissions to propogate, try the backup again.

NOTE 2: if you are backing up across the network and your SQL is running as "Local Service" then you are in trouble ... you can try assigning permissions or it may be easier to backup locally and xcopy across outside of SQL Server (an hour later).

NOTE 3: If you're running as network service then SOMETIMES the remote machine will not recognize the network serivce on your SQL Server. If this is the case you need to add permissions for the actual computer itself eg. MyServer$.

How to handle windows file upload using Selenium WebDriver?

Import System.Windows.Forms binary to the test solution and call the following two LOC on clicking the Upload button on the UI.

        // Send the file path and enter file path and wait.
        System.Windows.Forms.SendKeys.SendWait("complete path of the file");
        System.Windows.Forms.SendKeys.SendWait("{ENTER}");

Call removeView() on the child's parent first

Kotlin Solution

Kotlin simplifies parent casting with as?, returning null if left side is null or cast fails.

(childView.parent as? ViewGroup)?.removeView(childView)

Kotlin Extension Solution

If you want to simplify this even further, you can add this extension.

childView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parentView = parent as? ViewGroup ?: return
    parentView.removeView(this)
}

It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup

NOTE: If you also want safe removal of child views by parent, add this:

fun ViewGroup.removeViewSafe(toRemove: View) {
    if (contains(toRemove)) removeView(toRemove)
}

How to drop a database with Mongoose?

Mongoose 4.6.0+:

mongoose.connect('mongodb://localhost/mydb')
mongoose.connection.once('connected', () => {
    mongoose.connection.db.dropDatabase();
});

Passing a callback to connect won't work anymore:

TypeError: Cannot read property 'commandsTakeWriteConcern' of null

How to get a table creation script in MySQL Workbench?

It is located in server administration rather than in SQL development.

  • From the home screen select the database server instance your database is located on from the server administration section on the far right.
  • From the menu on the right select Data Export.
  • Select the database you want to export and choose a location.
  • Click start export.

How do I check if a directory exists? "is_dir", "file_exists" or both?

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

How to change UIButton image in Swift

in swift 3.0:

@IBOutlet weak var selectionButton: UIButton!

selectionButton.setImage(UIImage.addBlueIcon, for: .selected)

Is there a way to use shell_exec without waiting for the command to complete?

You can also give your output back to the client instantly and continue processing your PHP code afterwards.

This is the method I am using for long-waiting Ajax calls which would not have any effect on client side:

ob_end_clean();
ignore_user_abort();
ob_start();
header("Connection: close");
echo json_encode($out);
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
// execute your command here. client will not wait for response, it already has one above.

You can find the detailed explanation here: http://oytun.co/response-now-process-later

PHP: check if any posted vars are empty - form: all fields required

foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

WPF Datagrid set selected row

You don't need to iterate through the DataGrid rows, you can achieve your goal with a more simple solution. In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource property then assign this item to you DataGrid.SelectedItem property programmatically, alternatively you can add it to your DataGrid.SelectedItems collection if you want to allow the user to select more than one row. See the code below:

<Window x:Class="ProgGridSelection.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
    <DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
    <TextBox Name="empNameTextBox"/>
    <Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>

public partial class MainWindow : Window
{
    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

    private ObservableCollection<Employee> _empCollection;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void OnWindowLoaded(object sender, RoutedEventArgs e)
    {
        // Generate test data
        _empCollection =
            new ObservableCollection<Employee>
                {
                    new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
                    new Employee {Code = "E013", Name = "Ahmed Yousif"},
                    new Employee {Code = "E431", Name = "Jasmin Kamal"},
                };

        /* Set the Window.DataContext, alternatively you can set your
         * DataGrid DataContext property to the employees collection.
         * on the other hand, you you have to bind your DataGrid
         * DataContext property to the DataContext (see the XAML code)
         */
        DataContext = _empCollection;
    }

    private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
    {
        /* select the employee that his name matches the
         * name on the TextBox
         */
        var emp = (from i in _empCollection
                   where i.Name == empNameTextBox.Text.Trim()
                   select i).FirstOrDefault();

        /* Now, to set the selected item on the DataGrid you just need
         * assign the matched employee to your DataGrid SeletedItem
         * property, alternatively you can add it to your DataGrid
         * SelectedItems collection if you want to allow the user
         * to select more than one row, e.g.:
         *    empDataGrid.SelectedItems.Add(emp);
         */
        if (emp != null)
            empDataGrid.SelectedItem = emp;
    }
}

Loading an image to a <img> from <input file>

ES2017 Way

_x000D_
_x000D_
// convert file to a base64 url
const readURL = file => {
    return new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = e => res(e.target.result);
        reader.onerror = e => rej(e);
        reader.readAsDataURL(file);
    });
};

// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);

const preview = async event => {
    const file = event.target.files[0];
    const url = await readURL(file);
    img.src = url;
};

fileInput.addEventListener('change', preview);
_x000D_
_x000D_
_x000D_

Setting the default page for ASP.NET (Visual Studio) server configuration

This One Method For Published Solution To Show SpeciFic Page on startup.

Here Is the Route Example to Redirect to Specific Page...

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "YourSolutionName.Controllers" }
        );
    }
}

By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.

Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..

Create component to specific module with Angular-CLI

If you have multiple apps declared in .angular-cli.json ( e.g. in case working on feature module)

"apps": [{
    "name": "app-name",
    "root": "lib",
    "appRoot": ""
}, {...} ]

You can :

ng g c my-comp -a app-name

-a stands for --app (name)

Add string in a certain position in Python

Simple function to accomplish this:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

Change the maximum upload file size

many times i have noticed that site wit shared hosting do not allow to change settings in php.ini files. one also can not even crate .htaaccess file at all. in such situation one can try following things

ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use

[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }

as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:

{
  "Items": [
    {
      "$type": "Namespace.ClassA, Assembly",
      "Property": "Value"
    },
    {
      "$type": "Namespace.ClassB, Assembly",
      "Property": "Value",
      "Additional_ClassB_Property": 3
    }
  ]
}

Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.

How to convert an array into an object using stdClass()

To convert array to object using stdClass just add (object) to array u declare.

EX:

echo $array['value'];
echo $object->value;

to convert object to array

$obj = (object)$array;

to convert array to object

$arr = (array)$object

with these methods you can swap between array and object very easily.


Another method is to use json

$object = json_decode(json_encode($array), FALSE);

But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

Show/Hide Table Rows using Javascript classes

event.preventDefault()

Doesn't work in all browsers. Instead you could return false in OnClick event.

onClick="toggle_it('tr1');toggle_it('tr2'); return false;">

Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.

Build the full path filename in Python

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

How can I take a screenshot/image of a website using Python?

I can't comment on ars's answer, but I actually got Roland Tapken's code running using QtWebkit and it works quite well.

Just wanted to confirm that what Roland posts on his blog works great on Ubuntu. Our production version ended up not using any of what he wrote but we are using the PyQt/QtWebKit bindings with much success.

Note: The URL used to be: http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/ I've updated it with a working copy.

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

Create JSON object dynamically via JavaScript (Without concate strings)

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

How to export iTerm2 Profiles

Preferences -> General -> Load preferences from a custom folder or URL

First time you choose this, it will automatically save a preferences file into this folder called "com.googlecode.iterm2.plist"

How do I format date and time on ssrs report?

In SSRS 2016 There is an option under the properties header "Localization" called "Calendar", if you click on this it gives you these 2 options:

  • Gregorian (dd/mm/yyyy)
  • GregorianUSEnglish (MM/dd/yyyy)

This works brilliantly when referencing data from a tables aswell

alternatively if this does not work for you, specify one of these formats under "Number" and in the cell "Format":

dd/MM/yyyy or MM/dd/yyyy

printscreen

Getting started with Haskell

Don't try to read all the monad tutorials with funny metaphors. They will just get you mixed up even worse.

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

How to create a DataTable in C# and how to add rows?

The easiest way is to create a DtaTable as of now

DataTable table = new DataTable
{
    Columns = {
        "Name", // typeof(string) is implied
        {"Marks", typeof(int)}
    },
    TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);

Blurry text after using CSS transform: scale(); in Chrome

My solution was:

display: initial;

Then it was crispy sharp

Find Facebook user (url to profile page) by known email address

Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain.. A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..

in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.

"sed" command in bash

Here sed is replacing all occurrences of % with $ in its standard input.

As an example

$ echo 'foo%bar%' | sed -e 's,%,$,g'

will produce "foo$bar$".

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

How to getElementByClass instead of GetElementById with JavaScript?

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>

How to stretch the background image to fill a div

You can use:

background-size: cover;

Or just use a big background image with:

background: url('../images/teaser.jpg') no-repeat center #eee;

Split output of command by columns using Bash?

Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:

command|head -n 6|tail -n 1|awk '{print $4}'

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

Add key value pair to all objects in array

Simply you can add that way. see below the console image

enter image description here

How can I show and hide elements based on selected option with jQuery?

You are missing a :selected on the selector for show() - see the jQuery documentation for an example of how to use this.

In your case it will probably look something like this:

$('#'+$('#colorselector option:selected').val()).show();

Assigning multiple styles on an HTML element

The way you have used the HTML syntax is problematic.

This is how the syntax should be

style="property1:value1;property2:value2"

In your case, this will be the way to do

<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>

A further example would be as follows

<div class ="row">
    <button type="button" style= "margin-top : 20px; border-radius: 15px" 
    class="btn btn-primary">View Full Profile</button>
</div>

Change text color with Javascript?

innerHTML is a string representing the contents of the element.

You want to modify the element itself. Drop the .innerHTML part.

grep exclude multiple strings

The greps can be chained. For example:

tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

Remove duplicates in the list using linq

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

When using $_SERVER["REMOTE_ADDR"], I get the server's IP address rather than the visitor's.

Then something is wrong, or odd, with your configuration.

  • Are you using some sort of reverse proxy? In that case, @simshaun's suggestion may work.

  • Do you have anything else out of the ordinary in your web server config?

  • Can you show the PHP code you are using?

  • Can you show what the address looks like. Is it a local one, or a Internet address?

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

Using Python's os.path, how do I go up one directory?

Go up a level from the work directory

import os
os.path.dirname(os.getcwd())

or from the current directory

import os
os.path.dirname('current path')

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

Run AVD Emulator without Android Studio

Open your terminal and

cd path_to/Android/Sdk/emulator

And run the following to get the emulator name that you created before using android studio

./emulator -list-avds

Replace $emulator_name with the one you want to launch and run

./emulator -avd $emulator_name

Getting value GET OR POST variable using JavaScript?

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.

Notes

  • No sanity checking of values
  • Just outputting to the console - you'll want to store them in an array or something
  • this is only for GET, and not POST

    var paramindex = returnURL.indexOf('?');
    if (paramindex > 0) {
        var paramstring = returnURL.split('?')[1];
        while (paramindex > 0) {
            paramindex = paramstring.indexOf('=');
            if (paramindex > 0) {
                var parkey = paramstring.substr(0,paramindex);
                console.log(parkey)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the =
            }
            paramindex = paramstring.indexOf('&');
            if (paramindex > 0) {
                var parvalue = paramstring.substr(0,paramindex);
                console.log(parvalue)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the &
            } else { // we're at the end of the URL
                var parvalue = paramstring
                console.log(parvalue)
                break;
            }
        }
    }
    

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

Is there a function to round a float in C or do I need to write my own?

There is a round() function, also fround(), which will round to the nearest integer expressed as a double. But that is not what you want.

I had the same problem and wrote this:

#include <math.h>

   double db_round(double value, int nsig)
/* ===============
**
** Rounds double <value> to <nsig> significant figures.  Always rounds
** away from zero, so -2.6 to 1 sig fig will become -3.0.
**
** <nsig> should be in the range 1 - 15
*/

{
    double     a, b;
    long long  i;
    int        neg = 0;


    if(!value) return value;

    if(value < 0.0)
    {
        value = -value;
        neg = 1;
    }

    i = nsig - log10(value);

    if(i) a = pow(10.0, (double)i);
    else  a = 1.0;

    b = value * a;
    i = b + 0.5;
    value = i / a;

    return neg ? -value : value;
} 

Android Drawing Separator/Divider Line in Layout?

This would help you to resolve this problem. Here a small view is created to make a black line as a separator between two views.

 <View
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
         />

Get counts of all tables in a schema

Get counts of all tables in a schema and order by desc

select 'with tmp(table_name, row_number) as (' from dual 
union all 
select 'select '''||table_name||''',count(*) from '||table_name||' union  ' from USER_TABLES 
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;

Copy the entire result and execute

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


Update:

This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

How to edit incorrect commit message in Mercurial?

Good news: hg 2.2 just added git like --amend option.

and in tortoiseHg, you can use "Amend current revision" by select black arrow on the right of commit button

a

How to run a SQL query on an Excel table?

If you need to do this once just follow Charles' descriptions, but it is also possible to do this with Excel formulas and helper columns in case you want to make the filter dynamic.

Lets assume you data is on the sheet DataSheet and starts in row 2 of the following columns:

  • A: lastname
  • B: firstname
  • C: phonenumber

You need two helper columns on this sheet.

  • D2: =if(A2 = "", 1, 0), this is the filter column, corresponding to your where condition
  • E2: =if(D2 <> 1, "", sumifs(D$2:D$1048576, A$2:A$1048576, "<"&A2) + sumifs(D$2:D2, A$2:A2, A2)), this corresponds to the order by

Copy down these formulas as far as your data goes.

On the sheet which should display your result create the following columns.

  • A: A sequence of numbers starting with 1 in row 2, this limits the total number of rows you can get (kind like a limit in sequel)
  • B2: =match(A2, DataSheet!$E$2:$E$1048576, 0), this is the row of the corresponding data
  • C2: =iferror(index(DataSheet!A$2:A$1048576, $B2), ""), this is the actual data or empty if no data exists

Copy down the formulas in B2 and C2 and copy-past column C to D and E.

How do I select an element with its name attribute in jQuery?

it's very simple getting a name:

$('[name=elementname]');

Resource:

http://www.electrictoolbox.com/jquery-form-elements-by-name/ (google search: get element by name jQuery - first result)

Delaying a jquery script until everything else has loaded

This code block solve my problem,

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(window).bind("load", function () {_x000D_
    // Code here_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

Mergesort with Python

As already said, l.pop(0) is a O(len(l)) operation and must be avoided, the above msort function is O(n**2). If efficiency matter, indexing is better but have cost too. The for x in l is faster but not easy to implement for mergesort : iter can be used instead here. Finally, checking i < len(l) is made twice because tested again when accessing the element : the exception mechanism (try except) is better and give a last improvement of 30% .

def msort(l):
    if len(l)>1:
        t=len(l)//2
        it1=iter(msort(l[:t]));x1=next(it1)
        it2=iter(msort(l[t:]));x2=next(it2)
        l=[]
        try:
            while True:
                if x1<=x2: l.append(x1);x1=next(it1)
                else     : l.append(x2);x2=next(it2)
        except:
            if x1<=x2: l.append(x2);l.extend(it2)
            else:      l.append(x1);l.extend(it1)
    return l

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

How to colorize diff on the command line?

Here is another solution that invokes sed to insert the appropriate ANSI escape sequences for colors to show the +, -, and @ lines in red, green, and cyan, respectively.

diff -u old new | sed "s/^-/$(tput setaf 1)&/; s/^+/$(tput setaf 2)&/; s/^@/$(tput setaf 6)&/; s/$/$(tput sgr0)/"

Unlike the other solutions to this question, this solution does not spell out the ANSI escape sequences explicitly. Instead, it invokes the tput setaf and tput sgr0 commands to generate the ANSI escape sequences to set an appropriate color and reset terminal attributes, respectively.

To see the available colors for each argument to tput setaf, use this command:

for i in {0..255}; do tput setaf $i; printf %4d $i; done; tput sgr0; echo

Here is how the output looks:

enter image description here

Here is the evidence that the tput setaf and tput sgr0 commands generate the appropriate ANSI escape sequences:

$ tput setaf 1 | xxd -g1
00000000: 1b 5b 33 31 6d                                   .[31m
$ tput setaf 2 | xxd -g1
00000000: 1b 5b 33 32 6d                                   .[32m
$ tput setaf 6 | xxd -g1
00000000: 1b 5b 33 36 6d                                   .[36m
$ tput sgr0 | xxd -g1
00000000: 1b 28 42 1b 5b 6d                                .(B.[m

How to override toString() properly in Java?

Always have easy way: Right Click > Generate > toString() > select template that you want. enter image description here

How to update the value stored in Dictionary in C#?

Use LINQ: Access to dictionary for the key and change the value

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

Any tools to generate an XSD schema from an XML instance document?

Altova XmlSpy does this well - you can find an overview here

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I just had this problem. This is what worked for me:

pip install botocore==1.13.20

Source: https://github.com/boto/botocore/issues/1892

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

How to preSelect an html dropdown list with php?

Programmers are lazy...er....efficient....I'd do it like so:

<select><?php
    $the_key = 1; // or whatever you want
    foreach(array(
        1 => 'Yes',
        2 => 'No',
        3 => 'Fine',
    ) as $key => $val){
        ?><option value="<?php echo $key; ?>"<?php
            if($key==$the_key)echo ' selected="selected"';
        ?>><?php echo $val; ?></option><?php
    }
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

How can I get the name of an object in Python?

Here is my answer, I am also using globals().items()

    def get_name_of_obj(obj, except_word = ""):

        for name, item in globals().items():
            if item == obj and name != except_word:
                return name

I added except_word because I want to filter off some word used in for loop. If you didn't add it, the keyword in for loop may confuse this function, sometimes the keyword like "each_item" in the following case may show in the function's result, depends on what you have done to your loop.

eg.

    for each_item in [objA, objB, objC]:
        get_name_of_obj(obj, "each_item")

eg.

    >>> objA = [1, 2, 3]
    >>> objB = ('a', {'b':'thi is B'}, 'c')
    >>> for each_item in [objA, objB]:
    ...     get_name_of_obj(each_item)
    ...
    'objA'
    'objB'
    >>>
    >>>
    >>> for each_item in [objA, objB]:
    ...     get_name_of_obj(each_item)
    ...
    'objA'
    'objB'
    >>>
    >>>
    >>> objC = [{'a1':'a2'}]
    >>>
    >>> for item in [objA, objB, objC]:
    ...     get_name_of_obj(item)
    ...
    'objA'
    'item'  <<<<<<<<<< --------- this is no good
    'item'
    >>> for item in [objA, objB]:
    ...     get_name_of_obj(item)
    ...
    'objA'
    'item'     <<<<<<<<--------this is no good
    >>>
    >>> for item in [objA, objB, objC]:
    ...     get_name_of_obj(item, "item")
    ...
    'objA'
    'objB'  <<<<<<<<<<--------- now it's ok
    'objC'
    >>>

Hope this can help.

Count all values in a matrix greater than a value

To count the number of values larger than x in any numpy array you can use:

n = len(matrix[matrix > x])

The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.

ionic build Android | error: No installed build tools found. Please install the Android build tools

This is very irritating error and i wasted my almost 9 hours to solve this.

Steps to solve:

Notice **ANDROID_HOME** while you run **ionic cordova build android** . command i. for example in my case it was pointing to some other android sdk which i uninstalled and then it started pointing to right sdk.
**In my case i uninstalled :**

brew cask uninstall android-sdk
brew cask uninstall android-platform-tool


then i ran **ionic cordova build android**

> cordova build android
ANDROID_HOME=/Users/anand/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home


Then it might say lineces not accepted then run below command :

cd /Users/Android/sdk/tools/bin/
then run ./sdkmanager --licenses
accepts all with y option


Then it might say unable to download jars then go to platform android and build.gradle

and search for buildscript and inside that reverse the order 


repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }

Thats it . Enjoy huh

java.lang.IllegalArgumentException: View not attached to window manager

i agree a opinion of 'Damjan'.
if you use many dialogs, should close all dialog in onDestroy() or onStop().
then you may be able to reduce the frequency 'java.lang.IllegalArgumentException: View not attached to window manager' exception occurs.

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mDialog.dismiss();
    super.onDestroy();
}



but little exceed...
to make it more clear, you prevent to show any dialog after onDestroy called.
i don't use as below. but it's clear.

private boolean mIsDestroyed = false;

private void showDialog() {
    closeDialog();

    if (mIsDestroyed) {
        Log.d(TAG, "called onDestroy() already.");
        return;
    }

    mDialog = new AlertDialog(this)
        .setTitle("title")
        .setMessage("This is DialogTest")
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
        .create();
    mDialog.show();
}

private void closeDialog() {
    if (mDialog != null) {
        mDialog.dismiss();
    }
}

@Override
protected void onDestroy() {
    Log.d(TAG, "called onDestroy");
    mIsDestroyed = true;
    closeDialog();
    super.onDestroy();
}


good luck!

How do I do an OR filter in a Django query?

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

Add a new line to a text file in MS-DOS

echo Hello, > file.txt
echo.       >>file.txt
echo world  >>file.txt

and you can always run:

wordpad file.txt

on any version of Windows.


On Windows 2000 and above you can do:

( echo Hello, & echo. & echo world ) > file.txt

Another way of showing a message for a small amount of text is to create file.vbs containing:

Msgbox "Hello," & vbCrLf & vbCrLf & "world", 0, "Message"

Call it with

cscript /nologo file.vbs

Or use wscript if you don't need it to wait until they click OK.


The problem with the message you're writing is that the vertical bar (|) is the "pipe" operator. You'll need to escape it by using ^| instead of |.

P.S. it's spelled Pwned.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

For me, I missed this statement in @Component decorator: animations: [yourAnimation]

Once I added this statement, errors gone. (Angular 6.x)

Python: Find in list

Another alternative: you can check if an item is in a list with if item in list:, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

Not going to be the correct solution in every case, but for some cases this might give you better performance.

Note that creating the set with set(my_list) is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.

printf formatting (%d versus %u)

%u prints unsigned integer

%d prints signed integer

to get a pointer address use %p

Other List of Formatting Escapes:

Here are the full list of formatting escapes. I am just giving a screen shot from this page

enter image description here

Python function pointer

eval(compile(myvar,'<str>','eval'))(myargs)

compile(...,'eval') allows only a single statement, so that there can't be arbitrary commands after a call, or there will be a SyntaxError. Then a tiny bit of validation can at least constrain the expression to something in your power, like testing for 'mypackage' to start.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Reasons I've encountered this error:

  1. Did not use .AsNoTracking() when querying for existing entities. Especially when calling a helper function to check permissions.
  2. Calling .Include() on a query and then trying to edit the parent. Example: var ent = repo.Query<Ent>().Include(e=>e.Ent2).First(); ...repo.Edit(e.Ent2); repo.Edit(e); If I'm going to edit a nested object, I try to separate these into separate query calls now. If you can't do that, set the child object to null and iterate through lists, detaching objects like this
  3. Editing an old entity in a Put web call. The new item is already added to the repo, so modify that one and have it be saved in super.Put(). Example of what will throw an error: public void Put(key, newItem){ var old = repo.Query<Entity>().Where(e=>Id==key).First(); ... repo.Edit(old); super.Put(key,newItem); ... }
  4. Multiple helper functions edit the same entity. Instead of passing the ID as a parameter into each function, pass a reference to the entity. Error solved!

How Do I Uninstall Yarn

If you are still getting errors after deleting ~/.yarn about files not being found, don't forget to delete the yarn rc file:

rm ~/.yarnrc.yml 

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

How to get method parameter names?

In python 3, below is to make *args and **kwargs into a dict (use OrderedDict for python < 3.6 to maintain dict orders):

from functools import wraps

def display_param(func):
    @wraps(func)
    def wrapper(*args, **kwargs):

        param = inspect.signature(func).parameters
        all_param = {
            k: args[n] if n < len(args) else v.default
            for n, (k, v) in enumerate(param.items()) if k != 'kwargs'
        }
        all_param .update(kwargs)
        print(all_param)

        return func(**all_param)
    return wrapper

Determine .NET Framework version for dll

Expanding on the answers here, this can blow up if there is a dependent assembly. If you're lucky and you know where the dependent is (or even luckier, it's in the GAC) then this may help ...

using System.Reflection;
using System.Runtime.Versioning;
// ...
{
    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);
    var asm = System.Reflection.Assembly.LoadFrom(@"C:\Codez\My.dll");
    var targetFrameAttribute = asm.GetCustomAttributes(true).OfType<TargetFrameworkAttribute>().FirstOrDefault();
    targetFrameAttribute.Dump();
}

Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    var name = args.Name;

    if (name.StartsWith("Depends"))
        return System.Reflection.Assembly.ReflectionOnlyLoadFrom(@"C:\Codez\Depends.dll");

    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

Reference: https://weblog.west-wind.com/posts/2006/Dec/22/Reflection-on-Problem-Assemblies

Accessing Session Using ASP.NET Web API

Following on from LachlanB's answer, if your ApiController doesn't sit within a particular directory (like /api) you can instead test the request using RouteTable.Routes.GetRouteData, for example:

protected void Application_PostAuthorizeRequest()
    {
        // WebApi SessionState
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
        if (routeData != null && routeData.RouteHandler is HttpControllerRouteHandler)
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    }

Play/pause HTML 5 video using JQuery

use this.. $('#video1').attr({'autoplay':'true'});

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

How do I run a bat file in the background from another bat file?

Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.

DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)

name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)

Array initializing in Scala

Another way of declaring multi-dimentional arrays:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))

Data-frame Object has no Attribute

I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.

laravel 5.3 new Auth::routes()

Auth routes for Laravel 5.3 instead Auth::routes(). I hope it helps...

Route::group(['middleware' => ['web']], function() {

// Login Routes...
    Route::get('login', ['as' => 'login', 'uses' => 'Auth\LoginController@showLoginForm']);
    Route::post('login', ['as' => 'login.post', 'uses' => 'Auth\LoginController@login']);
    Route::post('logout', ['as' => 'logout', 'uses' => 'Auth\LoginController@logout']);

// Registration Routes...
    Route::get('register', ['as' => 'register', 'uses' => 'Auth\RegisterController@showRegistrationForm']);
    Route::post('register', ['as' => 'register.post', 'uses' => 'Auth\RegisterController@register']);

// Password Reset Routes...
    Route::get('password/reset', ['as' => 'password.reset', 'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm']);
    Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail']);
    Route::get('password/reset/{token}', ['as' => 'password.reset.token', 'uses' => 'Auth\ResetPasswordController@showResetForm']);
    Route::post('password/reset', ['as' => 'password.reset.post', 'uses' => 'Auth\ResetPasswordController@reset']);
});

So if you change some names of these routes, remember to also change in views the actions of the posts!

Why won't my PHP app send a 404 error?

try with:

header("Status: 404 Not Found");
header('HTTP/1.0 404 Not Found');

Bye!

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

See line breaks and carriage returns in editor

You can view break lines using gedit editor.

First, if you don't have installed:

sudo apt-get install gedit

Now, install gedit plugins:

sudo apt-get install gedit-plugins

and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines

enter image description here

enter image description here

Using VSCode you can install Line endings extension.

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type

shift + ctrl + p and start type the name of the plugin, and toggle to show line ending.

Join two data frames, select all columns from one and some columns from the other

Here is the code snippet that does the inner join and select the columns from both dataframe and alias the same column to different column name.

emp_df  = spark.read.csv('Employees.csv', header =True);
dept_df = spark.read.csv('dept.csv', header =True)


emp_dept_df = emp_df.join(dept_df,'DeptID').select(emp_df['*'], dept_df['Name'].alias('DName'))
emp_df.show()
dept_df.show()
emp_dept_df.show()
Output  for 'emp_df.show()':

+---+---------+------+------+
| ID|     Name|Salary|DeptID|
+---+---------+------+------+
|  1|     John| 20000|     1|
|  2|    Rohit| 15000|     2|
|  3|    Parth| 14600|     3|
|  4|  Rishabh| 20500|     1|
|  5|    Daisy| 34000|     2|
|  6|    Annie| 23000|     1|
|  7| Sushmita| 50000|     3|
|  8| Kaivalya| 20000|     1|
|  9|    Varun| 70000|     3|
| 10|Shambhavi| 21500|     2|
| 11|  Johnson| 25500|     3|
| 12|     Riya| 17000|     2|
| 13|    Krish| 17000|     1|
| 14| Akanksha| 20000|     2|
| 15|   Rutuja| 21000|     3|
+---+---------+------+------+

Output  for 'dept_df.show()':
+------+----------+
|DeptID|      Name|
+------+----------+
|     1|     Sales|
|     2|Accounting|
|     3| Marketing|
+------+----------+

Join Output:
+---+---------+------+------+----------+
| ID|     Name|Salary|DeptID|     DName|
+---+---------+------+------+----------+
|  1|     John| 20000|     1|     Sales|
|  2|    Rohit| 15000|     2|Accounting|
|  3|    Parth| 14600|     3| Marketing|
|  4|  Rishabh| 20500|     1|     Sales|
|  5|    Daisy| 34000|     2|Accounting|
|  6|    Annie| 23000|     1|     Sales|
|  7| Sushmita| 50000|     3| Marketing|
|  8| Kaivalya| 20000|     1|     Sales|
|  9|    Varun| 70000|     3| Marketing|
| 10|Shambhavi| 21500|     2|Accounting|
| 11|  Johnson| 25500|     3| Marketing|
| 12|     Riya| 17000|     2|Accounting|
| 13|    Krish| 17000|     1|     Sales|
| 14| Akanksha| 20000|     2|Accounting|
| 15|   Rutuja| 21000|     3| Marketing|
+---+---------+------+------+----------+

Image vs Bitmap class

Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.

You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.

Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.

PHP AES encrypt / decrypt

If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.

Find more information here - http://php.net/manual/en/intro.sodium.php.

jquery $('.class').each() how many items?

Use the .length property. It is not a function.

alert($('.class').length); // alerts a nonnegative number 

In Java, remove empty elements from a list of Strings

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
System.out.println(list);
list.removeAll(Arrays.asList("", null));
System.out.println(list);

Output:

[, Hi, null, How]
[Hi, How]

Multi-Column Join in Hibernate/JPA Annotations

If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar owns them and Foo uses them to reference Bar) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar so the many-to-one relation doesn't become a many-to-many.

@Embeddable
public class AnEmbeddedObject
{
    @Column(name = "column_1")
    private Long column1;
    @Column(name = "column_2")
    private Long column2;
    @Column(name = "column_3")
    private Long column3;
    @Column(name = "column_4")
    private Long column4;
}

@Entity
public class Foo
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "column_1", referencedColumnName = "column_1"),
        @JoinColumn(name = "column_2", referencedColumnName = "column_2"),
        @JoinColumn(name = "column_3", referencedColumnName = "column_3"),
        @JoinColumn(name = "column_4", referencedColumnName = "column_4")
    })
    private Bar bar;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
    "column_1",
    "column_2",
    "column_3",
    "column_4"
}))
public class Bar
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
    private Long id;
    @Embedded
    private AnEmbeddedObject anEmbeddedObject;
}

Position an element relative to its container

You are right that CSS positioning is the way to go. Here's a quick run down:

position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).

However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children.

To demonstrate:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="box">absolute</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

class << self idiom in Ruby

What class << thing does:

class Hi
  self #=> Hi
  class << self #same as 'class << Hi'
    self #=> #<Class:Hi>
    self == Hi.singleton_class #=> true
  end
end

[it makes self == thing.singleton_class in the context of its block].


What is thing.singleton_class?

hi = String.new
def hi.a
end

hi.class.instance_methods.include? :a #=> false
hi.singleton_class.instance_methods.include? :a #=> true

hi object inherits its #methods from its #singleton_class.instance_methods and then from its #class.instance_methods.
Here we gave hi's singleton class instance method :a. It could have been done with class << hi instead.
hi's #singleton_class has all instance methods hi's #class has, and possibly some more (:a here).

[instance methods of thing's #class and #singleton_class can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]


By the way - they call object's singleton class == metaclass == eigenclass.

How to check if mysql database exists

Rails Code:

ruby-1.9.2-p290 :099 > ActiveRecord::Base.connection.execute("USE INFORMATION_SCHEMA")

ruby-1.9.2-p290 :099 > ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM         INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development'").to_a
SQL (0.2ms) SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME =               'entos_development'
=> [["entos_development"]] 
ruby-1.9.2-p290 :100 > ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM              INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development1'").to_a
SQL (0.3ms) SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME =            'entos_development1'
=> []

=> entos_development exist , entos_development1 not exist

How to add app icon within phonegap projects?

Just noting that I've just changed my config.xml to look like Sebastian's example.

Something that's also helpful in debugging all this especially if you don't do local builds... is to download the XAP/IPA/APK files as built from PhoneGap cloud and create folders for each. Rename each file with a .ZIP extension and extract the contents of each to their respective folders. So basically, you can now see what's in the package that will be shipped to the phone.

Doing this, I can see that for the Microsoft Phone platform it's largely ignoring all my attempts at replacing the icon or splash screen. If you then replace the ApplicationIcon.png and SplashScreenImage.jpg, then re-zip the folderset and rename it again as a .XAP file you can then deploy it to your phone and it will work perfectly. Somehow, there's a way of just getting the PhoneGap build to turn your icon.png and icon.jpg into those two files. Perhaps Masood's suggestion is a possibility here and utilize a hook script.

Doing the same for the .IPA file (iOS) results in several files like icon-something.png at the parent level above www. They all appear to be blank.

Doing the same for the .APK file (Android) results in a res/drawable-something set of folders and it appears to have my icon.png in each one. It's the closest to a success I can claim at the moment.

R legend placement in a plot

Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max() and then you re-use those maximum values to set the legend xy coordinates. To make sure you don't get beyond the borders, you set up ylim slightly over the maximum values.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)

enter image description here

How do you create a Distinct query in HQL

I have got a answer for Hibernate Query Language to use Distinct fields. You can use *SELECT DISTINCT(TO_CITY) FROM FLIGHT_ROUTE*. If you use SQL query, it return String List. You can't use it return value by Entity Class. So the Answer to solve that type of Problem is use HQL with SQL.

FROM FLIGHT_ROUTE F WHERE F.ROUTE_ID IN (SELECT SF.ROUTE_ID FROM FLIGHT_ROUTE SF GROUP BY SF.TO_CITY);

From SQL query statement it got DISTINCT ROUTE_ID and input as a List. And IN query filter the distinct TO_CITY from IN (List).

Return type is Entity Bean type. So you can it in AJAX such as AutoComplement.

May all be OK

How to make custom dialog with rounded corners in android

Create a xml in drawable ,say customd.xml.

then set it at background in your custom Dialog layout xml:

android:background="@drawable/customd"

finally in the java part for custom Dialog class you need to do this:

public class Customdialoque extends DialogFragment {

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    View view = inflater.inflate(R.layout.activity_customdialoque, container, false);

    return view;
}

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How to resize an image to fit in the browser window?

Make it simple. Thanks

_x000D_
_x000D_
.bg {_x000D_
  background-image: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: cover;_x000D_
  background-position: center;_x000D_
  height: 100vh;_x000D_
  width: 100vw;_x000D_
}
_x000D_
<div class="bg"></div>
_x000D_
_x000D_
_x000D_

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

?: ?? Operators Instead Of IF|ELSE

I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.

LEFT OUTER JOIN in LINQ

Take a look at this example. This query should work:

var leftFinal = from left in lefts
                join right in rights on left equals right.Left into leftRights
                from leftRight in leftRights.DefaultIfEmpty()
                select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

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

I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like

>scriptName.sh arg1 arg2

And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as "$arg1" instead of $arg1

Here are the details

Bootstrap navbar Active State not working

$(document).ready(function() {
            
   var url = window.location.href;
            
   $('a[href*="'+url+'"]').addClass("active");
            
});

Error message "No exports were found that match the constraint contract name"

I got this error after reinstalling IntelliJ IDEA and ReSharper for C# in Visual Studio 2013.

First, I got an error problem with extensions, and after this I got this error:

"No exports were found that match the constraint contract name”

I simply removed folder ComponentModelCache and resolved this error.

Creating your own header file in C

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

Is it possible to declare a variable in Gradle usable in Java?

I'm using

buildTypes.each {
    it.buildConfigField 'String', 'GoogleMapsApiKey', "\"$System.env.GoogleMapsApiKey\""
}

Its based on Dennis's answer but grabs its from an environment variable.

Should I use alias or alias_method?

I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:

class Engine
  def start
    #code goes here
  end
  alias run start
end

If you need to extend your code, use the ruby meta alternative.

class Engine
  def start
    puts "start me"
  end
end

Engine.new.start() # => start me

Engine.class_eval do
  unless method_defined?(:run)
    alias_method :run, :start
    define_method(:start) do
      puts "'before' extension"
      run()
      puts "'after' extension"
    end
  end
end

Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension

Engine.new.run # => start me

multiple prints on the same line in Python

print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

HTML image bottom alignment inside DIV container

<div> with some proportions

div {
  position: relative;
  width: 100%;
  height: 100%;
}

<img>'s with their own proportions

img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: auto; /* to keep proportions */
  height: auto; /* to keep proportions */
  max-width: 100%; /* not to stand out from div */
  max-height: 100%; /* not to stand out from div */
  margin: auto auto 0; /* position to bottom and center */
}

No connection could be made because the target machine actively refused it 127.0.0.1:3446

If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.

Dynamically updating plot in matplotlib

In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw alone does not produce the plot (at least with the qt backend).

The following works for me:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

What does it mean by select 1 from table?

I see it is always used in SQL injection,such as:

www.urlxxxxx.com/xxxx.asp?id=99 union select 1,2,3,4,5,6,7,8,9 from database;

These numbers can be used to guess where the database exists and guess the column name of the database you specified.And the values of the tables.

How to get first element in a list of tuples?

when I ran (as suggested above):

>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b

instead of returning:

[1, 2]

I received this as the return:

<map at 0xb387eb8>

I found I had to use list():

>>> b = list(map(operator.itemgetter(0), a))

to successfully return a list using this suggestion. That said, I'm happy with this solution, thanks. (tested/run using Spyder, iPython console, Python v3.6)

Concatenating two std::vectors

With range v3, you may have a lazy concatenation:

ranges::view::concat(v1, v2)

Demo.

React - How to force a function component to render?

None of these gave me a satisfactory answer so in the end I got what I wanted with the key prop, useRef and some random id generator like shortid.

Basically, I wanted some chat application to play itself out the first time someone opens the app. So, I needed full control over when and what the answers are updated with the ease of async await.

Example code:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// ... your JSX functional component, import shortid somewhere

const [render, rerender] = useState(shortid.generate())

const messageList = useRef([
    new Message({id: 1, message: "Hi, let's get started!"})
])

useEffect(()=>{
    await sleep(500)
    messageList.current.push(new Message({id: 1, message: "What's your name?"}))
    // ... more stuff
    // now trigger the update
    rerender(shortid.generate())
}, [])

// only the component with the right render key will update itself, the others will stay as is and won't rerender.
return <div key={render}>{messageList.current}</div> 

In fact this also allowed me to roll something like a chat message with a rolling .

const waitChat = async (ms) => {
    let text = "."
    for (let i = 0; i < ms; i += 200) {
        if (messageList.current[messageList.current.length - 1].id === 100) {
            messageList.current = messageList.current.filter(({id}) => id !== 100)
        }
        messageList.current.push(new Message({
            id: 100,
            message: text
        }))
        if (text.length === 3) {
            text = "."
        } else {
            text += "."
        }
        rerender(shortid.generate())
        await sleep(200)
    }
    if (messageList.current[messageList.current.length - 1].id === 100) {
        messageList.current = messageList.current.filter(({id}) => id !== 100)
    }
}

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

I tried using phyatt's AspectRatioPixmapLabel class, but experienced a few problems:

  • Sometimes my app entered an infinite loop of resize events. I traced this back to the call of QLabel::setPixmap(...) inside the resizeEvent method, because QLabel actually calls updateGeometry inside setPixmap, which may trigger resize events...
  • heightForWidth seemed to be ignored by the containing widget (a QScrollArea in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
  • I want the label to never grow more than the original pixmap size
  • QLabel's implementation of minimumSizeHint() does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite it

That said, here is my solution. I found that I could just use setScaledContents(true) and let QLabel handle the resizing. Of course, this depends on the containing widget / layout honoring the heightForWidth.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
    virtual int heightForWidth(int width) const;
    virtual bool hasHeightForWidth() { return true; }
    virtual QSize sizeHint() const { return pixmap()->size(); }
    virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"

AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
    QLabel(parent)
{
    QLabel::setPixmap(pixmap);
    setScaledContents(true);
    QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    policy.setHeightForWidth(true);
    this->setSizePolicy(policy);
}

int AspectRatioPixmapLabel::heightForWidth(int width) const
{
    if (width > pixmap()->width()) {
        return pixmap()->height();
    } else {
        return ((qreal)pixmap()->height()*width)/pixmap()->width();
    }
}

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance

dtImage.TableName="mydtimage";


if(!ds.Tables.Contains(dtImage.TableName))
        ds.Tables.Add(dtImage);

it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

dynamically set iframe src

<script type="text/javascript">
function iframeDidLoad() {
    alert('Done');
}

function newSite() {
    var sites = ['http://getprismatic.com',
                 'http://gizmodo.com/',
                 'http://lifehacker.com/']

    document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}    
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>

Example at http://jsfiddle.net/MALuP/

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

Problems with local variable scope. How to solve it?

I found this approach useful. This way you do not need a class nor final

 btnInsert.addMouseListener(new MouseAdapter() {
        private Statement _statement;

        public MouseAdapter setStatement(Statement _stmnt)
        {
            _statement = _stmnt;
            return this;
        }
        @Override
        public void mouseDown(MouseEvent e) {
            String name = text.getText();
            String from = text_1.getText();
            String to = text_2.getText();
            String price = text_3.getText();

            String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
            try {
                _statement.executeUpdate(query);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }.setStatement(statement));

JavaFX 2.1 TableView refresh items

Workaround:

 tableView.getColumns().get(0).setVisible(false);
 tableView.getColumns().get(0).setVisible(true);

What's the easiest way to call a function every 5 seconds in jQuery?

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suites you most and how to stop each of them.

Null pointer Exception on .setOnClickListener

Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.

jQuery .attr("disabled", "disabled") not working in Chrome

if you are removing all disabled attributes from input, then why not just do:

$("input").removeAttr('disabled');

Then after ajax success:

$("input[type='text']").attr('disabled', true);

Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

illegal character in path

Try this:

string path = @"C:\Program Files (x86)\test software\myapp\demo.exe";

Detect enter press in JTextField

If you want to set a default button action in a JTextField enter, you have to do this:

//put this after initComponents();

textField.addActionListener(button.getActionListeners()[0]);

It is [0] because a button can has a lot of actions, but normally just has one (ActionPerformed).

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

What's the difference between a mock & stub?

Here's a description of each one followed by with real world sample.

  • Dummy - just bogus values to satisfy the API.

    Example: If you're testing a method of a class which requires many mandatory parameters in a constructor which have no effect on your test, then you may create dummy objects for the purpose of creating new instances of a class.

  • Fake - create a test implementation of a class which may have a dependency on some external infrastructure. (It's good practice that your unit test does NOT actually interact with external infrastructure.)

    Example: Create fake implementation for accessing a database, replace it with in-memory collection.

  • Stub - override methods to return hard-coded values, also referred to as state-based.

    Example: Your test class depends on a method Calculate() taking 5 minutes to complete. Rather than wait for 5 minutes you can replace its real implementation with stub that returns hard-coded values; taking only a small fraction of the time.

  • Mock - very similar to Stub but interaction-based rather than state-based. This means you don't expect from Mock to return some value, but to assume that specific order of method calls are made.

    Example: You're testing a user registration class. After calling Save, it should call SendConfirmationEmail.

Stubs and Mocks are actually sub types of Mock, both swap real implementation with test implementation, but for different, specific reasons.

Using `date` command to get previous, current and next month

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

How to abort a Task like aborting a Thread (Thread.Abort method)?

You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.

(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)

How do I make Git ignore file mode (chmod) changes?

If you want to set this option for all of your repos, use the --global option.

git config --global core.filemode false

If this does not work you are probably using a newer version of git so try the --add option.

git config --add --global core.filemode false

If you run it without the --global option and your working directory is not a repo, you'll get

error: could not lock config file .git/config: No such file or directory

Javascript logical "!==" operator?

reference here

!== is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:

a !== b 
a !== "2" 
4 !== '4' 

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)
#!/usr/bin/python3

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py

Username and password in command for git push

According to the Git documentation, the last argument of the git push command can be the repository that you want to push to:

    git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
             [--repo=<repository>] [-f | --force] [--prune] [-v | --verbose] [-u | --set-upstream]
             [<repository> [<refspec>…]]

And the repository parameter can be either a URL or a remote name.

So you can specify username and password the same way as you do in your example of clone command.

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

What's the best way to set a single pixel in an HTML5 canvas?

Since different browsers seems to prefer different methods, maybe it would make sense to do a smaller test with all three methods as a part of the loading process to find out which is best to use and then use that throughout the application?

How to vertically align a html radio button to it's label?

Something like this should work

CSS:

input {
    float: left;
    clear: left;
    width: 50px;
    line-height: 20px;
}

label {
    float: left;
    vertical-align: middle;
}

How do I monitor the computer's CPU, memory, and disk usage in Java?

The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:

Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010

My recommendation is to use https://github.com/oshi/oshi

Or the answer mentioned above.

Laravel 5: Display HTML with Blade

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

According to the doc, you must do the following to render your html in your Blade files:

{!! $text !!}

Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Converting a string to a date in a cell

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.