Programs & Examples On #Line segment

Shortest distance between a point and a line segment

WPF version:

public class LineSegment
{
    private readonly Vector _offset;
    private readonly Vector _vector;

    public LineSegment(Point start, Point end)
    {
        _offset = (Vector)start;
        _vector = (Vector)(end - _offset);
    }

    public double DistanceTo(Point pt)
    {
        var v = (Vector)pt - _offset;

        // first, find a projection point on the segment in parametric form (0..1)
        var p = (v * _vector) / _vector.LengthSquared;

        // and limit it so it lays inside the segment
        p = Math.Min(Math.Max(p, 0), 1);

        // now, find the distance from that point to our point
        return (_vector * p - v).Length;
    }
}

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

Stop Visual Studio from mixing line endings in files

In Visual Studio 2015 (this still holds in 2019 for the same value), check the setting:

Tools > Options > Environment > Documents > Check for consistent line endings on load

VS2015 will now prompt you to convert line endings when you open a file where they are inconsistent, so all you need to do is open the files, select the desired option from the prompt and save them again.

How to read a line from the console in C?

I came across the same problem some time ago, this was my solutuion, hope it helps.

/*
 * Initial size of the read buffer
 */
#define DEFAULT_BUFFER 1024

/*
 * Standard boolean type definition
 */
typedef enum{ false = 0, true = 1 }bool;

/*
 * Flags errors in pointer returning functions
 */
bool has_err = false;

/*
 * Reads the next line of text from file and returns it.
 * The line must be free()d afterwards.
 *
 * This function will segfault on binary data.
 */
char *readLine(FILE *file){
    char *buffer   = NULL;
    char *tmp_buf  = NULL;
    bool line_read = false;
    int  iteration = 0;
    int  offset    = 0;

    if(file == NULL){
        fprintf(stderr, "readLine: NULL file pointer passed!\n");
        has_err = true;

        return NULL;
    }

    while(!line_read){
        if((tmp_buf = malloc(DEFAULT_BUFFER)) == NULL){
            fprintf(stderr, "readLine: Unable to allocate temporary buffer!\n");
            if(buffer != NULL)
                free(buffer);
            has_err = true;

            return NULL;
        }

        if(fgets(tmp_buf, DEFAULT_BUFFER, file) == NULL){
            free(tmp_buf);

            break;
        }

        if(tmp_buf[strlen(tmp_buf) - 1] == '\n') /* we have an end of line */
            line_read = true;

        offset = DEFAULT_BUFFER * (iteration + 1);

        if((buffer = realloc(buffer, offset)) == NULL){
            fprintf(stderr, "readLine: Unable to reallocate buffer!\n");
            free(tmp_buf);
            has_err = true;

            return NULL;
        }

        offset = DEFAULT_BUFFER * iteration - iteration;

        if(memcpy(buffer + offset, tmp_buf, DEFAULT_BUFFER) == NULL){
            fprintf(stderr, "readLine: Cannot copy to buffer\n");
            free(tmp_buf);
            if(buffer != NULL)
                free(buffer);
            has_err = true;

            return NULL;
        }

        free(tmp_buf);
        iteration++;
    }

    return buffer;
}

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

There are some dedicated classes for this:

import java.text.*;

final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
   // process c
   ...
}

Calling a function of a module by using its name (a string)

getattr calls method by name from an object. But this object should be parent of calling class. The parent class can be got by super(self.__class__, self)

class Base:
    def call_base(func):
        """This does not work"""
        def new_func(self, *args, **kwargs):
            name = func.__name__
            getattr(super(self.__class__, self), name)(*args, **kwargs)
        return new_func

    def f(self, *args):
        print(f"BASE method invoked.")

    def g(self, *args):
        print(f"BASE method invoked.")

class Inherit(Base):
    @Base.call_base
    def f(self, *args):
        """function body will be ignored by the decorator."""
        pass

    @Base.call_base
    def g(self, *args):
        """function body will be ignored by the decorator."""
        pass

Inherit().f() # The goal is to print "BASE method invoked."

Check whether an array is empty

I can't replicate that (php 5.3.6):

php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)

php > $error = array();
php > var_dump(empty($error));
bool(true)
php >

exactly where are you doing the empty() call that returns true?

Eclipse "this compilation unit is not on the build path of a java project"

Your source files should be in a structure with a 'package' icon in the Package Explorer view (in the menu under Window > Show View > Package Explorer or press Ctrl+3 and type pack), like this:

Java project in Eclipse

If they are not, select the folder containing your root package (src in the image above) and select Use as Source Folder from the context menu (right click).

How to debug Angular JavaScript Code

For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P

Type Debugger for Chrome in the search bar, install it and enable it.

In your launch.json file add this config :

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost with sourcemaps",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/mypage.html",
            "webRoot": "${workspaceRoot}/app/files",
            "sourceMaps": true
        },
        {
            "name": "Launch index.html (without sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceRoot}/index.html"
        },
    ]
}

You must launch Chrome with remote debugging enabled in order for the extension to attach to it.

  • Windows

Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222

  • OS X

In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

  • Linux

In a terminal, launch google-chrome --remote-debugging-port=9222

Find More ===>

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

 Use the below code to solve the CertPathValidatorException issue.


 Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_BASE_URL)
        .client(getUnsafeOkHttpClient().build())
        .build();


  public static OkHttpClient.Builder getUnsafeOkHttpClient() {

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

For more details visit https://mobikul.com/android-retrofit-handling-sslhandshakeexception/

What is the SSIS package and what does it do?

SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.

SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.

Using jq to parse and display multiple fields in a json serially

You can use addition to concatenate strings.

Strings are added by being joined into a larger string.

jq '.users[] | .first + " " + .last'

The above works when both first and last are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.

jq '.users[] | .first + " " + (.number|tostring)'

Convert comma separated string of ints to int array

You should use a foreach loop, like this:

public static IEnumerable<int> StringToIntList(string str) {
    if (String.IsNullOrEmpty(str))
        yield break;

    foreach(var s in str.Split(',')) {
        int num;
        if (int.TryParse(s, out num))
            yield return num;
    }
}

Note that like your original post, this will ignore numbers that couldn't be parsed.

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

return (str ?? "").Split(',').Select<string, int>(int.Parse);

Parse an URL in JavaScript

Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.

I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.

How do I sort a Set to a List in Java?

@Jeremy Stein I wanted to implement same code. As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable. This code helped me,

set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());

All com.android.support libraries must use the exact same version specification

Try To make the build tools exactly the same version of support library

example

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.itechnologyeg.*******"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    } 
dependencies {
 compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:animated-vector-drawable:25.0.0'
    compile 'com.android.support:mediarouter-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
}

Push items into mongo array via mongoose

I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.

---- Person model

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

***Important: SingleFriend.schema -> make sure to use lowercase for schema

--- Child schema

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

C# string replace

You need to escape the double-quotes inside the search string, like this:

string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");

Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res will have the replacements.

ImportError: DLL load failed: The specified module could not be found

For Windows 10 x64 and Python:

Open a Visual Studio x64 command prompt, and use dumpbin:

dumpbin /dependents [Python Module DLL or PYD file]

If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.

Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.

Case study 1

  1. I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.

  2. It was giving this error: ImportError: DLL load failed: The specified module could not be found

  3. Opened a Visual Studio x64 command prompt.

  4. Under Windows, a .pyd file is a .dll file in disguise, so we want to run dumpbin on this file.

  5. cd MyLibrary\build\lib.win-amd64-3.7\Debug

  6. dumpbin /dependents MyLibrary.cp37-win_amd64.pyd which prints this:

    Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLibrary.cp37-win_amd64.pyd
    
    File Type: DLL
    
      Image has the following dependencies:
    
        clang_rt.asan_dbg_dynamic-x86_64.dll
        gtestd.dll
        tbb_debug.dll
        python37.dll
        KERNEL32.dll
        MSVCP140D.dll
        VCOMP140D.DLL
        VCRUNTIME140D.dll
        VCRUNTIME140_1D.dll
        ucrtbased.dll
    
      Summary
    
         1000 .00cfg
        D6000 .data
         7000 .idata
        46000 .pdata
       341000 .rdata
        23000 .reloc
         1000 .rsrc
       856000 .text
    
  7. Searched for clang_rt.asan_dbg_dynamic-x86_64.dll, copied it into the same directory, problem solved.

  8. Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.

Please feel free to add your own case studies here! I've made it a community wiki answer.

SOAP or REST for Web Services?

It's a good question... I don't want to lead you astray, so I'm open to other people's answers as much as you are. For me, it really comes down to cost of overhead and what the use of the API is. I prefer consuming web services when creating client software, however I don't like the weight of SOAP. REST, I believe, is lighter weight but I don't enjoy working with it from a client perspective nearly as much.

I'm curious as to what others think.

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

Arrays in unix shell?

in bash, you create array like this

arr=(one two three)

to call the elements

$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three

to ask for user input, you can use read

read -p "Enter your choice: " choice

typedef fixed length array

You want

typedef char type24[3];

C type declarations are strange that way. You put the type exactly where the variable name would go if you were declaring a variable of that type.

jQuery prevent change for select

Try this:

http://jsfiddle.net/qk2Pc/

var my_condition = true;
var lastSel = $("#my_select option:selected");

$("#my_select").change(function(){
  if(my_condition)
  {
    lastSel.prop("selected", true);
  }
});

$("#my_select").click(function(){
    lastSel = $("#my_select option:selected");
});

How permission can be checked at runtime without throwing SecurityException?

You can also use this:

private boolean doesUserHavePermission()
{
    int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}

How can I one hot encode in Python?

Here is a solution using DictVectorizer and the Pandas DataFrame.to_dict('records') method.

>>> import pandas as pd
>>> X = pd.DataFrame({'income': [100000,110000,90000,30000,14000,50000],
                      'country':['US', 'CAN', 'US', 'CAN', 'MEX', 'US'],
                      'race':['White', 'Black', 'Latino', 'White', 'White', 'Black']
                     })

>>> from sklearn.feature_extraction import DictVectorizer
>>> v = DictVectorizer()
>>> qualitative_features = ['country','race']
>>> X_qual = v.fit_transform(X[qualitative_features].to_dict('records'))
>>> v.vocabulary_
{'country=CAN': 0,
 'country=MEX': 1,
 'country=US': 2,
 'race=Black': 3,
 'race=Latino': 4,
 'race=White': 5}

>>> X_qual.toarray()
array([[ 0.,  0.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  1.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  1.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  1.,  1.,  0.,  0.]])

Use of 'const' for function parameters

const is pointless when the argument is passed by value since you will not be modifying the caller's object.

const should be preferred when passing by reference, unless the purpose of the function is to modify the passed value.

Finally, a function which does not modify current object (this) can, and probably should be declared const. An example is below:

int SomeClass::GetValue() const {return m_internalValue;}

This is a promise to not modify the object to which this call is applied. In other words, you can call:

const SomeClass* pSomeClass;
pSomeClass->GetValue();

If the function was not const, this would result in a compiler warning.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

The type or namespace name 'System' could not be found

I've tried all answers above. For me works only removal and adding the reference again described in the following steps:

  1. Open 'References' under the project.
  2. Right click on 'System' reference.
  3. Click on 'Remove'.
  4. Right click on 'References'.
  5. Click 'Add Reference...'.
  6. From right menu choose an 'Assemblies',
  7. In a search field type 'System'.
  8. Choose 'System' from the list.
  9. Click 'Add' button.
  10. IMPORTANT: Restart the Visual Studio.

How to call multiple functions with @click in vue?

You can use this:

<div @click="f1(), f2()"></div> 

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

Although I didn't use this exact function I got this same error.

In my case I just had to remove the protocol.

Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";

Use $uri = "api.hostip.info/?ip=$ip&position=true";

And it worked fine afterwards

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Is key-value pair available in Typescript?

Another simple way is to use a tuple:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

Output:

First: hello Second: 10

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

How to set UITextField height?

1.) Change the border Style in the InterfaceBuilder.

enter image description here

2.) After that you're able to change the size.

enter image description here

3.) Create an IBOutlet to your TextField and enter the following code to your viewDidLoad() to change the BorderStyle back.

textField.borderStyle = UITextBorderStyleRoundedRect;

Swift 3:

textField.borderStyle = UITextBorderStyle.roundedRect

Maven: The packaging for this project did not assign a file to the build artifact

This reply is on a very old question to help others facing this issue.

I face this failed error while I were working on my Java project using IntelliJ IDEA IDE.

Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project getpassword: The packaging for this project did not assign a file to the build artifact

this failed happens, when I choose install:install under Plugins - install, as pointed with red arrow in below image.

Choose Wrong Selection

Once I run the selected install under Lifecycle as illustrated above, the issue gone, and my maven install compile build successfully.

Use URI builder in Android or create URL with variables

You can do that with lambda expressions;

    private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";

    private String getBaseUrl(Map<String, String> params) {
        final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
        params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
        return builder.build().toString();
    }

and you can create params like that;

    Map<String, String> params = new HashMap<String, String>();
    params.put("zip", "94043,us");
    params.put("units", "metric");

Btw. If you will face any issue like “lambda expressions not supported at this language level”, please check this URL;

https://stackoverflow.com/a/22704620/2057154

sed one-liner to convert all uppercase to lowercase?

Here are many solutions :

To upercaser with perl, tr, sed and awk

perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'

To lowercase with perl, tr, sed and awk

perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'

Complicated bash to lowercase :

while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done

Complicated bash to uppercase :

while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done

Simple bash to lowercase :

while read v;do echo "${v,,}"; done

Simple bash to uppercase :

while read v;do echo "${v^^}"; done

Note that ${v,} and ${v^} only change the first letter.

You should use it that way :

(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt

Hash table in JavaScript

The Javascript interpreter natively stores objects in a hash table. If you're worried about contamination from the prototype chain, you can always do something like this:

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true

LINQ to SQL Left Outer Join

Take care of performance:

I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.

In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]

The solution by Marc Gravell resulted in a query without cross joins.

Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.

Estimated operator costs:

  • with cross apply: 0.2534
  • without cross apply: 0.0991.

Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):

  • with cross apply: 5, 6, 6, 6, 6, 6, 6, 6, 6, 6
  • without cross apply: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

(The very first run was slower for both queries; seems that something is cached.)

Table sizes:

  • main table: 87 rows,
  • first table for left join: 179 rows;
  • second table for left join: 7 rows.

EF Core version: 2.2.1.

SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).

All relevant tables had indexes on the primary keys only.

My conclusion: it's always recommended to look at the generated SQL since it can really differ.


[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.

Download pdf file using jquery ajax

You can do this with html5 very easily:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))

since

operator.itemgetter(self.testListNone,slice(None,1))

is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

Temporary tables in stored procedures

The database uses the same lock for all #temp tables so if you are using a lot you will get deadlock problems. It is better to use @ table variables for concurrency.

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

ruby 1.9: invalid byte sequence in UTF-8

This seems to work:

def sanitize_utf8(string)
  return nil if string.nil?
  return string if string.valid_encoding?
  string.chars.select { |c| c.valid_encoding? }.join
end

Add custom icons to font awesome

Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.

Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.

Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

TSQL: How to convert local time to UTC? (SQL Server 2008)

While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.

That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.

Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.

How do I get the last character of a string?

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) {

or, strings

if (str.endsWith("bar")) {

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

What is the difference between SessionState and ViewState?

Usage: If you're going to store information that you want to access on different web pages, you can use SessionState

If you want to store information that you want to access from the same page, then you can use Viewstate

Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.

The SessionState will clear in the following conditions

  1. Cleared by programmer
  2. Cleared by user
  3. Timeout

How to len(generator())

Generators have no length, they aren't collections after all.

Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.

if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?

Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.

You can however simply return (generator, length) pairs from your functions or wrap the generator in a simple object like this:

class GeneratorLen(object):
    def __init__(self, gen, length):
        self.gen = gen
        self.length = length

    def __len__(self): 
        return self.length

    def __iter__(self):
        return self.gen

g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)

How can JavaScript save to a local file?

If you are using FireFox you can use the File HandleAPI

https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API

I had just tested it out and it works!

Table with fixed header and fixed column on pure css

All of these suggestions are great and all, but they're either only fixing either the header or a column, not both, or they're using javascript. The reason - it don't believe it can be done in pure CSS. The reason:

If it were possible to do it, you would need to nest several scrollable divs one inside the other, each with a scroll in a different direction. Then you would need to split your table into three parts - the fixed header, the fixed column and the rest of the data.

Fine. But now the problem - you can make one of them stay put when you scroll, but the other one is nested inside the scrolling area of first and is therefore subject to being scrolled out of sight itself, so can't be fixed in place on the screen. 'Ah-ha' you say 'but I can somehow use absolute or fixed position to do that' - no you can't. As soon as you do that you lose the ability to scroll that container. It's a chicken and egg situation - you can't have both, they cancel each other out.

I believe the only solution is through javascript. You need to completely seperate out the three elements and keep their positions in sync through javascript. There are good examples in other posts on this page. This one is also worth a look:

http://tympanus.net/codrops/2014/01/09/sticky-table-headers-columns/

Replace tabs with spaces in vim

Once you've got expandtab on as per the other answers, the extremely convenient way to convert existing files according to your new settings is:

:retab

It will work on the current buffer.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

When I copied only javaw, the second error occured, there is not a java.dll file, when I copied it too, eclipse did not start, what I did was that I copied whole jdk folder to eclipse folder and renamed id to jre. Problem solved.

How to determine an object's class?

Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

If your design is good, you should not find yourself needing to use getClass() or instanceof.

Any of the suggested methods will do, but just something to keep in mind, design-wise.

How to print color in console using System.out.println?

Best Solution to print any text in red color in Java is:

System.err.print("Hello World");

Initialize a string in C to empty string

Assuming your array called 'string' already exists, try

string[0] = '\0';

\0 is the explicit NUL terminator, required to mark the end of string.

In Maven how to exclude resources from the generated jar?

Another possibility is to use the Maven Shade Plugin, e.g. to exclude a logging properties file used only locally in your IDE:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>${maven-shade-plugin-version}</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>log4j2.xml</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

This will however exclude the files from every artifact, so it might not be feasible in every situation.

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

PHP: Best way to check if input is a valid number?

The most secure way

if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
  //if all made of numbers "-" or ".", then yes is number;
}

Vim autocomplete for Python

This can be a good option if you want python completion as well as other languages. https://github.com/Valloric/YouCompleteMe

The python completion is jedi based same as jedi-vim.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Why is vertical-align: middle not working on my span or div?

Here is the latest simplest solution - no need to change anything, just add three lines of CSS rules to your container of the div where you wish to center at. I love Flex Box #LoveFlexBox

_x000D_
_x000D_
.main {_x000D_
  /* I changed height to 200px to make it easy to see the alignment. */_x000D_
  height: 200px;_x000D_
  vertical-align: middle;_x000D_
  border: 1px solid #000000;_x000D_
  padding: 2px;_x000D_
  _x000D_
  /* Just add the following three rules to the container of which you want to center at. */_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  /* This is true vertical center, no math needed. */_x000D_
}_x000D_
.inner {_x000D_
  border: 1px solid #000000;_x000D_
}_x000D_
.second {_x000D_
  border: 1px solid #000000;_x000D_
}
_x000D_
<div class="main">_x000D_
  <div class="inner">This box should be centered in the larger box_x000D_
    <div class="second">Another box in here</div>_x000D_
  </div>_x000D_
  <div class="inner">This box should be centered in the larger box_x000D_
    <div class="second">Another box in here</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bonus

the justify-content value can be set to the following few options:

  • flex-start, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.

  • center, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column flex-direction. similarly, if you change the flow-direction to row, it will become horizontally centered.

  • flex-end, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.

  • space-between, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.

  • space-around, similar to space-between, but with half of the space in the beginning and end of the flow.

Check to see if cURL is installed locally?

Assuming you want curl installed: just execute the install command and see what happens.

$ sudo yum install curl

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.cat.pdx.edu
 * epel: mirrors.kernel.org
 * extras: mirrors.cat.pdx.edu
 * remi-php72: repo1.sea.innoscale.net
 * remi-safe: repo1.sea.innoscale.net
 * updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do

C++ template constructor

You can create a templated factory function:

class Foo
{
public:
    template <class T> static Foo* create() // could also return by value, or a smart pointer
    {
        return new Foo(...);
    }
...        
};

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

How can I create a progress bar in Excel VBA?

============== This code goes in Module1 ============

Sub ShowProgress()
    UserForm1.Show
End Sub

============== Module1 Code Block End =============

Create a Button on a Worksheet; map button to "ShowProgress" macro

Create a UserForm1 with 2 buttons, progress bar, bar box, text box:

UserForm1 = canvas to hold other 5 elements
CommandButton2 = Run Progress Bar Code; Caption:Run
CommandButton1 = Close UserForm1; Caption:Close
Bar1 (label) = Progress bar graphic; BackColor:Blue
BarBox (label) = Empty box to frame Progress Bar; BackColor:White
Counter (label) = Display the integers used to drive the progress bar

======== Attach the following code to UserForm1 =========

Option Explicit

' This is used to create a delay to prevent memory overflow
' remove after software testing is complete

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub UserForm_Initialize()

    Bar1.Tag = Bar1.Width
    Bar1.Width = 0

End Sub
Sub ProgressBarDemo()
    Dim intIndex As Integer
    Dim sngPercent As Single
    Dim intMax As Integer
    '==============================================
    '====== Bar Length Calculation Start ==========

    '-----------------------------------------------'
    ' This section is where you can use your own    '
    ' variables to increase bar length.             '
    ' Set intMax to your total number of passes     '
    ' to match bar length to code progress.         '
    ' This sample code automatically runs 1 to 100  '
    '-----------------------------------------------'
    intMax = 100
    For intIndex = 1 To intMax
        sngPercent = intIndex / intMax
        Bar1.Width = Int(Bar1.Tag * sngPercent)
        Counter.Caption = intIndex


    '======= Bar Length Calculation End ===========
    '==============================================


DoEvents
        '------------------------
        ' Your production code would go here and cycle
        ' back to pass through the bar length calculation
        ' increasing the bar length on each pass.
        '------------------------

'this is a delay to keep the loop from overrunning memory
'remove after testing is complete
        Sleep 10

    Next

End Sub
Private Sub CommandButton1_Click() 'CLOSE button

Unload Me

End Sub
Private Sub CommandButton2_Click() 'RUN button

        ProgressBarDemo

End Sub

================= UserForm1 Code Block End =====================

============== This code goes in Module1 =============

Sub ShowProgress()
    UserForm1.Show
End Sub

============== Module1 Code Block End =============

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How to place div side by side

CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.

Simply define the width of the first div, and then give the second a flex-grow value of 1 which will allow it to fill the remaining width of the parent.

.container{
    display: flex;
}
.fixed{
    width: 200px;
}
.flex-item{
    flex-grow: 1;
}
<div class="container">
  <div class="fixed"></div>
  <div class="flex-item"></div>
</div>

Demo:

_x000D_
_x000D_
div {
    color: #fff;
    font-family: Tahoma, Verdana, Segoe, sans-serif;
    padding: 10px;
}
.container {
    background-color:#2E4272;
    display:flex;
}
.fixed {
    background-color:#4F628E;
    width: 200px;
}
.flex-item {
    background-color:#7887AB;
    flex-grow: 1;
}
_x000D_
<div class="container">
    <div class="fixed">Fixed width</div>
    <div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
_x000D_
_x000D_

Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Application not picking up .css file (flask/python)

One more point to add on to this thread.

If you add an underscore in your .css file name, then it wouldn't work.

Operator overloading on class templates

This way works:

class A
{
    struct Wrap
    {
        A& a;
        Wrap(A& aa) aa(a) {}
        operator int() { return a.value; }
        operator std::string() { stringstream ss; ss << a.value; return ss.str(); } 
    }
    Wrap operator*() { return Wrap(*this); }
};

How to send PUT, DELETE HTTP request in HttpURLConnection?

public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}

Adding class to element using Angular JS

Use the MV* Pattern

Based on the example you attached, It's better in angular to use the following tools:

  • ng-click - evaluates the expression when the element is clicked (Read More)
  • ng-class - place a class based on the a given boolean expression (Read More)

for example:

<button ng-click="enabled=true">Click Me!</button>

<div ng-class="{'alpha':enabled}"> 
    ...
</div>

This gives you an easy way to decouple your implementation. e.g. you don't have any dependency between the div and the button.

Read this to learn about the MV* Pattern

Send POST data via raw json with postman

Just check JSON option from the drop down next to binary; when you click raw. This should do

skill synon pass json to postman

Replace the single quote (') character from a string

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
    
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")
    

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
    
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")
    

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended - works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)
    x.remove("'")
    ''.join(x)
    

Folder is locked and I can't unlock it

This was the first time I had this issue. I even tried to restart PC, without effect. This solves my problem:

Solution for me:

  1. Right Click on Project Working Directory.
  2. Navigate TortoiseSVN.
  3. Navigate To Clean Up.
  4. Leave all default options, and check Break Locks
  5. Click OK

This works for me. I was able to commit changes.

IOS: verify if a point is inside a rect

In objective c you can use CGRectContainsPoint(yourview.frame, touchpoint)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch* touch = [touches anyObject];
CGPoint touchpoint = [touch locationInView:self.view];
if( CGRectContainsPoint(yourview.frame, touchpoint) ) {

}else{

}}

In swift 3 yourview.frame.contains(touchpoint)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let touchpoint:CGPoint = touch.location(in: self.view)
    if wheel.frame.contains(touchpoint)  {

    }else{

    }

}

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

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

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

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

How do implement a breadth first traversal?

For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java

Numbering rows within groups in a data frame

Another dplyr possibility could be:

df %>%
 group_by(cat) %>%
 mutate(num = 1:n())

   cat      val   num
   <fct>  <dbl> <int>
 1 aaa   0.0564     1
 2 aaa   0.258      2
 3 aaa   0.308      3
 4 aaa   0.469      4
 5 aaa   0.552      5
 6 bbb   0.170      1
 7 bbb   0.370      2
 8 bbb   0.484      3
 9 bbb   0.547      4
10 bbb   0.812      5
11 ccc   0.280      1
12 ccc   0.398      2
13 ccc   0.625      3
14 ccc   0.763      4
15 ccc   0.882      5

Confused about stdin, stdout and stderr?

Using ps -aux reveals current processes, all of which are listed in /proc/ as /proc/(pid)/, by calling cat /proc/(pid)/fd/0 it prints anything that is found in the standard output of that process I think. So perhaps,

/proc/(pid)/fd/0 - Standard Output File
/proc/(pid)/fd/1 - Standard Input File
/proc/(pid)/fd/2 - Standard Error File

for examplemy terminal window

But only worked this well for /bin/bash other processes generally had nothing in 0 but many had errors written in 2

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet "ControllerA", it should refer the specified URL Pattern "theController" from the form.

eg:

<form action="theController" method="POST">
</form>

return error message with actionResult

You need to return a view which has a friendly error message to the user

catch (Exception ex)
{
   // to do :log error
   return View("Error");
}

You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.

If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions

[HttpPost]
public ActionResult Create(CustomerVM model)
{
  try
  {
   //save customer
    return Json(new { status="success",message="customer created"});
  }
  catch(Exception ex)
  {
    //to do: log error
   return Json(new { status="error",message="error creating customer"});
  }
} 

If you want to show the error in the form user submitted, You may use ModelState.AddModelError method along with the Html helper methods like Html.ValidationSummary etc to show the error to the user in the form he submitted.

Virtual Serial Port for Linux

I can think of three options:

Implement RFC 2217

RFC 2217 covers a com port to TCP/IP standard that allows a client on one system to emulate a serial port to the local programs, while transparently sending and receiving data and control signals to a server on another system which actually has the serial port. Here's a high-level overview.

What you would do is find or implement a client com port driver that would implement the client side of the system on your PC - appearing to be a real serial port but in reality shuttling everything to a server. You might be able to get this driver for free from Digi, Lantronix, etc in support of their real standalone serial port servers.

You would then implement the server side of the connection locally in another program - allowing the client to connect and issuing the data and control commands as needed.

It's probably non trivial, but the RFC is out there, and you might be able to find an open source project that implements one or both sides of the connection.

Modify the linux serial port driver

Alternately, the serial port driver source for Linux is readily available. Take that, gut the hardware control pieces, and have that one driver run two /dev/ttySx ports, as a simple loopback. Then connect your real program to the ttyS2 and your simulator to the other ttySx.

Use two USB<-->Serial cables in a loopback

But the easiest thing to do right now? Spend $40 on two serial port USB devices, wire them together (null modem) and actually have two real serial ports - one for the program you're testing, one for your simulator.

-Adam

How to apply a function to two columns of Pandas dataframe

I suppose you don't want to change get_sublist function, and just want to use DataFrame's apply method to do the job. To get the result you want, I've wrote two help functions: get_sublist_list and unlist. As the function name suggest, first get the list of sublist, second extract that sublist from that list. Finally, We need to call apply function to apply those two functions to the df[['col_1','col_2']] DataFrame subsequently.

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

def get_sublist_list(cols):
    return [get_sublist(cols[0],cols[1])]

def unlist(list_of_lists):
    return list_of_lists[0]

df['col_3'] = df[['col_1','col_2']].apply(get_sublist_list,axis=1).apply(unlist)

df

If you don't use [] to enclose the get_sublist function, then the get_sublist_list function will return a plain list, it'll raise ValueError: could not broadcast input array from shape (3) into shape (2), as @Ted Petrou had mentioned.

Adding a JAR to an Eclipse Java library

In eclipse Galileo :

  • Open the project's properties
  • Select Java Build Path
  • Select Libraries tab

From there you can Add External Jars

Why std::cout instead of simply cout?

"std" is a namespace used for STL (Standard Template Library). Please refer to https://en.wikipedia.org/wiki/Namespace#Use_in_common_languages

You can either write using namespace std; before using any stl functions, variables or just insert std:: before them.

Converting strings to floats in a DataFrame

In a newer version of pandas (0.17 and up), you can use to_numeric function. It allows you to convert the whole dataframe or just individual columns. It also gives you an ability to select how to treat stuff that can't be converted to numeric values:

import pandas as pd
s = pd.Series(['1.0', '2', -3])
pd.to_numeric(s)
s = pd.Series(['apple', '1.0', '2', -3])
pd.to_numeric(s, errors='ignore')
pd.to_numeric(s, errors='coerce')

Change MySQL root password in phpMyAdmin

Explain what video describe to resolve problem

After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

If you have more than 1 DB server, add "i++" to file and continue add new config as above

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

How to list files in an android directory?

In addition to all the answers above:

If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having

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

in your manifest won't be enough. You also have actively request the permission in your activity:

//check for permission
if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
    //ask for permission
    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMISSION_CODE);
}

I recommend reading this: http://developer.android.com/training/permissions/requesting.html#perm-request

What's the regular expression that matches a square bracket?

If you want to remove the [ or the ], use the expression: "\\[|\\]".

The two backslashes escape the square bracket and the pipe is an "or".

Scanner is skipping nextLine() after using next() or nextFoo()?

In one of my usecase, I had the scenario of reading a string value preceded by a couple of integer values. I had to use a "for / while loop" to read the values. And none of the above suggestions worked in this case.

Using input.next() instead of input.nextLine() fixed the issue. Hope this might be helpful for those dealing with similar scenario.

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

How to prevent default event handling in an onclick method?

This worked for me

<a href="javascript:;" onclick="callmymethod(24); return false;">Call</a>

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How to change color of ListView items on focus and on click

The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.

Specifically, you'd set the textColor of your textViews to an XML resource like this one:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

To solve this:

All you need to do is to install Python certificates! A common issue on macOS.

Open these files:

Install Certificates.command
Update Shell Profile.command

Simply Run these two scripts and you wont have this issue any more.

Hope this helps!

DataRow: Select cell value by a given column name

This must be a new feature or something, otherwise I'm not sure why it hasn't been mentioned.

You can access the value in a column in a DataRow object using row["ColumnName"]:

DataRow row = table.Rows[0];
string rowValue = row["ColumnName"].ToString();

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

How do I revert all local changes in Git managed project to previous state?

Try this for revert all changes uncommited in local branch

$ git reset --hard HEAD

But if you see a error like this:

fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.

You can navigate to '.git' folder then delete index.lock file:

$ cd /directory/for/your/project/.git/
$ rm index.lock

Finaly, run again the command:

$ git reset --hard HEAD

Calling another different view from the controller using ASP.NET MVC 4

You have to specify the name of the custom view and its related model in Controller Action method.

public ActionResult About()
{            
   return View("NameOfViewYouWantToReturn",Model); 
}

Removing trailing newline character from fgets() input

Direct to remove the '\n' from the fgets output if every line has '\n'

line[strlen(line) - 1] = '\0';

Otherwise:

void remove_newline_ch(char *line)
{
    int new_line = strlen(line) -1;
    if (line[new_line] == '\n')
        line[new_line] = '\0';
}

How to check edittext's text is email address or not?

Please follow the following Steps

Step 1 :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@+id/textView_email"
        android:layout_marginTop="40dp"
        android:hint="Email Adderess"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Email Validation Example" />

</RelativeLayout>

Step 2:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

Step 3:

public class MainActivity extends Activity {

private EditText email;

private String valid_email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initilizeUI();
}

/**
 * This method is used to initialize UI Components
 */
private void initilizeUI() {
    // TODO Auto-generated method stub

    email = (EditText) findViewById(R.id.editText_email);

    email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            Is_Valid_Email(email); // pass your EditText Obj here.
        }

        public void Is_Valid_Email(EditText edt) {
            if (edt.getText().toString() == null) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(edt.getText().toString()) == false) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else {
                valid_email = edt.getText().toString();
            }
        }

        boolean isEmailValid(CharSequence email) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                    .matches();
        } // end of TextWatcher (email)
    });

}

}

How to change default format at created_at and updated_at value laravel

You can also try like this.

Use Carbon\Carbon;


$created_at = "2014-06-26 04:07:31";

$date = Carbon::parse($created_at);

echo $date->format("Y-m-d");

split string only on first instance of specified character

Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.

So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:

_x000D_
_x000D_
String.prototype.splitOnce = function(regex)_x000D_
{_x000D_
    var match = this.match(regex);_x000D_
    if(match)_x000D_
    {_x000D_
        var match_i = this.indexOf(match[0]);_x000D_
        _x000D_
        return [this.substring(0, match_i),_x000D_
        this.substring(match_i + match[0].length)];_x000D_
    }_x000D_
    else_x000D_
    { return [this, ""]; }_x000D_
}_x000D_
_x000D_
var str = "something/////another thing///again";_x000D_
_x000D_
alert(str.splitOnce(/\/+/)[1]);
_x000D_
_x000D_
_x000D_

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

Getting the last element of a split string array

There's a one-liner for everything. :)

var output = input.split(/[, ]+/).pop();

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

Set Locale programmatically

 /**
 * Requests the system to update the list of system locales.
 * Note that the system looks halted for a while during the Locale migration,
 * so the caller need to take care of it.
 */
public static void updateLocales(LocaleList locales) {
    try {
        final IActivityManager am = ActivityManager.getService();
        final Configuration config = am.getConfiguration();

        config.setLocales(locales);
        config.userSetLocale = true;

        am.updatePersistentConfiguration(config);
    } catch (RemoteException e) {
        // Intentionally left blank
    }
}

'invalid value encountered in double_scalars' warning, possibly numpy

In my case, I found out it was division by zero.

How to position a Bootstrap popover?

Sure you can. Fortunately there is a clean way to do that and it is in the Bootstrap popover / tooltip documentation as well.

let mySpecialTooltip = $('#mySpecialTooltip); 
mySpecialTooltip.tooltip({
 container: 'body',
 placement: 'bottom',
 html: true,
 template: '<div class="tooltip your-custom-class" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
}); 

in your css file:-

.your-custom-class {
 bottom: your value;
}

Make sure to add the template in bootstrap's tooltip documentation and add your custom class name and style it using css

And, that's it. You can find more about this on https://getbootstrap.com/docs/4.0/components/tooltips/

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

Summernote image upload

Image Upload for Summernote v0.8.1

for large images

$('#summernote').summernote({
    height: ($(window).height() - 300),
    callbacks: {
        onImageUpload: function(image) {
            uploadImage(image[0]);
        }
    }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("image", image);
    $.ajax({
        url: 'Your url to deal with your image',
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('<img>').attr('src', 'http://' + url);
            $('#summernote').summernote("insertNode", image[0]);
        },
        error: function(data) {
            console.log(data);
        }
    });
}

How to detect window.print() finish

It is difficult, due to different browser behavior after print. Desktop Chrome handles the print dialogue internally, so doesn't shift focus after print, however, afterprint event works fine here (As of now, 81.0). On the other hand, Chrome on mobile device and most of the other browsers shifts focus after print and afterprint event doesn't work consistently here. Mouse movement event doesn't work on mobile devices.

So, Detect if it is Desktop Chrome, If Yes, use afterprint event. If No, use focus based detection. You can also use mouse movement event(Works in desktop only) in combination of these, to cover more browsers and more scenarios.

How to fix 'android.os.NetworkOnMainThreadException'?

Google deprecated the Android AsyncTask API in Android 11, even if you create a thread class outside the main activity, just by calling it in main you will get the same error, the calls must be inside a runnable thread, but if you need some asynchronous code to execute on the background or some on post afterwards here you can check out some alternatives for both Kotlin and Java

https://stackoverflow.com/questions/58767733/android-asynctask-api-deprecating-in-android-11-what-are-the-alternatives

the one that worked for me specifically was an answer by mayank1513 for a java 8 implementation of runnable thread found on the above link, code is as follows

new Thread(() -> {
        // do background stuff here
        runOnUiThread(()->{
            // OnPostExecute stuff here
        });
    }).start();

However you can define the thread first in some part of your code and start it somewhere else like this

thread definition

Thread thread = new Thread(() -> {
            // do background stuff here
            runOnUiThread(()->{
                // OnPostExecute stuff here
            });
        });

thread call

thread.start();

hope this saves someone the headache of seeing deprecated AsyncTask

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

PHP - Failed to open stream : No such file or directory

There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.

Let's consider that we are troubleshooting the following line:

require "/path/to/file"


Checklist


1. Check the file path for typos

  • either check manually (by visually checking the path)
  • or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:

    $path = "/path/to/file";
    
    echo "Path : $path";
    
    require "$path";
    

    Then, in a terminal:

    cat <file path pasted>
    


2. Check that the file path is correct regarding relative vs absolute path considerations

  • if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
    • for example, your website's directory might be /users/tony/htdocs
  • if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
    • thus, not relative to the path of your web site's root, or to the file where you are typing
    • for that reason, always use absolute file paths

Best practices :

In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :

  1. use require __DIR__ . "/relative/path/from/current/file". The __DIR__ magic constant returns the directory of the current file.
  2. define a SITE_ROOT constant yourself :

    • at the root of your web site's directory, create a file, e.g. config.php
    • in config.php, write

      define('SITE_ROOT', __DIR__);
      
    • in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :

      require_once __DIR__."/../config.php";
      ...
      require_once SITE_ROOT."/other/file.php";
      

These 2 practices also make your application more portable because it does not rely on ini settings like the include path.


3. Check your include path

Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.

Such an inclusion will look like this :

include "Zend/Mail/Protocol/Imap.php"

In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.

You can check the include path with :

echo get_include_path();

You can add a folder to it with :

set_include_path(get_include_path().":"."/path/to/new/folder");


4. Check that your server has access to that file

It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.

To check under what user the server is running you can use posix_getpwuid :

$user = posix_getpwuid(posix_geteuid());

var_dump($user);

To find out the permissions on the file, type the following command in the terminal:

ls -l <path/to/file>

and look at permission symbolic notation


5. Check PHP settings

If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.

Three settings could be relevant :

  1. open_basedir
    • If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
    • However, the default behavior is for it not to be set in which case there is no restriction
    • This can be checked by either calling phpinfo() or by using ini_get("open_basedir")
    • You can change the setting either by editing your php.ini file or your httpd.conf file
  2. safe mode
    • if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
  3. allow_url_fopen and allow_url_include
    • this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
    • this can be checked with ini_get("allow_url_include") and set with ini_set("allow_url_include", "1")


Corner cases

If none of the above enabled to diagnose the problem, here are some special situations that could happen :


1. The inclusion of library relying on the include path

It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :

require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"

But then you still get the same kind of error.

This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.

For example, the Zend framework file mentioned before could have the following include :

include "Zend/Mail/Protocol/Exception.php" 

which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.

In such a case, the only practical solution is to add the directory to your include path.


2. SELinux

If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.

To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.

To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.

setenforce 0

If you no longer have the problem with SELinux turned off, then this is the root cause.

To solve it, you will have to configure SELinux accordingly.

The following context types will be necessary :

  • httpd_sys_content_t for files that you want your server to be able to read
  • httpd_sys_rw_content_t for files on which you want read and write access
  • httpd_log_t for log files
  • httpd_cache_t for the cache directory

For example, to assign the httpd_sys_content_t context type to your website root directory, run :

semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root

If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :

setsebool -P httpd_enable_homedirs 1

In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.


3. Symfony

If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache has been uploaded, or that cache hasn't been cleared.

You can test and fix this by running the following console command:

cache:clear


4. Non ACSII characters inside Zip file

Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as "é".

A potential solution is to wrap the file name in utf8_decode() before creating the target file.

Credits to Fran Cano for identifying and suggesting a solution to this issue

View content of H2 or HSQLDB in-memory database

You can expose it as a JMX feature, startable via JConsole:

@ManagedResource
@Named
public class DbManager {

    @ManagedOperation(description = "Start HSQL DatabaseManagerSwing.")
    public void dbManager() {
        String[] args = {"--url", "jdbc:hsqldb:mem:embeddedDataSource", "--noexit"};
        DatabaseManagerSwing.main(args);
    }
}

XML context:

<context:component-scan base-package="your.package.root" scoped-proxy="targetClass"/>
<context:annotation-config />
<context:mbean-server />
<context:mbean-export />

Object not found! The requested URL was not found on this server. localhost

You are not specified your project as right way.

  • So run your XAMPP control panel then start the apache and MySQL
  • Then note the ports.
  • For Example PORT 80: then you type your browser url as localhost:80\ press enter now your php basic Config page is visible.
  • Then create any folder on xampp\htdocs\YourFloderName Then create php file then save it and go to browser then type it localhost\YourFolderName now it listed the files click the file and it runs.

Add unique constraint to combination of two columns

And if you have lot insert queries but not wanna ger a ERROR message everytime , you can do it:

CREATE UNIQUE NONCLUSTERED INDEX SK01 ON dbo.Person(ID,Name,Active,PersonNumber) 
WITH(IGNORE_DUP_KEY = ON)

enter image description here

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

How to make a new List in Java

List is an interface like Set and has ArrayList and LinkedList as general purpose implementations.

We can create List as:

 List<String> arrayList = new ArrayList<>();
 List<String> linkedList = new LinkedList<>(); 

We can also create a fixed-size list as:

List<String> list = Arrays.asList("A", "B", "C");

We would almost always be using ArrayList opposed to LinkedList implementation:

  1. LinkedList uses a lot of space for objects and performs badly when we have lots of elements.
  2. Any indexed operation in LinkedList requires O(n) time compared to O(1) in ArrayList.
  3. Check this link for more information.

The list created by Arrays.asList above can not be modified structurally but its elements can still be modified.

Java 8

As per doc, the method Collections.unmodifiableList returns an unmodifiable view of the specified list. We can get it like:

Collections.unmodifiableList(Arrays.asList("A", "B", "C"));

Java 9

In case we are using Java 9 then:

List<String> list = List.of("A", "B");

Java 10

In case we are at Java 10 then the method Collectors.unmodifiableList will return an instance of truly unmodifiable list introduced in Java 9. Check this answer for more info about the difference in Collections.unmodifiableList vs Collectors.unmodifiableList in Java 10.

Speed tradeoff of Java's -Xms and -Xmx options

The -Xmx argument defines the max memory size that the heap can reach for the JVM. You must know your program well and see how it performs under load and set this parameter accordingly. A low value can cause OutOfMemoryExceptions or a very poor performance if your program's heap memory is reaching the maximum heap size. If your program is running in dedicated server you can set this parameter higher because it wont affect other programs.

The -Xms argument sets the initial heap memory size for the JVM. This means that when you start your program the JVM will allocate this amount of memory instantly. This is useful if your program will consume a large amount of heap memory right from the start. This avoids the JVM to be constantly increasing the heap and can gain some performance there. If you don't know if this parameter is going to help you, don't use it.

In summary, this is a compromise that you have to decide based only in the memory behavior of your program.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

The request failed or the service did not respond in a timely fashion?

If you recently changed the password associated with the service account:

  1. Start SQL Server Configuration Manager.
  2. Select SQL Server Services in the left pane.
  3. Right click the service you are trying to start in the right pane and click Properties.
  4. Enter the new Password and Confirm password.

Image inside div has extra space below the image

I found it works great using display:block; on the image and vertical-align:top; on the text.

_x000D_
_x000D_
.imagebox {_x000D_
    width:200px;_x000D_
    float:left;_x000D_
    height:88px;_x000D_
    position:relative;_x000D_
    background-color: #999;_x000D_
}_x000D_
.container {_x000D_
    width:600px;_x000D_
    height:176px;_x000D_
    background-color: #666;_x000D_
    position:relative;_x000D_
    overflow:hidden;_x000D_
}_x000D_
.text {_x000D_
    color: #000;_x000D_
    font-size: 11px;_x000D_
    font-family: robotomeduim, sans-serif;_x000D_
    vertical-align:top;_x000D_
    _x000D_
}_x000D_
_x000D_
.imagebox img{ display:block;}
_x000D_
<div class="container">_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or you can edit the code a JS FIDDLE

Refresh an asp.net page on button click

Page reload can be done using javascript code. Use either a HTML button and implement it like...

<input type="button" value="Reload Page" onClick="document.location.reload(true)">

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

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

My issue was that I was trying to give my ssh key a SPECIFIC NAME every time I entered ssh-keygen on my mac terminal.

I solved the issue by just leaving the name that "ssh-keygen" generates = id_rsa. You'll end up with 2 keys in your .ssh folder on a mac, id_rsa, which is your private key, and the id_rsa.pub, which is your public key. Then I copied and saved the code from id_rsa.pub into my GitHub account settings, and that was it. Problem solved.

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

Struct Constructor in C++?

struct HaveSome
{
   int fun;
   HaveSome()
   {
      fun = 69;
   }
};

I'd rather initialize inside the constructor so I don't need to keep the order.

How to add a touch event to a UIView?

You can achieve this by adding Gesture Recogniser in your code.

Step 1: ViewController.m:

// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] 
                                          initWithTarget:self 
                                          action:@selector(handleTap:)];
gesRecognizer.delegate = self;

// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer]; 

Step 2: ViewController.m:

// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
   NSLog(@"Tapped");
}

NOTE: here yourView in my case was @property (strong, nonatomic) IBOutlet UIView *localView;

EDIT: *localView is the white box in Main.storyboard from below

enter image description here

enter image description here

SQL Order By Count

Try using below Query:

SELECT
    GROUP,
    COUNT(*) AS Total_Count
FROM
    TABLE
GROUP BY
    GROUP
ORDER BY
    Total_Count DESC

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


How to construct a REST API that takes an array of id's for the resources

As much as I prefer this approach:-

    api.com/users?id=id1,id2,id3,id4,id5

The correct way is

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

or

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

This is how rack does it. This is how php does it. This is how node does it as well...

Function for Factorial in Python

Non-recursive solution, no imports:

def factorial(x):
    return eval(' * '.join(map(str, range(1, x + 1))))

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

Clear contents of cells in VBA using column reference

To clear all rows that have data I use two variables like this. I like this because you can adjust it to a certain range of columns if you need to. Dim CRow As Integer Dim LastRow As Integer

CRow = 1
LastRow = Cells(Rows.Count, 3).End(xlUp).Row

Do Until CRow = LastRow + 1
    Cells(CRow, 1).Value = Empty
    Cells(CRow, 2).Value = Empty
    Cells(CRow, 3).Value = Empty
    Cells(CRow, 4).Value = Empty
    CRow = CRow + 1
Loop

How to exclude a directory from ant fileset, based on directories contents

works for me:

<target name="build2-jar" depends="compile" >
   <jar destfile="./myJjar.jar">
        <fileset dir="./WebContent/WEB-INF/lib" includes="hibernate*.jar,mysql*.jar" />
        <fileset dir="./WebContent/WEB-INF/classes" excludes="**/controlador/*.class,**/form/*.class,**/orm/*.class,**/reporting/*.class,**/org/w3/xmldsig/*.class"/>
   </jar>

How do I create JavaScript array (JSON format) dynamically?

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

Stash just a single file

Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use

git checkout -- <file>

Note that git stash is just a quicker and simple alternative to branching and doing stuff.

Converting BigDecimal to Integer

Well, you could call BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

You can then either explicitly call Integer.valueOf(int) or let auto-boxing do it for you if you're using a sufficiently recent version of Java.

How to override application.properties during production in Spring-Boot?

From Spring Boot 2, you will have to use

--spring.config.additional-location=production.properties

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use This code ..to change action bar background color. open "res/values/themes.xml" (if not present, create it) and add

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActionBarTheme"
       parent="@android:style/Theme.Holo.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
 <!-- ActionBar styles -->
<style name="MyActionBar"
       parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/actionbar_background</item>
</style>

Note : this code works for android 3.0 and higher versions only

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

Just type

unlink [SOCKET NAME]

in the terminal, then the error should no longer exist.

WAMP 403 Forbidden message on Windows 7

Remember to remove dummy elements in httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

How can I completely remove TFS Bindings

In visual studio 2015,

  1. Unbind the solution and project by File->Source Control->Advanced->Change Source Control
  2. Remove the cache in C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\6.0

Combine two tables that have no common fields

try:

select * from table 1 left join table2 as t on 1 = 1;

This will bring all the columns from both the table.

How do I temporarily disable triggers in PostgreSQL?

PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER command, which seems to do what I need. See ALTER TABLE.

How do I remove the height style from a DIV using jQuery?

To reset the height of the div, just try

$("#someDiv").height('auto');

JavaScript unit test tools for TDD

The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.

Message 'src refspec master does not match any' when pushing commits in Git

One reason for this month is probably be: github has rename default "master" branch to "main" branch. So, use git push origin main instead.

Using Python String Formatting with Lists

The same as @neobot's answer but a little more modern and succinct.

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

iOS: Multi-line UILabel in Auto Layout

Expand your label set number of lines to 0 and also more importantly for auto layout set height to >= x. Auto layout will do the rest. You may also contain your other elements based on previous element to correctly position then.

auto layout

Android: ScrollView vs NestedScrollView

NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView.

But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed. So to bring back smooth scrolling there's trick:

ViewCompat.setNestedScrollingEnabled(recyclerView, false);

put above line after setting adapter for recyclerView.

Access Tomcat Manager App from different host

Following two configuration is working for me.

1 .tomcat-users.xml details
--------------------------------
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <role rolename="tomcat"/>


  <user  username="tomcat"  password="tomcat" roles="tomcat"/>

  <user  username="admin"  password="admin" roles="admin-gui"/>

  <user  username="adminscript"  password="adminscrip" roles="admin-script"/>

  <user  username="tomcat"  password="s3cret" roles="manager-gui"/>
  <user  username="status"  password="status" roles="manager-status"/>

  <user  username="both"    password="both"   roles="manager-gui,manager-status"/>

  <user  username="script"  password="script" roles="manager-script"/>
  <user  username="jmx"     password="jmx"    roles="manager-jmx"/>

2. context.xml  of <tomcat>/webapps/manager/META-INF/context.xml and 
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>

CSV with comma or semicolon?

CSV is a standard format, outlined in RFC 4180 (in 2005), so there IS no lack of a standard. https://www.ietf.org/rfc/rfc4180.txt

And even before that, the C in CSV has always stood for Comma, not for semiColon :(

It's a pity Microsoft keeps ignoring that and is still sticking to the monstrosity they turned it into decades ago (yes, I admit, that was before the RFC was created).

  • One record per line, unless a newline occurs within quoted text (see below).
  • COMMA as column separator. Never a semicolon.
  • PERIOD as decimal point in numbers. Never a comma.
  • Text containing commas, periods and/or newlines enclosed in "double quotation marks".
  • Only if text is enclosed in double quotation marks, such quotations marks in the text escaped by doubling. These examples represent the same three fields:

    1,"this text contains ""quotation marks""",3

    1,this text contains "quotation marks",3

The standard does not cover date and time values, personally I try to stick to ISO 8601 format to avoid day/month/year -- month/day/year confusion.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

Changing cell color using apache poi

checkout the example here

http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java

style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());

bundle install fails with SSL certificate verification error

I was able to track this down to the fact that the binaries that rvm downloads do not play nice with OS X's OpenSSL, which is old and is no longer used by the OS.

The solution for me was to force compilation when installing Ruby via rvm:

rvm reinstall --disable-binary 2.2

Removing legend on charts with chart.js v2

You can change default options by using Chart.defaults.global in your javascript file. So you want to change legend and tooltip options.

Remove legend

Chart.defaults.global.legend.display = false;

Remove Tooltip

Chart.defaults.global.tooltips.enabled = false;

Here is a working fiddler.

How can I change the language (to english) in Oracle SQL Developer?

You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf:

Just add the JVM Option:

AddVMOption -Duser.language=en

The file will be like this:

enter image description here

Accessing MP3 metadata with Python

Just additional information to you guys:

take a look at the section "MP3 stuff and Metadata editors" in the page of PythonInMusic.

turn typescript object into json string

Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.

const temp = [];
const t = {
    name: "name",
    etc: [
        {
            a: 0,
        },
    ],
};
for (let i = 0; i < 3; i++) {
    const bla = Object.assign({}, t);
    bla.name = bla.name + i;
    bla.etc[0].a = i;
    temp.push(bla);
}

console.log(JSON.stringify(temp));

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

Parsing HTML using Python

I guess what you're looking for is pyquery:

pyquery: a jquery-like library for python.

An example of what you want may be like:

from pyquery import PyQuery    
html = # Your HTML CODE
pq = PyQuery(html)
tag = pq('div#id') # or     tag = pq('div.class')
print tag.text()

And it uses the same selectors as Firefox's or Chrome's inspect element. For example:

the element selector is 'div#mw-head.noprint'

The inspected element selector is 'div#mw-head.noprint'. So in pyquery, you just need to pass this selector:

pq('div#mw-head.noprint')

Find a line in a file and remove it

This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close(); 
reader.close(); 
boolean successful = tempFile.renameTo(inputFile);

Normalize columns of pandas data frame

You can use the package sklearn and its associated preprocessing utilities to normalize the data.

import pandas as pd
from sklearn import preprocessing

x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pd.DataFrame(x_scaled)

For more information look at the scikit-learn documentation on preprocessing data: scaling features to a range.

How to stop default link click behavior with jQuery

$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I changed :

compile 'com.google.android.gms:play-services:9.0.0'

compile 'com.google.android.gms:play-services-auth:9.0.0'

to :

compile 'com.google.android.gms:play-services-maps:9.0.0'

compile 'com.google.android.gms:play-services-auth:9.0.0'

Jquery in React is not defined

Isn't easier than doing like :

1- Install jquery in your project:

yarn add jquery

2- Import jquery and start playing with DOM:

import $ from 'jquery';

Clear text in EditText when entered

First you need to call setContentView(R.layout.main) then all other initialization.

Please try below Code.

public class Trackfolio extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    public EditText editText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        editText = (EditText) findViewById(R.id.editText1);
        editText.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        editText.getText().clear(); //or you can use editText.setText("");
    }
}

Why is pydot unable to find GraphViz's executables in Windows 8?

Some things to know about graphviz:

  1. graphviz is not only a python module, it's also a standalone program. I believe you need both to make graphviz to work.
  2. The standalone graphviz program was originally developed by AT&T, open sourced, then abandoned. The current maintainers of the package forgot to include Windows registry entries so Python can find the program executable.
  3. Line 620 of pydotplus\graphviz.py includes a backup path to look for graphviz if it isn't found in the registry. It uses the old ATT file path. Update the file path to what is on your machine (you will need to have administrator privileges) and graphviz should work with pydotplus.

Example:

# Just in case, try the default... path = r"C:\Program Files (x86)\Graphviz2.38\bin"

How do I exclude all instances of a transitive dependency when using Gradle?

In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:

compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
    exclude group: 'org.apache.httpcomponents', module: ''
    exclude group: 'org.slf4j', module: ''
}

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']
]);

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']
]);

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation


Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

    public function getShow($id)
    {
        // get request to 'users/show/{id}'
    }

    public function postStore()
    {
        // POST request to 'users/store'
    }

}

Implicit Controller documentation


It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

How to do this in Laravel, subquery where in

The script is tested in Laravel 5.x and 6.x. The static closure can improve performance in some cases.

Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
            ->whereIn('id', static function ($query) {
                $query->select(['product_id'])
                    ->from((new ProductCategory)->getTable())
                    ->whereIn('category_id', [15, 223]);
            })
            ->where('active', 1)
            ->get();

generates the SQL

SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products` 
WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE 
`category_id` IN (?, ?)) AND `active` = ?