Programs & Examples On #Acl

An access control list (ACL), with respect to a computer file system, is a list of permissions attached to an object.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

Here's how to do it using default ACLs, at least under Linux.

First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl option. In that case, add the option to your /etc/fstab. For example, if the directory is located on your root filesystem:

/dev/mapper/qz-root   /    ext3    errors=remount-ro,acl   0  1

Then remount it:

mount -oremount /

Now, use the following command to set the default ACL:

setfacl -dm u::rwx,g::rwx,o::r /shared/directory

All new files in /shared/directory should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp, tar, and rsync will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.

Hope this helps!

Spring Security with roles and permissions

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

My problem was the system virtualenv version.

When I created an env with python3 venv everything worked. But when I used virtualenv (by default with python2.7) to create an env I receive those error messages.

In the virtualenv created the pip version was 1.5.6, but my system pip version was 10.0.1

Then I ran (outside any env):

pip install virtualenv --upgrade

It upgraded virtualenv to version 16.0.0 and now my pip install in the envs created with virtualenv and python2.7 work flawlessly. Also, the pip version inside the env is now 10.0.1.

Before upgrade:

Ignoring NaNs with str.contains

I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.

import pandas as pd
import numpy as np

df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

newdf = df.loc[df['a'].str.contains('foo') == True]

Works with or without .loc.

I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True or False. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

How to apply slide animation between two activities in Android?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);

         new Handler().postDelayed(new Runnable() {
             public void run() {

                     /* Create an intent that will start the main activity. */
                     Intent mainIntent = new Intent(SplashScreen.this,
                             ConnectedActivity.class);
                     mainIntent.putExtra("id", "1");

                     //SplashScreen.this.startActivity(mainIntent);
                     startActivity(mainIntent);
                     /* Finish splash activity so user cant go back to it. */
                     SplashScreen.this.finish();

                     /* Apply our splash exit (fade out) and main
                        entry (fade in) animation transitions. */
                     overridePendingTransition(R.anim.mainfadein,R.anim.splashfadeout);
             }
     }, SPLASH_DISPLAY_TIME);   
    }

How to count the number of letters in a string without the spaces?

I found this is working perfectly

str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))

Abstraction VS Information Hiding VS Encapsulation

It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/.

abstraction

  1. view of an object that focuses on the information relevant to a particular purpose and ignores the remainder of the information
  2. process of formulating a view
  3. process of suppressing irrelevant detail to establish a simplified model, or the result of that process

information hiding

  1. software development technique in which each module's interfaces reveal as little as possible about the module's inner workings and other modules are prevented from using information about the module that is not in the module's interface specification
  2. containment of a design or implementation decision in a single module so that the decision is hidden from other modules

encapsulation

  1. software development technique that consists of isolating a system function or a set of data and operations on those data within a module and providing precise specifications for the module
  2. concept that access to the names, meanings, and values of the responsibilities of a class is entirely separated from access to their realization
  3. idea that a module has an outside that is distinct from its inside, that it has an external interface and an internal implementation

How to round up value C# to the nearest integer?

Another option:

string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33

string[] valStr = strVal.Split('.');

int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);

if (rightSide > 0)
    leftSide = leftSide + 1;


return (leftSide);

Short circuit Array.forEach like calling break

var Book = {"Titles":[                          
    {
    "Book3" : "BULLETIN 3"
    }   
    ,
    {
    "Book1" : "BULLETIN 1"
    }
    ,
    {
    "Book2" : "BULLETIN 2"
    }    
]}

var findbystr = function(str) { 
    var return_val;
    Book.Titles.forEach(function(data){ 
        if(typeof data[str] != 'undefined')
        {
            return_val = data[str];
        } 
    }, str) 

    return return_val;
}

book = findbystr('Book1');
console.log(book);

How to create an instance of System.IO.Stream stream

Stream stream = new MemoryStream();

you can use MemoryStream

Reference: MemoryStream

How do I copy an entire directory of files into an existing directory using Python?

Here's a solution that's part of the standard library:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

See this similar question.

Copy directory contents into a directory with python

Sort columns of a dataframe by column name

So to have a specific column come first, then the rest alphabetically, I'd propose this solution:

test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]

How to simulate a click by using x,y coordinates in JavaScript?

This is just torazaburo's answer, updated to use a MouseEvent object.

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);

    el.dispatchEvent(ev);
}

How do you get current active/default Environment profile programmatically in Spring?

And if you neither want to use @Autowire nor injecting @Value you can simply do (with fallback included):

System.getProperty("spring.profiles.active", "unknown");

This will return any active profile (or fallback to 'unknown').

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Change MySQL default character set to UTF-8 in my.cnf?

On MySQL 5.5 I have in my.cnf

[mysqld] 
init_connect='SET collation_connection = utf8_unicode_ci' 
init_connect='SET NAMES utf8' 
character-set-server=utf8 
collation-server=utf8_unicode_ci 
skip-character-set-client-handshake

Result is

mysql> show variables like "%character%";show variables like "%collation%";

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database   | utf8_unicode_ci |
| collation_server     | utf8_unicode_ci |
+----------------------+-----------------+
3 rows in set (0.00 sec)

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

How Big can a Python List Get?

In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system.

In addition, the list methods / functions should continue to work despite the size of the list.

If you care about performance, it might be worthwhile to look into a library such as NumPy.

GIT: Checkout to a specific folder

If you're working under your feature and don't want to checkout back to master, you can run:

cd ./myrepo

git worktree add ../myrepo_master master

git worktree remove ../myrepo_master

It will create ../myrepo_master directory with master branch commits, where you can continue work

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

jQuery multiple events to trigger the same function

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

How do you attach and detach from Docker's process?

I think this should depend on the situation.Take the following container as an example:

# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         5 seconds ago       Up 4 seconds                            serene_goldstine

(1) Use "docker attach" to attach the container:

Since "docker attach" will not allocate a new tty, but reuse the original running tty, so if you run exit command, it will cause the running container exit:

# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         39 minutes ago      Exited (0) 3 seconds ago                       serene_goldstine

So unless you really want to make running container exit, you should use Ctrl+p + Ctrl+q.

(2) Use "docker exec"

Since "docker exec" will allocate a new tty, so I think you should use exit instead of Ctrl+p + Ctrl+q.

The following is executing Ctrl+p + Ctrl+q to quit the container:

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss   04:03   0:00 bash
root        28  0.0  0.0  15564  1148 ?        R+   04:03   0:00 ps -aux
root@91262536f7c9:/# echo $$
15

Then login container again, you will see the bash process in preavious docker exec command is still alive (PID is 15):

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss+  04:03   0:00 bash
root        29  0.0  0.0  18164  1888 ?        Ss   04:04   0:00 bash
root        42  0.0  0.0  15564  1148 ?        R+   04:04   0:00 ps -aux
root@91262536f7c9:/# echo $$
29

Call a Class From another class

Suposse you have

Class1

public class Class1 {
    //Your class code above
}

Class2

public class Class2 {
}

and then you can use Class2 in different ways.

Class Field

public class Class1{
    private Class2 class2 = new Class2();
}

Method field

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2 class2 = new Class2();
         class2.invokeSomeMethod();
         //your actual code
    }
}

Static methods from Class2 Imagine this is your class2.

public class Class2 {
     public static void doSomething(){
     }
}

from class1 you can use doSomething from Class2 whenever you want

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2.doSomething();
         //your actual code
    }
}

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

Bootstrap 3 dropdown select

I found a better library which transform the normal <select> <option> to bootsrap button dropdown format.

https://developer.snapappointments.com/bootstrap-select/

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

How to read file from res/raw by name

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

List columns with indexes in PostgreSQL

Just do: \d table_name

But I'm not sure what do you mean that the information about columns is not there.

For example:

# \d pg_class
       Table "pg_catalog.pg_class"
     Column      |   Type    | Modifiers
-----------------+-----------+-----------
 relname         | name      | not null
 relnamespace    | oid       | not null
 reltype         | oid       | not null
 reloftype       | oid       | not null
 relowner        | oid       | not null
 relam           | oid       | not null
 relfilenode     | oid       | not null
 reltablespace   | oid       | not null
 relpages        | integer   | not null
 reltuples       | real      | not null
 reltoastrelid   | oid       | not null
 reltoastidxid   | oid       | not null
 relhasindex     | boolean   | not null
 relisshared     | boolean   | not null
 relistemp       | boolean   | not null
 relkind         | "char"    | not null
 relnatts        | smallint  | not null
 relchecks       | smallint  | not null
 relhasoids      | boolean   | not null
 relhaspkey      | boolean   | not null
 relhasexclusion | boolean   | not null
 relhasrules     | boolean   | not null
 relhastriggers  | boolean   | not null
 relhassubclass  | boolean   | not null
 relfrozenxid    | xid       | not null
 relacl          | aclitem[] |
 reloptions      | text[]    |
Indexes:
    "pg_class_oid_index" UNIQUE, btree (oid)
    "pg_class_relname_nsp_index" UNIQUE, btree (relname, relnamespace)

It clearly shows which columns given index is on this table.

How to import JSON File into a TypeScript file?

I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.

Add:

"resolveJsonModule": true,

To tsconfig.json

Import like:

import * as nameOfJson from 'path/to/file.json';

Stop ng test, start again.

Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

How to print full stack trace in exception?

Recommend to use LINQPad related nuget package, then you can use exceptionInstance.Dump().

enter image description here

For .NET core:

  • Install LINQPad.Runtime

For .NET framework 4 etc.

  • Install LINQPad

Sample code:

using System;
using LINQPad;

namespace csharp_Dump_test
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                dosome();
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }

        private static void dosome()
        {
            throw new Exception("Unable.");
        }
    }
}

Running result: enter image description here

LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

How to change color of the back arrow in the new material theme?

On compileSdkVersoin 25, you could do this:

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
     <item name="android:textColorSecondary">@color/your_color</item>
</style>

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

How can I disable a button on a jQuery UI dialog?

Looks like anyone, even in this linked question, have proposed this solution, similar to the first part of the answer given by Nick Craver:

$("#dialog").dialog({
    width: 480,
    height: "auto",
    buttons: [
        {
            id: "button-cancel",
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        },
        {
            id: "button-ok",
            text: "Ok",
            click: function() {
                $(this).dialog("close");
            }
        }
    ]
});

Then, elsewhere, you should be able to use the API for the jquery UI button:

$("#button-ok").button("disable");

How to compare 2 dataTables

If you have the tables in a database, you can make a full outer join to get the differences. Example:

select t1.Field1, t1.Field2, t2.Field1, t2.Field2
from Table1 t1
full outer join Table2 t2 on t1.Field1 = t2.Field1 and t1.Field2 = t2.Field2
where t1.Field1 is null or t2.Field2 is null

All records that are identical are filtered out. There is data either in the first two or the last two fields, depending on what table the record comes from.

Swift Alamofire: How to get the HTTP response status code

I needed to know how to get the actual error code number.

I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:

} .catch { (error) in

    guard let error = error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
}

Or if you need to get it from the response value follow @mbryzinski's answer

Alamofire ... { (response) in

    guard let error = response.result.error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
})

Remove all items from RecyclerView

On Xamarin.Android, It works for me and need change layout

 var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
 layout.SpanCount = GetItemPerRow(Context);
 recyclerView.SetAdapter(null);
 recyclerView.SetAdapter(adapter); //reset

How to insert a column in a specific position in oracle without dropping and recreating the table?

Amit-

I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:

CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;

Drop the table you want to add columns to:

DROP TABLE TABLE_TO_CHANGE;

It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".

Now insert the data back into the new table:

INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4) 
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;

When the data is inserted into your "new-old" table, you can drop the temp table.

DROP TABLE MY_TEMP_TABLE;

This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.

-CJ

How to split a single column values to multiple column values?

What you need is a split user-defined function. With that, the solution looks like

With SplitValues As
    (
    Select T.Name, Z.Position, Z.Value
        , Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
    From Table As T
        Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
    )
Select Name
    , FirstName.Value
    , Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
    Left Join SplitValues As SecondName
        On S2.Name = S1.Name
            And S2.Num = 2
    Left Join SplitValues As ThirdName
        On S2.Name = S1.Name
            And S2.Num = 3
Where FirstName.Num = 1

Here's a sample split function:

Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.

$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Therefore:

  1. You aren't passing JSON to the server. You're passing JSON to jQuery.
  2. Model binding happens in the same way it happens in any other case.

Cannot open solution file in Visual Studio Code

VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.

It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.

How to set background image in Java?

The answer will vary slightly depending on whether the application or applet is using AWT or Swing.

(Basically, classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT.)

In either case, the basic steps would be:

  1. Draw or load an image into a Image object.
  2. Draw the background image in the painting event of the Component you want to draw the background in.

Step 1. Loading the image can be either by using the Toolkit class or by the ImageIO class.

The Toolkit.createImage method can be used to load an Image from a location specified in a String:

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");

Similarly, ImageIO can be used:

Image img = ImageIO.read(new File("background.jpg");

Step 2. The painting method for the Component that should get the background will need to be overridden and paint the Image onto the component.

For AWT, the method to override is the paint method, and use the drawImage method of the Graphics object that is handed into the paint method:

public void paint(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

For Swing, the method to override is the paintComponent method of the JComponent, and draw the Image as with what was done in AWT.

public void paintComponent(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

Simple Component Example

Here's a Panel which loads an image file when instantiated, and draws that image on itself:

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel()
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage("background.jpg");
    }

    public void paint(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
    }
}

For more information on painting:

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

Python idiom to return first item or None

Using the and-or trick:

a = get_list()
return a and a[0] or None

AngularJS: Basic example to use authentication in Single Page Application

I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

ng-login Github repo

Plunker

I'll try to explain as good as possible, hope I help some of you out there:

(1) app.js: Creation of authentication constants on app definition

var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
    all : '*',
    admin : 'admin',
    editor : 'editor',
    guest : 'guest'
}).constant('AUTH_EVENTS', {
    loginSuccess : 'auth-login-success',
    loginFailed : 'auth-login-failed',
    logoutSuccess : 'auth-logout-success',
    sessionTimeout : 'auth-session-timeout',
    notAuthenticated : 'auth-not-authenticated',
    notAuthorized : 'auth-not-authorized'
})

(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.

angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS', 
function($http, $rootScope, $window, Session, AUTH_EVENTS) {

authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]

return authService;
} ]);

(3) Session: A singleton to keep user data. The implementation here depends on you.

angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {

    this.create = function(user) {
        this.user = user;
        this.userRole = user.userRole;
    };
    this.destroy = function() {
        this.user = null;
        this.userRole = null;
    };
    return this;
});

(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.

<body ng-controller="ParentController">
[...]
</body>

(5) Access control: To deny access on certain routes 2 steps have to be implemented:

a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).

.config(function ($stateProvider, USER_ROLES) {
  $stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/index.html',
    data: {
      authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
    }
  });
})

b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.

$rootScope.$on('$stateChangeStart', function (event, next) {
    var authorizedRoles = next.data.authorizedRoles;
    if (!Auth.isAuthorized(authorizedRoles)) {
      event.preventDefault();
      if (Auth.isAuthenticated()) {
        // user is not allowed
        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      } else {
        // user is not logged in
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
      }
    }
});

(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.

angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
    return {
        responseError : function(response) {
            $rootScope.$broadcast({
                401 : AUTH_EVENTS.notAuthenticated,
                403 : AUTH_EVENTS.notAuthorized,
                419 : AUTH_EVENTS.sessionTimeout,
                440 : AUTH_EVENTS.sessionTimeout
            }[response.status], response);
            return $q.reject(response);
        }
    };
} ]);

P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.

P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.

How to remove blank lines from a Unix file

with awk

awk 'NF > 0' filename

Does it make sense to use Require.js with Angular.js?

Yes it makes sense to use angular.js along with require.js wherein you can use require.js for modularizing components.

There is a seed project which uses both angular.js and require.js.

Finding the number of days between two dates

Using this simple function. Declare function

<?php
function dateDiff($firstDate,$secondDate){
    $firstDate = strtotime($firstDate);
    $secondDate = strtotime($secondDate);

    $datediff = $firstDate - $secondDate;
    $output = round($datediff / (60 * 60 * 24));
    return $output;
}
?>

and call this function like this where you want

<?php
    echo dateDiff("2018-01-01","2018-12-31");    

// OR

    $firstDate = "2018-01-01";
    $secondDate = "2018-01-01";
    echo dateDiff($firstDate,$secondDate);    
?>

Jersey client: How to add a list as query parameter

GET Request with JSON Query Param

package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientGET {

    public static void main(String[] args) {
        try {               

            String BASE_URI="http://vaquarkhan.net:8080/khanWeb";               
            Client client = Client.create();    
            WebResource webResource = client.resource(BASE_URI);

            ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

            /*if (response.getStatus() != 200) {
               throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
            }
*/
            String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
            //String output = response.getEntity(String.class);

            System.out.println("Output from Server .... \n");
            System.out.println(output);                         

        } catch (Exception e) {

            e.printStackTrace();    
        }    
    }    
}

Post Request :

package com.rest.jersey.jerseyclient;

import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClientPOST {

    public static void main(String[] args) {
        try {

            KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");                      

            ClientConfig clientConfig = new DefaultClientConfig();

            clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

            Client client = Client.create(clientConfig);

               // final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
               // client.addFilter(authFilter);
               // client.addFilter(new LoggingFilter());

            //
            WebResource webResource = client
                    .resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");

              ClientResponse response = webResource.accept("application/json")
                .type("application/json").put(ClientResponse.class, khanDTOInput);


            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
            }

            String output = response.getEntity(String.class);

            System.out.println("Server response .... \n");
            System.out.println(output);

        } catch (Exception e) {

            e.printStackTrace();

        }    
    }    
}

How do I check if a string contains a specific word?

Check if string contains specific words?

This means the string has to be resolved into words (see note below).

One way to do this and to specify the separators is using preg_split (doc):

<?php

function contains_word($str, $word) {
  // split string into words
  // separators are substrings of at least one non-word character
  $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);

  // now the words can be examined each
  foreach ($arr as $value) {
    if ($value === $word) {
      return true;
    }
  }
  return false;
}

function test($str, $word) {
  if (contains_word($str, $word)) {
    echo "string '" . $str . "' contains word '" . $word . "'\n";
  } else {
    echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
  }
}

$a = 'How are you?';

test($a, 'are');
test($a, 'ar');
test($a, 'hare');

?>

A run gives

$ php -f test.php                   
string 'How are you?' contains word 'are' 
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'

Note: Here we do not mean word for every sequence of symbols.

A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl " word ". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (..)

How do I create a MongoDB dump of my database?

Backup/Restore Mongodb with timing.

Backup:

sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`

--db argument for databse name

--out argument for path of output

Restore:

sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/

--drop argument for drop databse before restore

Timing:

You can use crontab for timing backup:

sudo crontab -e

It opens with editor(e.g. nano)

3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`

backup every day at 03:03 AM

Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:

3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;

delete all the backups older than 7 days

Good Luck.

ref: https://www.digitalocean.com/community/tutorials/how-to-back-up-restore-and-migrate-a-mongodb-database-on-ubuntu-14-04

Http 415 Unsupported Media type error with JSON

If you are using AJAX jQuery Request this is a must to apply. If not it will throw you 415 Error.

dataType: "json",
contentType:'application/json'

Could not insert new outlet connection: Could not find any information for the class named

Here are some things that can fix this (in increasing order of difficulty):

  • Clean the project (Product > Clean)
  • Manually paste in

    @IBOutlet weak var viewName: UIView!
    // or
    @IBAction func viewTapped(_ sender: Any) { }
    

    and control drag to it. (Change type as needed.) Also see this.

  • Completely close Xcode and restart your project.

  • Delete the Derived Data folder (Go to Xcode > Preferences > Locations and click the gray arrow by the Derived Data folder. Then delete your project folder.)
  • Click delete on the class, remove reference (not Move to Trash), and add it back again. (see this answer)

How to embed small icon in UILabel

You can do this with iOS 7's text attachments, which are part of TextKit. Some sample code:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];

myLabel.attributedText = myString;

Forcing anti-aliasing using css: Is this a myth?

No, there's not really any way to control this as a web developer.

Small exceptions are that you can do some fake forcing of anti-aliasing by using Flash through sIFR, and some browsers won't anti-alias bitmap/pixel fonts (as they shouldn't, more info: Anti-Aliasing / Anti-Anti-Aliasing).

Also, as Daniel mentioned, it's ideal to be using em units for all fonts, see The Incredible Em & Elastic Layouts with CSS for more information about this.

What's the best three-way merge tool?

Meld Diff Viewer

I have had only good experiences working with Meld. I use it when I have to do messy code merges between branches. It is simple to use and has a clean interface.

  • Open Source
  • Linux, Windows and MacOS Supported
  • Multiple File Diff
  • Three-way Compare Support

In Ubuntu, install is as simple as: sudo apt-get install meld

enter image description here

Write in body request with HttpClient

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

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

pay attention to the Exceptions.

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

How to add files/folders to .gitignore in IntelliJ IDEA?

right click on the project create a file with name .ignore, then you can see that file opened.

at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).

Now when ever you give a right click on the file or project you can see the option call add to .ignore

Use IntelliJ to generate class diagram

Try Ctrl+Alt+U

Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S

How to make matrices in Python?

If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:

  mat = [[input() for i in range (col)] for j in range (row)]

and then enter the values you want.

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

Fixing broken UTF-8 encoding

In my case, I found out by using "mb_convert_encoding" that the previous encoding was iso-8859-1 (which is latin1) then I fixed my problem by using an sql query :

UPDATE myDB.myTable SET myColumn = CAST(CAST(CONVERT(myColumn USING latin1) AS binary) AS CHAR)

However, it is stated in the mysql documentations that conversion may be lossy if the column contains characters that are not in both character sets.

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

Check if a string matches a regex in Bash script

In bash version 3 you can use the '=~' operator:

if [[ "$date" =~ ^[0-9]{8}$ ]]; then
    echo "Valid date"
else
    echo "Invalid date"
fi

Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2

How to check if BigDecimal variable == 0 in java?

Just want to share here some helpful extensions for kotlin

fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
fun BigDecimal.isOne() = compareTo(BigDecimal.ONE) == 0
fun BigDecimal.isTen() = compareTo(BigDecimal.TEN) == 0

How can I switch views programmatically in a view controller? (Xcode, iPhone)

Swift 3.0 in

one view controller to secondviewcontroller go:

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MsgViewController") as! MsgViewController
        self.navigationController?.pushViewController(loginVC, animated: true)

2nd viewcontroller to 1stviewcontroller(back)for: back button on action event:-

self.navigationController?.popViewController(animated:true)

3rdviewcontroller to 1st viewcontroller jump for

self.navigationController?.popToRootViewController(animated:true)

and most important storyboard in navigation bar unclicked make sure than this back action perform

How to show DatePickerDialog on Button click?

    final Calendar newCalendar = Calendar.getInstance();
    final DatePickerDialog  StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    Calendar newDate = Calendar.getInstance();
                    newDate.set(year, monthOfYear, dayOfMonth);
                    activitydate.setText(dateFormatter.format(newDate.getTime()));
                }
    
            }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    
      btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override   public void onClick(View v) {
         StartTime.show():    
     });

How to remove non-alphanumeric characters?

here's a really simple regex for that:

\W|_

and used as you need it (with a forward / slash delimiter).

preg_replace("/\W|_/", '', $string);

Test it here with this great tool that explains what the regex is doing:

http://www.regexr.com/

How to add dividers and spaces between items in RecyclerView?

Here's my lazy approach but it works: wrap the CardView in a layout and set a padding/margin on the parent layout to mimic the divider, and force the normal divider to null

list_item.xml

<LinearLayout
    android:id="@+id/entry_item_layout_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="<divider_size>" > // this is the divider
    <CardView
        android:layout_width="<width_size>"
        android:layout_height="<height_size>">
        ...
    </CardView>
</LinearLayout

list.xml

<RecyclerView
 android:divider="@null"
 android:layout_width="<width_size>"
 android:layout_height="<height_size>"
 ...
/>

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

I will say It 's just shorthand syntax for get reference of html element during debugging time , normaly these kind of task will perform by these method

document.getElementById , document.getElementsByClassName , document.querySelector

so clicking on an html element and getting a reference variable ($0) in console is a huge time saving during the day

how to filter out a null value from spark dataframe

A good solution for me was to drop the rows with any null values:

Dataset<Row> filtered = df.filter(row => !row.anyNull);

In case one is interested in the other case, just call row.anyNull. (Spark 2.1.0 using Java API)

Can a CSS class inherit one or more other classes?

If you want a more powerful text preprocessor than LESS, check out PPWizard:

http://dennisbareis.com/ppwizard.htm

Warning the website is truly hideous and there's a small learning curve, but it's perfect for building both CSS and HTML code via macros. I've never understood why more web coders don't use it.

How to find out if a file exists in C# / .NET?

I use WinForms and my way to use File.Exists(string path) is the next one:

public bool FileExists(string fileName)
{
    var workingDirectory = Environment.CurrentDirectory;
    var file = $"{workingDirectory}\{fileName}";
    return File.Exists(file);
}

fileName must include the extension like myfile.txt

How to round up with excel VBA round()?

Try the RoundUp function:

Dim i As Double

i = Application.WorksheetFunction.RoundUp(Cells(1, 1).Value * Cells(1, 2).Value, 2)

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

Writing an mp4 video using python opencv

There are some things to change in your code:

  1. Change the name of your output to 'output.mp4' (change to .mp4)
  2. I had the the same issues that people have in the comments, so I changed the fourcc to 0x7634706d: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))

How to build and use Google TensorFlow C++ api

I use a hack/workaround to avoid having to build the whole TF library myself (which saves both time (it's set up in 3 minutes), disk space, installing dev dependencies, and size of the resulting binary). It's officially unsupported, but works well if you just want to quickly jump in.

Install TF through pip (pip install tensorflow or pip install tensorflow-gpu). Then find its library _pywrap_tensorflow.so (TF 0.* - 1.0) or _pywrap_tensorflow_internal.so (TF 1.1+). In my case (Ubuntu) it's located at /usr/local/lib/python2.7/dist-packages/tensorflow/python/_pywrap_tensorflow.so. Then create a symlink to this library called lib_pywrap_tensorflow.so somewhere where your build system finds it (e.g. /usr/lib/local). The prefix lib is important! You can also give it another lib*.so name - if you call it libtensorflow.so, you may get better compatibility with other programs written to work with TF.

Then create a C++ project as you are used to (CMake, Make, Bazel, whatever you like).

And then you're ready to just link against this library to have TF available for your projects (and you also have to link against python2.7 libraries)! In CMake, you e.g. just add target_link_libraries(target _pywrap_tensorflow python2.7).

The C++ header files are located around this library, e.g. in /usr/local/lib/python2.7/dist-packages/tensorflow/include/.

Once again: this way is officially unsupported and you may run in various issues. The library seems to be statically linked against e.g. protobuf, so you may run in odd link-time or run-time issues. But I am able to load a stored graph, restore the weights and run inference, which is IMO the most wanted functionality in C++.

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

how to compare two elements in jquery

Random AirCoded example of testing "set equality" in jQuery:

$.fn.isEqual = function($otherSet) {
  if (this === $otherSet) return true;
  if (this.length != $otherSet.length) return false;
  var ret = true;
  this.each(function(idx) { 
    if (this !== $otherSet[idx]) {
       ret = false; return false;
    }
  });
  return ret;
};

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];

console.log($(b).isEqual(a));

How to switch to the new browser window, which opens after click on the button?

This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window

String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
   for(String windowHandle  : handles)
       {
       if(!windowHandle.equals(parentWindow))
          {
          driver.switchTo().window(windowHandle);
         <!--Perform your operation here for new window-->
         driver.close(); //closing child window
         driver.switchTo().window(parentWindow); //cntrl to parent window
          }
       }

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        {
        AssetID = x.AssetID,
        Status = xx.Online ?? false
        };

Ruby: Calling class method from instance

If you have access to the delegate method you can do this:

[20] pry(main)> class Foo
[20] pry(main)*   def self.bar
[20] pry(main)*     "foo bar"
[20] pry(main)*   end  
[20] pry(main)*   delegate :bar, to: 'self.class'
[20] pry(main)* end  
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"

Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:

[1] pry(main)> class Foo
[1] pry(main)*   module AvailableToClassAndInstance
[1] pry(main)*     def bar
[1] pry(main)*       "foo bar"
[1] pry(main)*     end  
[1] pry(main)*   end  
[1] pry(main)*   include AvailableToClassAndInstance
[1] pry(main)*   extend AvailableToClassAndInstance
[1] pry(main)* end  
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"

A word of caution:

Don't just randomly delegate everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.

Task.Run with Parameter(s)?

From now you can also :

Action<int> action = (o) => Thread.Sleep(o);
int param = 10;
await new TaskFactory().StartNew(action, param)

Difference between webdriver.get() and webdriver.navigate()

driver.get() : It's used to go to the particular website , But it doesn't maintain the browser History and cookies so , we can't use forward and backward button , if we click on that , page will not get schedule

driver.navigate() : it's used to go to the particular website , but it maintains the browser history and cookies, so we can use forward and backward button to navigate between the pages during the coding of Testcase

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

Open Source Alternatives to Reflector?

2 options I know of.

  • CCI
  • Mono Cecil

These wont give you C# though.

gdb: how to print the current line or find the current line number?

I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.

Try compiling with -g3 remove any optimization flag. Then it might work. HTH!

Iterate two Lists or Arrays with one ForEach statement in C#

You can also do the following:

var i = 0;
foreach (var itemA in listA)
{
  Console.WriteLine(itemA + listB[i++]);
}

Note: the length of listA must be the same with listB.

Check if a string is html or not

/<\/?[^>]*>/.test(str) Only detect whether it contains html tags, may be a xml

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

CSS - How to Style a Selected Radio Buttons Label?

You are using an adjacent sibling selector (+) when the elements are not siblings. The label is the parent of the input, not it's sibling.

CSS has no way to select an element based on it's descendents (nor anything that follows it).

You'll need to look to JavaScript to solve this.

Alternatively, rearrange your markup:

<input id="foo"><label for="foo">…</label>

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Why not inherit from List<T>?

It depends on the behaviour of your "team" object. If it behaves just like a collection, it might be OK to represent it first with a plain List. Then you might start to notice that you keep duplicating code that iterates on the list; at this point you have the option of creating a FootballTeam object that wraps the list of players. The FootballTeam class becomes the home for all the code that iterates on the list of players.

It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?

Encapsulation. Your clients need not know what goes on inside of FootballTeam. For all your clients know, it might be implemented by looking the list of players up in a database. They don't need to know, and this improves your design.

It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.

Exactly :) you will say footballTeam.Add(john), not footballTeam.List.Add(john). The internal list will not be visible.

Using "-Filter" with a variable

Try this:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

Multiple radio button groups in MVC 4 Razor

all you need is to tie the group to a different item in your model

@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")

@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

Interview question: Check if one string is a rotation of other string

Here is an O(n) and in place alghoritm. It uses < operator for the elements of the strings. It's not mine of course. I took it from here (The site is in polish. I stumbled upon it once in the past and I couldn't find something like that now in English, so I show what I have :)).

bool equiv_cyc(const string &u, const string &v)
{
    int n = u.length(), i = -1, j = -1, k;
    if (n != v.length()) return false;

    while( i<n-1 && j<n-1 )
    {
        k = 1;
        while(k<=n && u[(i+k)%n]==v[(j+k)%n]) k++;
        if (k>n) return true;
        if (u[(i+k)%n] > v[(j+k)%n]) i += k; else j += k;
    }
    return false;
}

Setting size for icon in CSS

this works for me try it.

height:1rem;
font-size: 3.75em;

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

TensorFlow not found using pip

If you're trying to install tensorflow in anaconda and it isn't working, then you may need to downgrade python version because only 3.6.x is currently supported while anaconda has the latest version.

  1. check python version: python --version

  2. if version > 3.6.x then follow step 3, otherwise stop, the problem may be somewhere else

  3. conda search python

  4. conda install python=3.6.6

  5. Check version again: python --version

  6. If version is correct, install tensorflow (step 7)

  7. pip install tensorflow

Read .doc file with python

Prerequisites :

install antiword : sudo apt-get install antiword

install docx : pip install docx

from subprocess import Popen, PIPE

from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
    cmd = ['antiword', file_path]
    p = Popen(cmd, stdout=PIPE)
    stdout, stderr = p.communicate()
    return stdout.decode('ascii', 'ignore')

print document_to_text('your_file_name','your_file_path')

Notice – New versions of python-docx removed this function. Make sure to pip install docx and not the new python-docx

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

How to retrieve SQL result column value using column name in Python?

You didn't provide many details, but you could try something like this:

# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table') 
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
    # Now you should be able to access the fields as properties of "row"
    myVar1 = row.field1
    myVar2 = row.field2
conn.close()

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Uncomment the line extension=php_mysql.dll in your "php.ini" file and restart Apache.

Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.

See more about installing MySQL extension in manual.

P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Insert an item into sorted list in Python

Use the insort function of the bisect module:

import bisect 
a = [1, 2, 4, 5] 
bisect.insort(a, 3) 
print(a)

Output

[1, 2, 3, 4, 5] 

How do I resolve a TesseractNotFoundError?

One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

why are there two different kinds of for loops in java?

The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E> interface ... which the article notes):

http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html

How to split() a delimited string to a List<String>

Include using namespace System.Linq

List<string> stringList = line.Split(',').ToList();

you can make use of it with ease for iterating through each item.

foreach(string str in stringList)
{

}

String.Split() returns an array, hence convert it to a list using ToList()

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

How to read file binary in C#?

using (FileStream fs = File.OpenRead(binarySourceFile.Path))
    using (BinaryReader reader = new BinaryReader(fs))
    {              
        // Read in all pairs.
        while (reader.BaseStream.Position != reader.BaseStream.Length)
        {
            Item item = new Item();
            item.UniqueId = reader.ReadString();
            item.StringUnique = reader.ReadString();
            result.Add(item);
        }
    }
    return result;  

how to deal with google map inside of a hidden div (Updated picture)

I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

Do I need a content-type header for HTTP GET requests?

Get requests should not have content-type because they do not have request entity (that is, a body)

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

How to validate phone number in laravel 5.2?

There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)

Can a Windows batch file determine its own file name?

Try to run below example in order to feel how the magical variables work.

@echo off

SETLOCAL EnableDelayedExpansion

echo Full path and filename: %~f0
echo Drive: %~d0
echo Path: %~p0
echo Drive and path: %~dp0
echo Filename without extension: %~n0
echo Filename with    extension: %~nx0
echo Extension: %~x0

echo date time : %~t0
echo file size: %~z0

ENDLOCAL

The related rules are following.

%~I         - expands %I removing any surrounding quotes ("")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

Remove blank attributes from an Object in Javascript

Remove all the properties with null and undefined

_x000D_
_x000D_
let obj = {
"id": 1,
"firstName": null,
"lastName": null,
"address": undefined,
"role": "customer",
"photo": "fb79fd5d-06c9-4097-8fdc-6cebf73fab26/fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg",
"location": null,
"idNumber": null,
};

   let result =  Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
console.log(result)
_x000D_
_x000D_
_x000D_

How to redirect the output of a PowerShell to a file during its execution

If you want to do it from the command line and not built into the script itself, use:

.\myscript.ps1 | Out-File c:\output.csv

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

Open a URL without using a browser from a batch file

You can use this command:

start /min iexplore http://www.google.com

With the use of /min, it will hit on the URL without opening in the browser.

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

What is an abstract class in PHP?

An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.

The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class

Abstract must contains the abstract method and those methods must be defined in its inheriting class.

How to set scope property with ng-init?

You are trying to read the set value before Angular is done assigning.

Demo:

var testController = function ($scope, $timeout) {
    console.log('test');
    $timeout(function(){
        console.log($scope.testInput);
    },1000);
}

Ideally you should use $watch as suggested by @Beterraba to get rid of the timer:

var testController = function ($scope) {
    console.log('test');
    $scope.$watch("testInput", function(){
        console.log($scope.testInput);
    });
}

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

Switch case on type c#

The simplest thing to do could be to use dynamics, i.e. you define the simple methods like in Yuval Peled answer:

void Test(WebControl c)
{
...
}

void Test(ComboBox c)
{
...
}

Then you cannot call directly Test(obj), because overload resolution is done at compile time. You have to assign your object to a dynamic and then call the Test method:

dynamic dynObj = obj;
Test(dynObj);

Jenkins fails when running "service start jenkins"

I was trying to install it in kubuntu 18.04, and i was already sure that i had java installed, I confirmed by trying

java -version

I got the output like that

java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Since I already know that my java PATH variables are defined in /etc/environment file, I added that file to the top of /etc/init.d/jenkins file

source /etc/environment

you can even remove the PATH from /etc/init.d/jenkins file, since it's already defined in /etc/environment

after that, i restarted my jenkins server,and it seemed to start working fine from localhost:8080

How to have click event ONLY fire on parent DIV, not children?

You can use bubbling in your favor:

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});

Pandas: Setting no. of max rows

Personally, I like setting the options directly with an assignment statement as it is easy to find via tab completion thanks to iPython. I find it hard to remember what the exact option names are, so this method works for me.

For instance, all I have to remember is that it begins with pd.options

pd.options.<TAB>

enter image description here

Most of the options are available under display

pd.options.display.<TAB>

enter image description here

From here, I usually output what the current value is like this:

pd.options.display.max_rows
60

I then set it to what I want it to be:

pd.options.display.max_rows = 100

Also, you should be aware of the context manager for options, which temporarily sets the options inside of a block of code. Pass in the option name as a string followed by the value you want it to be. You may pass in any number of options in the same line:

with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

It is still perfectly good to set options via pd.set_option. I just find using the attributes directly is easier and there is less need for get_option and set_option.

JavaScript Extending Class

Summary:

There are multiple ways which can solve the problem of extending a constructor function with a prototype in Javascript. Which of these methods is the 'best' solution is opinion based. However, here are two frequently used methods in order to extend a constructor's function prototype.

ES 2015 Classes:

_x000D_
_x000D_
class Monster {_x000D_
  constructor(health) {_x000D_
    this.health = health_x000D_
  }_x000D_
  _x000D_
  growl () {_x000D_
  console.log("Grr!");_x000D_
  }_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
class Monkey extends Monster {_x000D_
  constructor (health) {_x000D_
    super(health) // call super to execute the constructor function of Monster _x000D_
    this.bananaCount = 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
const monkey = new Monkey(50);_x000D_
_x000D_
console.log(typeof Monster);_x000D_
console.log(monkey);
_x000D_
_x000D_
_x000D_

The above approach of using ES 2015 classes is nothing more than syntactic sugar over the prototypal inheritance pattern in javascript. Here the first log where we evaluate typeof Monster we can observe that this is function. This is because classes are just constructor functions under the hood. Nonetheless you may like this way of implementing prototypal inheritance and definitively should learn it. It is used in major frameworks such as ReactJS and Angular2+.

Factory function using Object.create():

_x000D_
_x000D_
function makeMonkey (bananaCount) {_x000D_
  _x000D_
  // here we define the prototype_x000D_
  const Monster = {_x000D_
  health: 100,_x000D_
  growl: function() {_x000D_
  console.log("Grr!");}_x000D_
  }_x000D_
  _x000D_
  const monkey = Object.create(Monster);_x000D_
  monkey.bananaCount = bananaCount;_x000D_
_x000D_
  return monkey;_x000D_
}_x000D_
_x000D_
_x000D_
const chimp = makeMonkey(30);_x000D_
_x000D_
chimp.growl();_x000D_
console.log(chimp.bananaCount);
_x000D_
_x000D_
_x000D_

This method uses the Object.create() method which takes an object which will be the prototype of the newly created object it returns. Therefore we first create the prototype object in this function and then call Object.create() which returns an empty object with the __proto__ property set to the Monster object. After this we can initialize all the properties of the object, in this example we assign the bananacount to the newly created object.

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

How to Select a substring in Oracle SQL up to a specific character?

You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.

  1  select 'ABC_blahblahblah' test_string,
  2         instr('ABC_blahblahblah','_',1,1) position_underscore,
  3         substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
  4*   from dual
SQL> /

TEST_STRING      POSITION_UNDERSCORE RES
---------------- ------------------  ---
ABC_blahblahblah                  4  ABC

Instr documentation

Susbtr Documentation

Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
        (function(j){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
        })(i);
  }

That should work; however, you should never create a function in a loop. Therefore,

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

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);
  }

Changing the selected option of an HTML Select element

I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.

Simplest code that worked is below:

var newValue1 = 'Mango'

var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;

Hope that helps someone. Best of luck.
Up vote if this helped you.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

Numpy how to iterate over columns of array?

You can also use unzip to iterate through the columns

for col in zip(*array):
   some_function(col)

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

jQuery select element in parent window

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

How to create an array of 20 random bytes?

If you are already using Apache Commons Lang, the RandomUtils makes this a one-liner:

byte[] randomBytes = RandomUtils.nextBytes(20);

Note: this does not produce cryptographically-secure bytes.

Pandas: change data type of Series to String

You can convert all elements of id to str using apply

df.id.apply(str)

0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610

Edit by OP:

I think the issue was related to the Python version (2.7.), this worked:

df['id'].astype(basestring)
0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610
Name: id, dtype: object

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

Run PHP Task Asynchronously

Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.

If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.

Regular expression for excluding special characters

Why do you consider regex the best tool for this? If your purpose is to detect whether an illegal character is present in a string, testing each character in a loop will be both simpler and more efficient than constructing a regex.

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

AngularJS format JSON string output

I guess you want to use to edit the json text. Then you can use ivarni's way:

{{data | json}}
and add an adition attribute to make
 editable

<pre contenteditable="true">{{data | json}}</pre>

Hope this can help you.

How to concatenate multiple column values into a single column in Panda dataframe

The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:

Reduce does a lot better:

from functools import reduce

import pandas as pd

# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'


def reduce_join(df, columns):
    assert len(columns) > 1
    slist = [df[x].astype(str) for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])


def apply_join(df, columns):
    assert len(columns) > 1
    return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)

# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)

# profile
%timeit df1 = reduce_join(df, list('1234'))  # 733 ms
%timeit df2 = apply_join(df, list('1234'))   # 8.84 s

Change windows hostname from command line

Why be easy when it can be complicated? Why use third-party applications like netdom.exe when correct interogations is the way? Try 2 interogations:

wmic computersystem where caption='%computername%' get caption, UserName, Domain /format:value

wmic computersystem where "caption like '%%%computername%%%'" get caption, UserName, Domain /format:value

or in a batch file use loop

for /f "tokens=2 delims==" %%i in ('wmic computersystem where "Caption like '%%%currentname%%%'" get UserName /format:value') do (echo. UserName- %%i)

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

client denied by server configuration

In my case, I modified directory tag.

From

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

To

<Directory "D:/Devel/matysart/matysart_dev1">
  Require local
</Directory>

And it seriously worked. It's seems changed with Apache 2.4.2.

Create a HTML table where each TR is a FORM

If you need form inside tr and inputs in every td, you can add form in td tag, and add attribute 'form' that contains id of form tag to outside inputs. Something like this:

<tr>
  <td>
    <form id='f1'>
      <input type="text">
    </form>
  </td>
  <td>
    <input form='f1' type="text">
  </td>
</tr>

When should an Excel VBA variable be killed or set to Nothing?

VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.

Object variables are guaranteed to be cleaned (set to Nothing) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.

There are only two cases when you want an explicit cleanup:

  1. When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).

  2. When you have a circular reference between two or more objects.

    If objectA stores a references to objectB, and objectB stores a reference to objectA, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing.

The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.

If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.).

If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.).

Access level of a variable (public vs. private) does not affect its life time.

Best font for coding

Inconsolata (http://www.levien.com/type/myfonts/inconsolata.html) is a great monospaced font for programming. Earlier versions tend to act weird on OS X, but the newer versions work out very well.

Select arrow style change

This would work well especially for those using Bootstrap, tested in latest browser versions:

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  /* Some browsers will not display the caret when using calc, so we put the fallback first */ _x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */_x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */_x000D_
}_x000D_
/*For IE*/_x000D_
select::-ms-expand { display: none; }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-6">_x000D_
      <select class="form-control">_x000D_
       <option>Option 1</option>_x000D_
       <option>Option 2</option>_x000D_
       <option>Option 3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot find Microsoft.Office.Interop Visual Studio

I had the same issue with Visual Studio Community 2013, I fixed it downloading and installing the latest update of Office Developer Tools for Visual Studio 2013. Now I am able to see the whole Microsoft.Office.Interop.* list when I go to

Add References > Assemblies > Extensions

you can download it from here:

https://www.visualstudio.com/en-us/news/vs2013-update4-rtm-vs.aspx#Office
http://aka.ms/OfficeDevToolsForVS2013

Which JRE am I using?

The Java system property System.getProperty(...) to consult is "java.runtime.name". This will distinguish between "OpenJDK Runtime Environment" and "Java(TM) SE Runtime Environment". They both have the same vendor - "Oracle Corporation".

This property is also included in the output for java -version.

C-like structures in Python

Perhaps you are looking for Structs without constructors:

class Sample:
  name = ''
  average = 0.0
  values = None # list cannot be initialized here!


s1 = Sample()
s1.name = "sample 1"
s1.values = []
s1.values.append(1)
s1.values.append(2)
s1.values.append(3)

s2 = Sample()
s2.name = "sample 2"
s2.values = []
s2.values.append(4)

for v in s1.values:   # prints 1,2,3 --> OK.
  print v
print "***"
for v in s2.values:   # prints 4 --> OK.
  print v

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Creating a constant Dictionary in C#

I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.

Example:

public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
        {
            { "Reference1", Array1 },
            { "Reference2", Array2 },
            { "Reference3", Array3 },
            { "Reference4", Array4 },
            { "Reference5", Array5 }
        };

C# Generics and Type Checking

I hope you find this helpful:

  • typeof(IList<T>).IsGenericType == true
  • typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
  • typeof(IList<int>).GetGenericArguments()[0] == typeof(int)

https://dotnetfiddle.net/5qUZnt

Android WebView Cookie Problem

I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").

Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.

how to get right offset of an element? - jQuery

Just an addition to what Greg said:

$("#whatever").offset().left + $("#whatever").outerWidth()

This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right property) then an addition to the code is necessary as follows:

$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())

This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right property in CSS.

How do I separate an integer into separate digits in an array in JavaScript?

Update with string interpolation in ES2015.

const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]

What is the difference between max-device-width and max-width for mobile web?

max-device-width is the device rendering width

@media all and (max-device-width: 400px) {
    /* styles for devices with a maximum width of 400px and less
       Changes only on device orientation */
}

@media all and (max-width: 400px) {
    /* styles for target area with a maximum width of 400px and less
       Changes on device orientation , browser resize */
}

The max-width is the width of the target display area means the current size of browser.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Just had this problem myself and accepted answer didn't help me but I solved it with:

Add reference > Browse > C: > Windows > assembly > GAC > Microsoft.Office.Interop.Excel > 12.0.0.0_etc > Microsoft.Office.Interop.Excel.dll

How to call any method asynchronously in c#

Here's a way to do it:

// The method to call
void Foo()
{
}


Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);

Of course you need to replace Action by another type of delegate if the method has a different signature

Change Default branch in gitlab

To change the default branch in Gitlab 7.7.2:

  • Click Settings in the left-hand bar
  • Change the Default Branch to the desired branch
  • Click Save Changes.

How to get the list of files in a directory in a shell script?

for entry in "$search_dir"/*
do
  echo "$entry"
done

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

How to center a label text in WPF?

You have to use HorizontalContentAlignment="Center" and! Width="Auto".

Comparing mongoose _id and strings

ObjectIDs are objects so if you just compare them with == you're comparing their references. If you want to compare their values you need to use the ObjectID.equals method:

if (results.userId.equals(AnotherMongoDocument._id)) {
    ...
}

Select the first row by group

(1) SQLite has a built in rowid pseudo-column so this works:

sqldf("select min(rowid) rowid, id, string 
               from test 
               group by id")

giving:

  rowid id string
1     1  1      A
2     3  2      B
3     5  3      C
4     7  4      D
5     9  5      E

(2) Also sqldf itself has a row.names= argument:

sqldf("select min(cast(row_names as real)) row_names, id, string 
              from test 
              group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

(3) A third alternative which mixes the elements of the above two might be even better:

sqldf("select min(rowid) row_names, id, string 
               from test 
               group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

Note that all three of these rely on a SQLite extension to SQL where the use of min or max is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

I had a similar issue when using AD on CAS , i.e. 52e error, In my case application accepts the Full Name when in the form of CN= instead of the actual username.

For example, if you had a user who's full name is Ross Butler and their login username is rbutler --you would normally put something like, cn=rbutler,ou=Users,dc=domain,dc=com but ours failed everytime. By changing this to cn=Ross Butler,ou=Users,dc=domain,dc=com it passed!!

Redirect stderr to stdout in C shell

As paxdiablo said you can use >& to redirect both stdout and stderr. However if you want them separated you can use the following:

(command > stdoutfile) >& stderrfile

...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

Wait for page load in Selenium

Use:

driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);

Which means any search for the elements on the web page could take time to load. The implicitlyWait is set before throwing an exception. The TimeUnit displays whichever way you want to wait in (seconds, minutes, hours and days).

Bootstrap - dropdown menu not working?

Check if you're referencing jquery.js BEFORE bootstrap.js and bootstrap.js is loaded only once. That fixed the same error for me:

<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>

How to convert C# nullable int to int

If you know that v1 has a value, you can use the Value property:

v2 = v1.Value;

Using the GetValueOrDefault method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:

v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value

v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value

You can use the HasValue property to check if v1 has a value:

if (v1.HasValue) {
  v2 = v1.Value;
}

There is also language support for the GetValueOrDefault(T) method:

v2 = v1 ?? -1;

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How to disable Compatibility View in IE

If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1") in a code block in _Layout to work quite well:

@Code
    Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else

Setting the correct encoding when piping stdout in Python

First, regarding this solution:

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.

A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

Here is my easy solution for this:

Click on Gradle button, you can find at the right side top. you will see all the gradle files. Now go to android, and double click on signingReport. Once the gradle build finishes, you see the SHA key. Check the below images for step by step guide.

Once you click on Gradle check the below images. Hope this helps someone.

STEP 1:

Image Step one

STEP 2:

Image Step two

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8)